diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py new file mode 100644 index 0000000..d7cb60f --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -0,0 +1,790 @@ +"""Rams and linkages across a one-axis hinge: numpy and the standard library only, and nothing from the package, so +a rig, a runtime or a test loads this file alone. Signed, the mesh oracle, asks for Blender's BVH tree when one is +made and not before. + +A Mechanism is the record of one hinge's drive: the hinge (pivot, unit axis, lo and hi in degrees, positive +right-handed about the axis), a kind, and pins, each in its own body's rest frame (the pose at angle 0, where +every body's frame is the parent's). + + direct the ram runs from a on the parent to b on the child. + four_bar a rocker pinned on the parent at `rocker` (R) carries the pin p; a coupler joins p to c on the child; + the ram runs from a on the parent to d on the rocker, and d is p (the excavator bucket linkage). + bell_crank the same loop with d elsewhere on the rocker. + +Every pose quantity is a pure function of (record, angle): pose() holds no solve state. The loop is solved in the +plane across the axis; a pin's coordinate along the axis only says where its member stands: the rocker bars at R's, +the coupler bar at c's, the ram at a's plus each of `offsets`. + + pose(m, degrees) every body's rotation, the ram's base and eye, L, dL/dtheta, per angle + length(m, degrees) pin-to-pin ram length + barrel_length(m, ram) the barrel the range's shorter end leaves room for + extension(m, ram, degrees) rod extension from closed + fit(m, ram, ...) the gates over the range: assembly, stroke, arm, load, clearance + clearance(m, ram, degrees, distance) the clearance gate's reading at any angles, per member and part + search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss + record(m, ram), from_record the JSON record a rig or runtime drives from + swept(fit, body, ...) points of the swept ram's surface in a body's rest frame + Signed(shells, cap) the distance oracle over closed meshes, signed by three rays + +Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame +it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`: +for each member of MEMBERS[kind], zones (part, pin, radius, depth). Every member meets every part. A zone lowers +what the member's samples keep from one part, and only within `radius` of the axis of `pin`, one of the member's +own (RIDES), measured across the hinge axis: there a sample may come as near the part as -depth and no nearer. +depth is 0 for what is stacked beside the member on the pin (a plate, the bracket or horn the pin stands in: the +member's axis stays outside it, so a pin whose place along the axis is inside the part it claims to stand beside +is refused), the pin's radius for the pin through the member's eye, half the thickness for the member's own plate +or clevis. Beyond the radius the pair is checked like any other; nothing is exempt by a name, a length or the +member's own body. Every body of the kind owns at least one part, or the gate refuses. + +A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin +to pin (a bar's between its pins; the ram's at the most its pins allow), which the record refuses by its pins +alone; its depth is no more than the member's eye on that pin (Ram.eye: e_a at the base, e_b at the rod's eye, +link_r on a bar), which from_record and the gate refuse, a world's answer included. Between two samples of which +either is in a zone, the gate does not trust the spacing: it halves the segment until the readings at its ends +prove it holds -depth throughout (see _between), so a part of any thickness that the axis crosses there is read. + +The oracle is distance(part, points) -> distances, points (N, 3) in the rest frame of the part's body. A distance +is signed: negative inside the part, by any depth. The oracle may cap what it returns at Ram.reach(spacing), +outside a part only: a point inside reads negative however deep it lies. An oracle that cannot tell inside from +outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here. It never reads +more than the true distance: the gate's proof between samples is that a distance changes by no more than the way +between two points. + +A RamError of a gate (assembly, stroke, toggle, arm, load, clash) names the angle and the pin; one of the record +or of a call (an unknown kind, a range, a grid over the limit, a version) names the pin or the field it refuses. +""" +import math +from dataclasses import dataclass, field, fields, replace + +import numpy as np + +KINDS = ("direct", "four_bar", "bell_crank") +BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker", "coupler"), + "bell_crank": ("parent", "child", "rocker", "coupler")} +PINS = {"direct": ("a", "b"), "four_bar": ("a", "rocker", "p", "c", "d"), "bell_crank": ("a", "rocker", "p", "c", "d")} +MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker", "coupler"), + "bell_crank": ("barrel", "rod", "rocker", "coupler", "rocker arm")} +EYE = {"direct": "b", "four_bar": "d", "bell_crank": "d"} # the pin the rod's eye rides +RIDES = {kind: {"barrel": ("a", EYE[kind]), "rod": ("a", EYE[kind]), "rocker": ("rocker", "p"), "coupler": ("p", "c"), "rocker arm": ("rocker", "d")} + for kind in KINDS} # member -> the pins at its start and its end +GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") +SCHEMA, VERSION = "brokkr.ram", 1 +ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it +COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version +BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler +FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE +RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order + + +class RamError(ValueError): + """A refusal: the mechanism kind, the gate, the angle and the pin it failed at. `fit` holds the readings when + the gates got far enough to take them.""" + + def __init__(self, kind, gate, message, angle=None, pin=None, fit=None): + where = (f" at {angle:g} deg" if angle is not None else "") + (f" (pin {pin})" if pin else "") + super().__init__(f"{kind} ram: {gate}{where}: {message}") + self.kind, self.gate, self.angle, self.pin, self.fit = kind, gate, angle, pin, fit + + +def _number(kind, name, value, least=None): + """A record's number: an int or a float, finite, never a bool, a string or null; above `least` when given.""" + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise RamError(kind, "record", f"a finite number, got {value!r}", pin=name) + if least is not None and not value > least: + raise RamError(kind, "record", f"a number greater than {least:g}, got {value!r}", pin=name) + return float(value) + + +@dataclass +class Ram: + """A ram's proportions. Lengths default from the bore radius. Every one is a finite number and the bore is + greater than 0, or the ram is refused naming the field (as the ram of `any` kind: a ram knows none).""" + bore: float + rod: float = None # rod radius + barrel_r: float = None # barrel outer radius + e_a: float = None # base pin centre to the barrel's back end + e_b: float = None # rod eye centre to the rod's shoulder (what stays out of the barrel, closed) + gland: float = None # piston and gland: barrel length that is not stroke + over: float = None # spare travel at each end of the stroke + tail: float = 0.0 # trunnion mount: barrel behind the base pin (replaces e_a) + min_arm: float = None # least effective arm |dL/dtheta|, length per radian + gap: float = None # least clearance to a body + link_r: float = None # half thickness of a rocker or coupler bar + max_load: float = 3.0 # greatest coupler pin load per unit ram force + + def __post_init__(self): + b = self.bore = _number("any", "bore", self.bore, 0.0) + for name, value in (("rod", 0.5 * b), ("barrel_r", 1.25 * b), ("e_a", 1.7 * b), ("e_b", 1.7 * b), ("gland", 1.3 * b), + ("over", 0.2 * b), ("min_arm", 1.5 * b), ("gap", 0.15 * b), ("link_r", 0.7 * b)): + if getattr(self, name) is None: + setattr(self, name, value) + for f in fields(self): + setattr(self, f.name, _number("any", f.name, getattr(self, f.name))) + + @property + def back(self): + """Signed distance from the base pin to the barrel's back end along the ram (negative: behind the pin).""" + return -self.tail if self.tail > 0 else self.e_a + + def spacing(self, spacing=None): + return self.barrel_r if spacing is None else float(spacing) + + def eye(self, member, pin): + """The radius of a member's eye on one of its pins: the most a zone's depth lets its axis into a part.""" + if member in ("barrel", "rod"): + return self.e_a if pin == "a" else self.e_b + return self.link_r + + def reach(self, spacing=None): + """The greatest distance the clearance gate asks of any member: what a distance oracle may cap at.""" + return max(self.barrel_r, self.rod, self.link_r) + self.gap + self.spacing(spacing) / 2 + + +def _flat(v, n): + """v without its part along the unit axis n.""" + return v - n * (v @ n)[..., None] + + +def _rot(v, n, t): + """v (..., 3) turned about the unit axis n by t radians (Rodrigues); t broadcasts over v's leading shape.""" + t = np.asarray(t, dtype=float)[..., None] + return v * np.cos(t) + np.cross(n, v) * np.sin(t) + n * (v @ n)[..., None] * (1.0 - np.cos(t)) + + +def _angle(v0, v, n): + """Signed angle about n from v0 to v, both across n.""" + return np.arctan2(np.cross(v0, v) @ n, v @ v0) + + +@dataclass +class Mechanism: + kind: str + pivot: np.ndarray + axis: np.ndarray + lo: float + hi: float + a: np.ndarray + b: np.ndarray = None + rocker: np.ndarray = None + p: np.ndarray = None + c: np.ndarray = None + d: np.ndarray = None + offsets: tuple = (0.0,) + parts: dict = field(default_factory=dict) # part -> the body it turns with + touch: dict = field(default_factory=dict) # member -> zones (part, pin, radius, depth) + + def __post_init__(self): + if self.kind not in KINDS: + raise RamError(str(self.kind), "record", f"kind is one of {', '.join(KINDS)}") + for name in ("pivot", "axis", "a", "b", "rocker", "p", "c", "d"): + value = getattr(self, name) + if value is not None: + value = np.array(value, dtype=float) + if value.shape != (3,) or not np.isfinite(value).all(): + raise RamError(self.kind, "record", "three finite numbers", pin=name) + setattr(self, name, value) + if abs(np.linalg.norm(self.axis) - 1.0) > 1e-6: + raise RamError(self.kind, "record", f"the axis is a unit vector, length {np.linalg.norm(self.axis):.6f}", pin="axis") + self.lo, self.hi = float(self.lo), float(self.hi) + if not self.lo < self.hi or self.hi - self.lo > 360.0: + raise RamError(self.kind, "record", f"lo < hi and hi - lo <= 360, got {self.lo:g}..{self.hi:g}", angle=self.lo) + self.offsets = tuple(float(o) for o in self.offsets) + if not self.offsets: + raise RamError(self.kind, "record", "at least one offset: where the ram stands along the axis from a", pin="a") + self.parts = {str(part): body for part, body in dict(self.parts).items()} + for part, body in self.parts.items(): + if body not in BODIES[self.kind]: + raise RamError(self.kind, "record", f"part {part!r} turns with {body!r}; this kind has {', '.join(BODIES[self.kind])}") + for name in ("a", "b", "rocker", "p", "c", "d"): + needed, given = name in PINS[self.kind], getattr(self, name) is not None + if needed != given: + raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name) + touch = {} + for member, zones in dict(self.touch).items(): + if member not in MEMBERS[self.kind]: + raise RamError(self.kind, "record", f"touch names {member!r}; this kind's members are {', '.join(MEMBERS[self.kind])}") + touch[member] = [] + for zone in zones: + if isinstance(zone, (str, dict)) or len(zone) != 4: + raise RamError(self.kind, "record", f"{member}'s zone is (part, pin, radius, depth), got {zone!r}") + part, pin, radius, depth = zone + if part not in self.parts: + raise RamError(self.kind, "record", f"{member} may touch {part!r}, which is no part of the record") + if pin not in RIDES[self.kind][member]: + raise RamError(self.kind, "record", f"{member} may touch {part!r} about a pin it rides ({', '.join(RIDES[self.kind][member])}), not {pin!r}", pin=str(pin)) + radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth) + if depth < 0.0: + raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth") + span = _span(self, member) + for name, value in (("radius", radius), ("depth", depth)): + if value > span: + raise RamError(self.kind, "record", f"a zone no wider or deeper than its member: {member} is at most {span:.4f} from pin to pin, got {value!r}", + pin=f"{member} {part} {name}") + touch[member].append((part, pin, radius, depth)) + touch[member] = tuple(touch[member]) + self.touch = touch + if self.kind == "direct": + return + n = self.axis + apart = float(np.linalg.norm(self.d - self.p)) + if self.kind == "four_bar" and apart > 0.0: + raise RamError(self.kind, "record", f"a four-bar's ram eye is the rocker's coupler pin; d is {apart:.4f} from p", pin="d") + if self.kind == "bell_crank" and apart == 0.0: + raise RamError(self.kind, "record", "a bell crank's ram eye stands off the coupler pin; d on p is a four_bar", pin="d") + self.lr = float(np.linalg.norm(_flat(self.p - self.rocker, n))) + self.lc = float(np.linalg.norm(_flat(self.p - self.c, n))) + side = float(n @ np.cross(_flat(self.c - self.rocker, n), _flat(self.p - self.rocker, n))) + if min(self.lr, self.lc) < BAND or abs(side) < BAND: + raise RamError(self.kind, "assembly", "the rest pose is a dead centre: R, p and c are in line", pin="p") + self.branch = 1.0 if side > 0 else -1.0 # which side of R -> c the pin p keeps, through the whole range + + +def _span(m, member): + """The most a member measures from pin to pin, by the pins alone: a bar's length across the axis; for the ram's + two, the base's and the eye's distances from the centre the eye turns about, added.""" + if member in ("barrel", "rod"): + centre, eye = m.pivot if m.kind == "direct" else m.rocker, getattr(m, EYE[m.kind]) + return float(np.linalg.norm(m.a - centre) + np.linalg.norm(eye - centre)) + start, end = RIDES[m.kind][member] + return float(np.linalg.norm(_flat(getattr(m, end) - getattr(m, start), m.axis))) + + +def _eyes(m, ram): + """Refuse a zone deeper than its member's eye on its pin.""" + for member, zones in m.touch.items(): + for part, pin, _, depth in zones: + if depth > ram.eye(member, pin): + raise RamError(m.kind, "record", f"a zone no deeper than its member's eye: {member}'s on {pin} is {ram.eye(member, pin):.4f}, got {depth!r}", + pin=f"{member} {part} depth") + + +@dataclass +class Pose: + degrees: np.ndarray # (S,) + base: np.ndarray # (S, 3) ram base pin, parent frame, at offset 0 + eye: np.ndarray # (S, 3) ram eye + u: np.ndarray # (S, 3) unit vector base -> eye + L: np.ndarray # (S,) pin to pin + dL: np.ndarray # (S,) dL/dtheta, length per radian: the effective arm, signed + phi: np.ndarray = None # (S,) rocker angle from rest, radians, in (-pi, pi] + psi: np.ndarray = None # (S,) coupler angle from rest + dphi: np.ndarray = None # (S,) dphi/dtheta + P: np.ndarray = None # (S, 3) the rocker's coupler pin + C: np.ndarray = None # (S, 3) the child's coupler pin + load: np.ndarray = None # (S,) coupler pin load per unit ram force + mu_c: np.ndarray = None # (S,) transmission angle at c, degrees, folded to 0..90 + mu_p: np.ndarray = None # (S,) transmission angle at p + + +def pose(m, degrees): + """The mechanism at each of `degrees` (a number or an array): a pure function of the record and the angle.""" + deg = np.atleast_1d(np.asarray(degrees, dtype=float)) + t, n, O = np.radians(deg), m.axis, m.pivot + if m.kind == "direct": + eye = O + _rot(m.b - O, n, t) + base = np.broadcast_to(m.a, eye.shape) + L = np.linalg.norm(eye - base, axis=1) + u = (eye - base) / np.maximum(L, 1e-12)[:, None] + return Pose(deg, base, eye, u, L, (np.cross(n, eye - O) * u).sum(axis=1)) + R = m.rocker + C = O + _rot(m.c - O, n, t) + g = _flat(C - R, n) + dist = np.linalg.norm(g, axis=1) + lo, hi = abs(m.lr - m.lc) + BAND, m.lr + m.lc - BAND + bad = (dist <= lo) | (dist >= hi) + if bad.any(): + i = int(np.argmax(bad)) + raise RamError(m.kind, "assembly", f"|c - R| is {dist[i]:.4f}, outside ({lo:.4f}, {hi:.4f}): the rocker ({m.lr:.4f}) and coupler " + f"({m.lc:.4f}) cannot close the loop, or reach a dead centre where the branch would change", angle=float(deg[i]), pin="c") + x = (m.lr * m.lr - m.lc * m.lc + dist * dist) / (2.0 * dist) + h = np.sqrt(np.maximum(m.lr * m.lr - x * x, 0.0)) + across = g / dist[:, None] + v = across * x[:, None] + m.branch * np.cross(n, across) * h[:, None] # p - R across the axis + phi = _angle(_flat(m.p - R, n), v, n) + P = R + _rot(m.p - R, n, phi) + eye = R + _rot(m.d - R, n, phi) + w = _flat(P - C, n) # the coupler, c -> p + k = w / np.linalg.norm(w, axis=1)[:, None] + psi = _angle(_flat(m.p - m.c, n), w, n) + # the coupler's two ends move equally along it + dphi = (np.cross(n, C - O) * k).sum(axis=1) / (np.cross(n, P - R) * k).sum(axis=1) + base = np.broadcast_to(m.a, eye.shape) + L = np.linalg.norm(eye - base, axis=1) + u = (eye - base) / np.maximum(L, 1e-12)[:, None] + dL = (np.cross(n, eye - R) * u).sum(axis=1) * dphi + crank, link = _flat(O - C, n), _flat(R - P, n) + moment = np.abs(np.cross(-crank, k) @ n) + load = np.abs(dL) / np.maximum(moment, 1e-12) + mu_c = np.degrees(np.arcsin(np.clip(moment / np.linalg.norm(crank, axis=1), 0.0, 1.0))) + mu_p = np.degrees(np.arcsin(np.clip(np.abs(np.cross(link, k) @ n) / np.linalg.norm(link, axis=1), 0.0, 1.0))) + return Pose(deg, base, eye, u, L, dL, phi, psi, dphi, P, C, load, mu_c, mu_p) + + +def length(m, degrees): + """Pin-to-pin ram length at each angle.""" + return pose(m, degrees).L + + +def barrel_length(m, ram): + """The barrel the mechanism leaves room for: the ram's length at the shorter end of the range, less the + overtravel, the base clevis (or nothing, on a trunnion) and the eye. L runs one way over a range that fits + (the toggle gate), so that end is the least. Derived, never stored: a record holds the pins and the ram.""" + return _barrel(ram, pose(m, (m.lo, m.hi)).L) + + +def _barrel(ram, ends): + return float(min(ends[0], ends[-1])) - ram.over - ram.back - ram.e_b + + +def extension(m, ram, degrees): + """Rod extension from closed at each angle: L - (back + barrel + e_b).""" + return pose(m, degrees).L - (ram.back + barrel_length(m, ram) + ram.e_b) + + +def _members(m, ram, barrel, p): + """(member, label, start (S, 3), end (S, 3), radius, (pin at start, pin at end)) of every member in the parent + frame, each from pin to pin: the barrel from its back end, the rod to the eye, a bar between its pins.""" + n, rides = m.axis, RIDES[m.kind] + for off in m.offsets: + base, tip = p.base + off * n, p.eye + off * n + front = base + p.u * (ram.back + max(barrel, 1e-6)) + yield "barrel", f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, rides["barrel"] + yield "rod", f"rod[{off:g}]", front, tip, ram.rod, rides["rod"] + if m.kind == "direct": + return + R = np.broadcast_to(m.rocker, p.P.shape) + yield "rocker", "rocker", R, p.P - n * ((p.P - R) @ n)[:, None], ram.link_r, rides["rocker"] + yield "coupler", "coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, ram.link_r, rides["coupler"] + if m.kind == "bell_crank": + yield "rocker arm", "rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], ram.link_r, rides["rocker arm"] + + +def _into(m, p, body, pts): + """Parent-frame points (S, N, 3) carried into a body's rest frame at each angle.""" + n = m.axis + if body == "parent": + return pts + if body == "child": + return m.pivot + _rot(pts - m.pivot, n, -np.radians(p.degrees)[:, None]) + if body == "rocker": + return m.rocker + _rot(pts - m.rocker, n, -p.phi[:, None]) + return m.p + _rot(pts - p.P[:, None, :], n, -p.psi[:, None]) + + +@dataclass +class Clearance: + margin: np.ndarray # (S,) the least margin of any checked pair at each angle + where: tuple # (angle, member label, part, pin) of the least: the pin is the member's nearer one + pairs: dict # (member label, part) -> (least margin, angle) of every pair: every member, every part + allowed: list # (member label, part) of every pair a zone of the record's `touch` lets near a pin + + +def clearance(m, ram, degrees, distance, spacing=None): + """The clearance gate's reading. A member is clear where margin >= 0: each sample of its axis, taken at most + `spacing` apart (default barrel_r), is at least radius + gap + spacing / 2 from every part, measured in the + rest frame of the part's body at that angle. A sample is at most spacing / 2 from any point of the axis, so + the member's surface keeps the gap. Every member meets every part of the record. Inside a zone of `touch` + (within its radius of its pin's axis, across the hinge axis) a sample keeps -depth from the zone's part + instead: the margin there is the distance plus the depth, and the segment to the next sample is proved to + hold -depth throughout (_between). Two zones of one pair that both reach a sample let it the deeper.""" + return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing) + + +def _between(kind, distance, part, pts, got, keep, zoned, floor): + """(S,) the least margin found between samples, inf where none is: for each segment between consecutive samples + of which either is in a zone, whether the axis holds -depth (the deeper of its ends') all along it. A distance + changes by no more than the way between two points, so along a segment it is at least (g(a) + g(b) - |ab|) / 2; + where that does not prove the segment it is halved, the midpoint read (its margin is counted), down to `floor`. + A segment still unproved at the floor against a part the axis is held outside (depth 0) reads that bound, so + it is refused: the part is within floor / 2 of the axis there, crossed or touched. Against a part the axis may + enter, the samples' readings stand: a burial is read to floor / 2.""" + out = np.full(len(pts), math.inf) + pair = zoned[:, :-1] | zoned[:, 1:] + row = np.nonzero(pair)[0] + a, b, ga, gb = pts[:, :-1][pair], pts[:, 1:][pair], got[:, :-1][pair], got[:, 1:][pair] + hold = np.minimum(keep[:, :-1], keep[:, 1:])[pair] + while len(row): + span = np.linalg.norm(b - a, axis=1) + bound = (ga + gb - span) / 2.0 + unproved = (bound < hold) & (np.minimum(ga, gb) >= hold) # an end under its hold is already refused + touched = unproved & (span <= floor) & (hold == 0.0) + np.minimum.at(out, row[touched], bound[touched]) + go = unproved & (span > floor) + if not go.any(): + break + a, b, ga, gb, hold, row = (x[go] for x in (a, b, ga, gb, hold, row)) + mid = (a + b) / 2.0 + gm = np.asarray(distance(part, mid), dtype=float) + if np.isnan(gm).any(): + raise RamError(kind, "oracle", f"the distance oracle answered nan for part {part!r}") + np.minimum.at(out, row, gm - hold) + a, b, ga, gb = np.concatenate([a, mid]), np.concatenate([mid, b]), np.concatenate([ga, gm]), np.concatenate([gm, gb]) + hold, row = np.concatenate([hold, hold]), np.concatenate([row, row]) + return out + + +def _clearance(m, ram, barrel, p, distance, spacing): + _eyes(m, ram) + for body in BODIES[m.kind]: + if body not in m.parts.values(): + raise RamError(m.kind, "record", f"no part turns with body {body}: the clearance gate would pass it unseen") + step = ram.spacing(spacing) + out = Clearance(np.full(len(p.degrees), math.inf), None, {}, []) + least = math.inf + at = {"a": p.base, EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C} # each pin over the angles, parent frame + for member, label, start, end, radius, pins in _members(m, ram, barrel, p): + count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2) + pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] + need = radius + ram.gap + step / 2.0 + seen = {} + for part, body in m.parts.items(): + if body not in seen: + seen[body] = _into(m, p, body, pts).reshape(-1, 3) + got = np.asarray(distance(part, seen[body]), dtype=float).reshape(len(p.degrees), count) + if np.isnan(got).any(): + raise RamError(m.kind, "oracle", f"the distance oracle answered nan for part {part!r}") + keep = np.full(got.shape, need) # what each sample keeps from the part + zoned = np.zeros(got.shape, dtype=bool) + zones = [zone for zone in m.touch.get(member, ()) if zone[0] == part] + for _, pin, reach, depth in zones: + across = np.linalg.norm(_flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2) + keep = np.where(across <= reach, np.minimum(keep, -depth), keep) + zoned |= across <= reach + over = got - keep + row = over.min(axis=1) + if zones: + out.allowed.append((label, part)) + row = np.minimum(row, _between(m.kind, distance, part, seen[body].reshape(len(p.degrees), count, 3), got, keep, zoned, step / FINE)) + out.margin = np.minimum(out.margin, row) + i = int(np.argmin(row)) + out.pairs[(label, part)] = (float(row[i]), float(p.degrees[i])) + if row[i] < least: + least = float(row[i]) + out.where = (float(p.degrees[i]), label, part, pins[int(np.argmin(over[i])) * 2 >= count]) + return out + + +@dataclass +class Fit: + m: Mechanism + ram: Ram + why: list # (gate, angle, pin, message) of every gate that failed; empty when it fits + degrees: np.ndarray + l_min: float + l_max: float + travel: float # L_max - L_min + barrel: float # barrel length: barrel_length(m, ram) + closed: float # pin to pin with the rod home: back + barrel + e_b + stroke: float # travel the barrel holds + spare: float # stroke - (travel + 2 over): negative when the stroke does not fit + arm_min: float # least |dL/dtheta| + arm_at: float # the angle of it + arm_sign: int # 0 when dL/dtheta changes sign (a dead centre inside the range) + swing: float = 0.0 # the rocker's travel, degrees + load_max: float = 0.0 # greatest coupler pin load per unit ram force + mu_c: float = None # least transmission angle at c, degrees: reported, never gated + mu_p: float = None # least transmission angle at p + clear_min: float = math.inf # least clearance beyond what the gate asks; inf with no oracle + clear_at: tuple = None # (angle, member, part, pin) of it + pairs: dict = field(default_factory=dict) # (member, part) -> (least margin, angle) of every pair + allowed: list = field(default_factory=list) # (member, part) of every pair a zone of `touch` lets near a pin + table: list = field(default_factory=list) # (angle, L, dL/dtheta, clearance margin) per step + + @property + def ok(self): + return not self.why + + def error(self): + gate, angle, pin, message = self.why[0] + return RamError(self.m.kind, gate, message, angle=angle, pin=pin, fit=self) + + def report(self): + """One line for a log or a sheet.""" + state = "OK" if self.ok else "NO (" + "; ".join(f"{g}: {msg}" for g, _, _, msg in self.why) + ")" + links = "" if self.m.kind == "direct" else f", rocker swing {self.swing:.1f}, pin load <= {self.load_max:.2f}, transmission >= {min(self.mu_c, self.mu_p):.1f} deg" + return (f"{state}: L {self.l_min:.3f}..{self.l_max:.3f}, barrel {self.barrel:.3f}, stroke {self.stroke:.3f} for travel {self.travel:.3f} " + f"(spare {self.spare:+.3f}), arm >= {self.arm_min:.3f}{links}, clear {self.clear_min:+.3f}") + + +def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True): + """Every gate's reading; raises only where the loop does not assemble or a bell crank's eye crowds its pin.""" + if m.kind == "bell_crank" and np.linalg.norm(m.d - m.p) < 2.0 * ram.bore: + raise RamError(m.kind, "pins", f"the ram eye stands at least 2 bore ({2.0 * ram.bore:.4f}) from the coupler pin; d is {np.linalg.norm(m.d - m.p):.4f} from p", pin="d") + if (m.kind != "direct") and not (m.lo <= 0.0 <= m.hi): + pose(m, np.linspace(0.0, m.lo if m.lo > 0.0 else m.hi, steps)) # the branch is carried from rest: no dead centre on the way + p = pose(m, np.linspace(m.lo, m.hi, steps)) + l_min, l_max = float(p.L.min()), float(p.L.max()) + eye = EYE[m.kind] + travel = l_max - l_min + barrel = _barrel(ram, p.L) # the samples' ends are lo and hi: barrel_length's own two angles + stroke = barrel - ram.gland + spare = stroke - (travel + 2.0 * ram.over) + i = int(np.argmin(np.abs(p.dL))) + arm_min, arm_at = float(abs(p.dL[i])), float(p.degrees[i]) + signs = set(np.sign(p.dL[np.abs(p.dL) > 1e-9]).tolist()) + arm_sign = int(signs.pop()) if len(signs) == 1 else 0 + f = Fit(m, ram, [], p.degrees, l_min, l_max, travel, barrel, ram.back + barrel + ram.e_b, stroke, spare, arm_min, arm_at, arm_sign) + if barrel <= ram.gland or spare < -1e-9: + f.why.append(("stroke", float(p.degrees[int(np.argmin(p.L))]), eye, f"travel {travel:.3f} needs {travel + 3.0 * ram.over + ram.gland + ram.back + ram.e_b:.3f} closed, L_min is {l_min:.3f}")) + if arm_sign == 0: + flip = np.nonzero(np.sign(p.dL[1:]) != np.sign(p.dL[:-1]))[0] + f.why.append(("toggle", float(p.degrees[flip[0] + 1]) if len(flip) else arm_at, eye, "dL/dtheta changes sign: a dead centre inside the range")) + elif arm_min < ram.min_arm: + f.why.append(("arm", arm_at, eye, f"least effective arm {arm_min:.3f} under {ram.min_arm:.3f}")) + if m.kind != "direct": + phi = np.degrees(np.unwrap(p.phi)) + j = int(np.argmax(p.load)) + f.swing, f.load_max = float(phi.max() - phi.min()), float(p.load[j]) + f.mu_c, f.mu_p = float(p.mu_c.min()), float(p.mu_p.min()) + if f.load_max > ram.max_load: + f.why.append(("load", float(p.degrees[j]), "c", f"coupler pin load {f.load_max:.2f} x the ram force, over {ram.max_load:.2f}")) + margin = np.full(steps, math.inf) + if distance is not None and clear: + c = _clearance(m, ram, barrel, p, distance, spacing) + margin, f.clear_at, f.pairs, f.allowed = c.margin, c.where, c.pairs, c.allowed + f.clear_min = float(margin.min()) + if f.clear_min < 0.0: + angle, member, part, pin = f.clear_at + f.why.append(("clash", angle, pin, f"{member} is {-f.clear_min:.3f} inside the clearance of part {part!r} ({m.parts[part]})")) + f.table = [tuple(row) for row in np.stack([p.degrees, p.L, p.dL, margin], axis=1).tolist()] + return f + + +def fit(m, ram, steps=25, distance=None, spacing=None): + """Check one mechanism from lo to hi. Gates, in order, each over all steps at once: assembly; stroke; effective + arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given + (see clearance: the record's parts say what it meets, its touch how near a pin). + Returns the Fit; a failed gate raises RamError, its `fit` holding the readings.""" + f = _fit(m, ram, steps, distance, spacing) + if not f.ok: + raise f.error() + return f + + +@dataclass +class Search: + best: Fit # the winner, or the nearest miss when none fits + found: bool + tried: int + fits: int # candidates that pass every gate but clearance + tally: dict # gate -> candidates it failed (a candidate can fail several) + seat: dict # the winner's or nearest miss's pins + + def report(self): + head = f"{self.fits} of {self.tried} candidates pass the gates before clearance" if self.found else f"no candidate of {self.tried} fits" + reasons = ", ".join(f"{k} {v}" for k, v in sorted(self.tally.items())) + return f"{head}{' (failed: ' + reasons + ')' if reasons else ''}; {'best' if self.found else 'nearest'}: {self.best.report() if self.best else 'none assembles'}" + + +def _polar(n, centre, toward, radii, step): + """Points about `centre` across the axis n: each radius, every `step` degrees from the direction `toward`.""" + e = _flat(np.asarray(toward, dtype=float) - centre, n) + if np.linalg.norm(e) < 1e-9: + e = _flat(np.array([0.0, 0.0, 1.0]) if abs(n[2]) < 0.9 else np.array([1.0, 0.0, 0.0]), n) + e = e / np.linalg.norm(e) + return [centre + r * _rot(e, n, math.radians(turn)) for r in radii for turn in range(0, 360, step)] + + +def candidates(kind, hinge, seats): + """The pins of every candidate of a seat grid. direct: seats['a'] x seats['b']. Linkages: seats['rocker'] x + seats['c'] x p on a polar grid about R (lengths seats['link'] = (lo, hi, n), every 15 degrees) x seats['a'], + and for a bell crank x d on a polar grid about R (seats['d'] = (lo, hi, n), every 30 degrees). The ram's eye + (d, and a four-bar's p) stands at a's place along the axis, so the ram runs across it.""" + n = np.asarray(hinge["axis"], dtype=float) + if kind == "direct": + return [{"a": a, "b": b} for a in seats["a"] for b in seats["b"]] + out = [] + for R in seats["rocker"]: + R = np.asarray(R, dtype=float) + for c in seats["c"]: + for p in _polar(n, R, c, np.linspace(*seats["link"]), 15): + eyes = [p] if kind == "four_bar" else _polar(n, R, p, np.linspace(*seats["d"]), 30) + for a in seats["a"]: + a = np.asarray(a, dtype=float) + for d in eyes: + d = d - n * ((d - a) @ n) + out.append({"a": a, "rocker": R, "p": d if kind == "four_bar" else p, "c": c, "d": d}) + return out + + +def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=None): + """Seat a mechanism from a grid (see candidates). hinge = {pivot, axis, lo, hi, offsets (optional)}. Best + first: every gate but clearance over all candidates, then clearance in order of least arm, greatest first; + the first clear one wins. world(m) -> (parts, touch, distance) builds a candidate's own parts, the brackets + and links its pins place among them, and the oracle that answers for them: a linkage's links are the + candidate's, so no one oracle serves a grid. What it returns is read as a record's: anything but the three, + a part on no body of the kind, a zone that is not (part, pin the member rides, radius, depth) or one wider or + deeper than its member is refused. A grid past `limit` candidates is refused naming the count. A + miss returns the tally and the nearest miss (the least total shortfall: stroke, arm, load excess, + clearance).""" + pins = candidates(kind, hinge, seats) + if len(pins) > limit: + raise RamError(kind, "search", f"{len(pins)} candidates, over the limit of {limit}: thin the seat grid") + tally, passed, miss = {}, [], None + + def missed(f, seat): + nonlocal miss + for gate in {g for g, _, _, _ in f.why}: + tally[gate] = tally.get(gate, 0) + 1 + short = (max(-f.spare, 0.0) + max(ram.min_arm - f.arm_min, 0.0) + (ram.min_arm if f.arm_sign == 0 else 0.0) + + max(f.load_max - ram.max_load, 0.0) + (max(-f.clear_min, 0.0) if f.clear_min < math.inf else 0.0)) + if miss is None or short < miss[0]: + miss = (short, f, seat) + + for seat in pins: + try: + m = Mechanism(kind, hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=hinge.get("offsets", (0.0,)), **seat) + f = _fit(m, ram, steps, clear=False) + except RamError as refusal: + tally[refusal.gate] = tally.get(refusal.gate, 0) + 1 + continue + if f.ok: + passed.append((f, seat)) + else: + missed(f, seat) + passed.sort(key=lambda entry: -entry[0].arm_min) + for f, seat in passed: + if world is None: + return Search(f, True, len(pins), len(passed), tally, seat) + made = world(f.m) + if not isinstance(made, tuple) or len(made) != 3 or not callable(made[2]): + raise RamError(kind, "search", f"world(m) returns (parts, touch, distance), got {type(made).__name__}") + parts, touch, distance = made + f = _fit(replace(f.m, parts=parts, touch=touch), ram, steps, distance, spacing) + if f.ok: + return Search(f, True, len(pins), len(passed), tally, seat) + missed(f, seat) + return Search(miss[1] if miss else None, False, len(pins), len(passed), tally, miss[2] if miss else None) + + +def record(m, ram): + """The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge + angle (from_record, then length or extension). It holds what is authored and nothing derived from it: barrel, + closed length and link lengths come from the pins and the ram. `compliance` is reserved for a load-path ram's + settle (COMPLIANCE: stiffness, damping, travel); version 1 writes it null and solves none.""" + return {"schema": SCHEMA, "version": VERSION, "kind": m.kind, + "hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi}, + "pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets), + "ram": {f.name: getattr(ram, f.name) for f in fields(Ram)}, + "parts": dict(m.parts), "compliance": None, + "touch": {member: [dict(zip(ZONE, zone)) for zone in zones] for member, zones in m.touch.items()}} + + +def from_record(data): + """(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with + a key this version does not know or without one it does, with a compliance block, or with a value that is not + its field's type (a finite number, three of them, a name), or with a zone wider or deeper than its member is + refused whole, as a RamError naming the field: nothing is read past and dropped.""" + if not isinstance(data, dict): + raise RamError("None", "record", f"a record is an object, got {type(data).__name__}") + kind, version = str(data.get("kind")), data.get("version") + if data.get("schema") != SCHEMA or type(version) is not int or version != VERSION: + raise RamError(kind, "record", f"this reader reads {SCHEMA} version {VERSION}; the record is {data.get('schema')} version {version!r}") + if kind not in KINDS: + raise RamError(kind, "record", f"kind is one of {', '.join(KINDS)}") + + def keys(name, given, known): + if not isinstance(given, dict): + raise RamError(kind, "record", f"an object, got {type(given).__name__}", pin=name) + if set(given) != set(known): + raise RamError(kind, "record", f"the {name}'s keys are not version {VERSION}'s: unknown {sorted(set(given) - set(known), key=str)}, missing {sorted(set(known) - set(given))}") + + def point(name, value): + if not isinstance(value, list) or len(value) != 3: + raise RamError(kind, "record", f"three finite numbers, got {value!r}", pin=name) + return [_number(kind, name, x) for x in value] + + keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance")) + hinge, pins, ram = data["hinge"], data["pins"], data["ram"] + keys("hinge", hinge, ("pivot", "axis", "lo", "hi")) + keys("pins", pins, PINS[kind]) + keys("ram", ram, [f.name for f in fields(Ram)]) + if data["compliance"] is not None: + raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it") + for name, value in ram.items(): + _number(kind, name, value, 0.0 if name == "bore" else None) + if not isinstance(data["offsets"], list): + raise RamError(kind, "record", f"a list of numbers, got {data['offsets']!r}", pin="offsets") + if not isinstance(data["parts"], dict) or not all(isinstance(body, str) for body in data["parts"].values()): + raise RamError(kind, "record", "an object of part: body", pin="parts") + if not isinstance(data["touch"], dict): + raise RamError(kind, "record", "an object of member: zones", pin="touch") + touch = {} + for member, zones in data["touch"].items(): + if not isinstance(zones, list): + raise RamError(kind, "record", f"{member}'s zones are a list, got {zones!r}", pin="touch") + for zone in zones: + keys(f"{member} zone", zone, ZONE) + touch[member] = [tuple(zone[key] for key in ZONE) for zone in zones] + m = Mechanism(kind, point("pivot", hinge["pivot"]), point("axis", hinge["axis"]), _number(kind, "lo", hinge["lo"]), _number(kind, "hi", hinge["hi"]), + offsets=tuple(_number(kind, "offsets", o) for o in data["offsets"]), parts=data["parts"], touch=touch, + **{name: point(name, value) for name, value in pins.items()}) + ram = Ram(**ram) + _eyes(m, ram) + return m, ram + + +def swept(f, body, margin=0.0, steps=13, around=8): + """Points on the swept ram's surface in a body's rest frame, the barrel radius grown by `margin`, a trunnion's + tail included: what a recess in that body must clear (their hull or bounding box).""" + m, ram = f.m, f.ram + if body not in BODIES[m.kind]: + raise RamError(m.kind, "swept", f"no body {body!r}; this kind has {', '.join(BODIES[m.kind])}") + p = pose(m, np.linspace(m.lo, m.hi, steps)) + side = np.cross(p.u, m.axis) + side = side / np.linalg.norm(side, axis=1)[:, None] + up = np.cross(side, p.u) + turn = np.linspace(0.0, 2.0 * math.pi, around, endpoint=False) + ring = (ram.barrel_r + margin) * (np.cos(turn)[None, :, None] * side[:, None, :] + np.sin(turn)[None, :, None] * up[:, None, :]) + pts = [] + for off in m.offsets: + for centre in (p.base + off * m.axis + p.u * min(ram.back, 0.0), p.eye + off * m.axis): + pts.append(centre[:, None, :] + ring) + return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3) + + +class Signed: + """The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative + where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside + only. shells: part -> [(vertices (N, 3), faces)], each shell closed, in the rest frame of the part's body. + Inside is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex + miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's + mathutils (BVHTree).""" + + def __init__(self, shells, cap=None, rays=3): + from mathutils import Vector + from mathutils.bvhtree import BVHTree + self.cap, self.asked, self.vector = cap, 0, Vector + self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]] + self.trees = {part: [(BVHTree.FromPolygons(np.asarray(v, dtype=float).tolist(), [tuple(face) for face in f], epsilon=0.0), + np.min(v, axis=0), np.max(v, axis=0)) for v, f in made] for part, made in shells.items()} + + @staticmethod + def crossings(tree, v, ray): + count, o = 0, v + for _ in range(64): + loc = tree.ray_cast(o, ray)[0] + if loc is None: + break + count, o = count + 1, loc + ray * 1e-6 + return count + + def inside(self, tree, v): + return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays) + + def __call__(self, part, pts): + pts = np.asarray(pts, dtype=float) + self.asked += len(pts) + out = np.full(len(pts), math.inf if self.cap is None else self.cap) + for tree, lo, hi in self.trees[part]: + boxed = ((pts >= lo) & (pts <= hi)).all(axis=1) + for i, p in enumerate(pts): + v = self.vector(p) + if boxed[i] and self.inside(tree, v): + out[i] = min(out[i], -tree.find_nearest(v)[3]) + continue + hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v) + if hit[0] is not None and hit[3] < out[i]: + out[i] = hit[3] + return out diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 6ddbbfa..157b805 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -777,6 +777,154 @@ field. Nothing in a kit is run as Python. Division by zero, a result that is not or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose vertices overflow. +## Rams and linkages + +`brokkr_kitbash/ram.py` owns the motion of a ram across one hinge. It is numpy and the standard library, imports +nothing from the package, and no action calls it yet: a rig or a runtime loads the file alone. Its input is a +mechanism record: the hinge (pivot, unit axis, `lo` and `hi` in degrees, positive right-handed about the axis like +a pin joint's roll), a kind, and pins, each in its own body's rest frame. + +| kind | pins | the ram runs | +| --- | --- | --- | +| `direct` | `a` on the parent, `b` on the child | `a` to `b` | +| `four_bar` | `a`; `rocker` (R), the rocker's pivot on the parent; `p` on the rocker; `c` on the child; `d` = `p` | `a` to `p`: the excavator bucket linkage, a coupler from `p` to `c` turning the child | +| `bell_crank` | the same, `d` elsewhere on the rocker, at least 2 bore from `p` | `a` to `d` | + +Everything is a function of the record and the hinge angle: `pose` gives each body's rotation, the ram's base and +eye, its pin-to-pin length L and dL/dtheta; `length` and `extension` (L less the closed length) are what a rig +drives a rod from. Nothing stores a rocker angle or an extension. The loop is solved in the plane across the axis: +`p` lies where the rocker's circle about R meets the coupler's about `c`, on the side of R -> `c` it has at rest, +so an angle gives the same pose whatever was asked before it. A pin's coordinate along the axis says only where +its member stands: the rocker bars at R's, the coupler at `c`'s, the ram at `a`'s plus each of `offsets` (twins). +Rates are closed form: for a linkage dphi/dtheta = (axis x (c - O)) . k / ((axis x (p - R)) . k), k along the +coupler, and dL/dtheta = (axis x (d - R)) . u x dphi/dtheta, u along the ram. + +`fit` runs the gates over the range, in this order. A failed gate is a `RamError` naming the kind, the gate, the +angle and the pin, with the readings attached; a refusal of the record or of a call (an unknown kind, a range, a +grid over the limit, a version) names the pin or the field it refuses. + +- **assembly**: the rocker and coupler close the loop at every step, and on the way from rest when the range does + not hold 0; within 1e-9 of a dead centre is refused, since the branch would change there. Names `c`. +- **stroke**: the barrel holds the travel, the overtravel at both ends and the gland. Names the angle of the + shortest length and the eye's pin. +- **toggle**, **arm**: dL/dtheta keeps one sign, and |dL/dtheta| (the effective arm: hinge torque per unit ram + force) stays at or above `min_arm`. Name the eye's pin. +- **load** (linkages): the coupler's pin load per unit ram force, |dL/dtheta| over the coupler's moment arm about + the hinge, stays at or under `max_load` (3). Names `c`. +- **clash**: clearance, when a distance oracle is given. Names the member, the part, and the member's nearer pin. + +The barrel is derived, never stored: `barrel_length` is the length at the shorter end of the range less the +overtravel, the base clevis and the eye, and `fit` reads it from its own two end samples. + +Transmission angles at `c` and `p` are reported and not gated. Over the R-3 knee's 125 degrees the best least +transmission angle of 200,000 sampled four-bars was 21.9 degrees, under the 30 to 40 a textbook asks; a gate there +would have refused every one of them. What a poor angle costs is pin load, and that is the gate. + +### Clearance: parts, and zones about a member's pins + +The record names the mechanism's `parts`, each a piece of one body (part -> parent, child, rocker or coupler: the +body whose rest frame it turns with), and `touch`: for each member (`barrel`, `rod`, `rocker`, `coupler`, and a +bell crank's `rocker arm`), zones `(part, pin, radius, depth)`. Every member meets every part. A zone changes what +the member's samples keep from one part, and only within `radius` of the axis of `pin`, measured across the hinge +axis; the pin is one the member rides (the ram `a` and its eye, the rocker its pivot and `p`, the coupler `p` and +`c`, the arm the pivot and `d`). Inside the zone a sample may come as near the part as `-depth`; beyond it the +pair is checked like any other. Nothing is exempt by a name, by a length cut from a member's end, or by the +member's own body: the barrel runs from its back end, the rod to the eye, a bar from pin to pin. Every body of the +kind owns at least one part, or the gate refuses the record. + +A zone's radius is the eye's radius plus a margin: the pin's, collar's or cheek's radius plus what the member +keeps (radius, gap, half the spacing). Its depth says how the member stands to the part there. 0 is beside it: a +plate stacked on the pin, the bracket or horn the pin stands in. The member's axis then stays outside the part, so +a pin whose place along the axis is inside what it claims to stand beside is refused: the gate does not take the +record's x on trust. The pin's radius is for the pin through the member's eye, half the plate's thickness for the +member's own plate, which is zoned about both of the member's pins. Two plates stacked on a pin cross like +scissors; the zone that lets one link by the other's plate reaches as far as the two part, (half width + what a +link keeps) / sin of the least angle they cross at, and no further than the link is long. Two zones of one pair +that both reach a sample let it the deeper of the two. + +A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin +to pin: a bar's length between its pins, and for the barrel and the rod the base's and the eye's distances from +the centre the eye turns about, added. A `Mechanism` refuses a zone past that from its pins alone. Its depth is +also no more than the member's eye on that pin (`Ram.eye`: `e_a` at the base, `e_b` at the rod's eye, `link_r` on +a bar), which `from_record` and the gate refuse, so a world's answer is held to it as well. The record holds no +plate widths, so the radius has no tighter bound than the length. + +Between two samples of which either is in a zone the gate does not rely on the spacing. A distance changes by no +more than the way between two points, so along a segment it is at least (g(a) + g(b) - length) / 2. Where that +does not show the segment keeps `-depth`, the gate halves it and reads the midpoint, down to spacing / 64. A +segment still unproved there against a part the axis is held outside (depth 0) is refused: the part is within +spacing / 128 of the axis, crossed or touched, whatever its thickness. Against a part the axis may enter, the +samples' readings stand, so a burial is read to spacing / 128. This asks of the oracle that it never reads more +than the true distance. + +What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a +gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. The members are +round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The proof +between samples costs oracle calls: a depth stated with no slack over the burial (a bar's own plates at `link_r`) +is halved to the floor along the whole zone. And it is along the axis at each checked angle; between two angles +nothing is proved. + +The oracle is `distance(part, points) -> distances`, `points` in the rest frame of the part's body. Each member is +sampled along its axis at most `spacing` apart (default the barrel's radius) and carried into each body's rest +frame at each angle; a sample is clear at radius + gap + spacing / 2 or more, which keeps the gap for the surface +between samples. A distance is signed: negative inside a part, by any depth. The oracle may cap what it returns at +`Ram.reach(spacing)`, outside a part only; a point inside reads negative however deep it lies. An oracle that +cannot tell inside from outside raises instead of answering (a nearest-surface query alone reads 0.13 at the +centre of the R-3 thigh's core, and reads clear when capped); nan is refused. `Fit.pairs` holds the least margin +and its angle for every pair, `Fit.allowed` the pairs a zone lets near a pin. + +`search` seats a mechanism from a grid (ram seats; for linkages rocker pivots, child pins, `p` on a polar grid +about R, and `d` about R for a bell crank, the eye standing at `a`'s place along the axis), refuses a grid over +`limit` candidates naming the count, runs every gate but clearance on all of them, then clearance in order of +least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch, +distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met +with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on +no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, or a zone wider or +deeper than its member is refused. +`swept` gives the ram's swept surface in any body's frame, for a recess. + +### The record + +`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`, +`pins`, `offsets`, `ram`, `parts`, `touch` (member -> zones, each `{part, pin, radius, depth}`), and `compliance`. +It holds what is authored; barrel, closed length and link lengths are derived by the reader. `compliance` is +reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A +record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or +without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value +that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone wider or +deeper than its member is refused whole, as a +`RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the +same numbers. + +### Readings on the R-3 knee + +Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clearance rows are +`tests/live/ram_knee.py`'s, Blender 5.3 (`ram_knee.result.json` is the last run): the knee as closed meshes the +test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that +carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width, +collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and the package's signed BVH +oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority, +for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands +clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them +and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24 +inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16. + +| drive | reading | +| --- | --- | +| direct, the joint library's seats, 0..-62 | fits (analytic thigh and shin) | +| direct, 2,000 seat pairs behind the knee | none fits (analytic thigh and shin) | +| four-bar behind the knee | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5. Refused on the meshes: the barrel and the rod against the shin's body (the barrel 0.122 inside its clearance, 49 steps), a body the ram is not pinned to | +| bell crank in front of the knee | fits on the meshes, the plates on either side: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8. 60 pairs, 20 of them with a zone. Over 251 steps, uncapped, the least margin of a pair with no zone is 0.034 (the rocker and the eye's pin at -125), then 0.039 (the rod and the rocker's pivot pin at -125) and 0.042 (the coupler and the bracket at 0). With `touch` empty the same gate refuses 19 pairs, each one a zoned pair; each stated zone takes in the least zone that lets its pair. A zone cut to half its radius refuses its pair | +| the same, a link's x moved | the rocker at x 0.25 (inside the bracket's 0.13..0.35) is refused 0.054 inside the bracket; the coupler at 0.25 (inside the horn's 0.23..0.31) 0.020 inside the horn | +| bell-crank search on the meshes | 13,824 candidates, each world built from the candidate's pins: 78 pass the gates before clearance, 21 of them are refused on their own parts, the 22nd fits (arm 0.090, swing 99.9, pin load 0.73) and holds at 251 steps | + +Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candidate's gates before clearance at +49 steps took 0.79 ms median on the bell crank; its clearance against the analytic parts (50 pairs) took 42 ms +(5th to 95th percentile 38 to 57) over 97,875 points, of which 23,520 are the samples and the rest the halving in +zones (the own plates, stated with no slack, to the floor); the samples alone took 11 ms. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit` +(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 1.95 to 2.12 s capped (two runs), in a +Python loop of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 43 s (one run). + ## The actions | action | fields | what it does | diff --git a/surfaces/blender/tests/fixtures/ram_rays.json b/surfaces/blender/tests/fixtures/ram_rays.json new file mode 100644 index 0000000..788d9ee --- /dev/null +++ b/surfaces/blender/tests/fixtures/ram_rays.json @@ -0,0 +1 @@ +{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them (one shell, triangulated, at rest), and points between the plates (|x| under 0.349, the plates begin at 0.35): each stands on the oracle's first ray 0.004 to 0.02 short of a vertex or an edge of the shell. Every point is outside.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"points":[[0.34569818,0.758339776,0.399797897],[0.34569818,0.765357508,0.412003349],[0.33924546,0.757903937,0.405161809],[0.34569818,0.768260135,0.425779979],[0.343547274,0.765775611,0.423499465],[0.33924546,0.760806564,0.418938439],[0.34569818,0.766763402,0.439779322],[0.343547274,0.764278879,0.437498808],[0.33924546,0.759309832,0.432937782],[0.34569818,0.761013938,0.452630947],[0.343547274,0.758529415,0.450350434],[0.33924546,0.753560368,0.445789407],[0.34569818,0.75157447,0.4630769],[0.343547274,0.749089947,0.460796386],[0.33924546,0.744120899,0.45623536],[0.347849087,0.741853572,0.472375145],[0.34569818,0.739369048,0.470094631],[0.343547274,0.736884525,0.467814118],[0.33924546,0.731915478,0.463253092],[0.347849087,0.728076971,0.475277742],[0.34569818,0.725592448,0.472997229],[0.343547274,0.723107924,0.470716715],[0.33924546,0.718138877,0.466155689],[0.347849087,0.714077628,0.473781039]]} \ No newline at end of file diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py new file mode 100644 index 0000000..33dc608 --- /dev/null +++ b/surfaces/blender/tests/live/ram_knee.py @@ -0,0 +1,435 @@ +"""Live proof, in a background Blender, of brokkr_kitbash/ram.py's clearance gate on meshes: the R-3 knee (thigh, +shin, the bracket and horn, a bell crank's or a four-bar's plates, pins and clevises), every piece a closed mesh this +file generates, each a named part of a body, and the gate answered by the package's signed BVH oracle (ram.Signed) +over them. Not part of the unittest run: it needs Blender (mathutils' BVHTree). + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/ram_knee.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path; writes .result.json and .r3_.png (the bell crank at 0, +-62.5 and -125) and exits 1 when a check failed. + +The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker +plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an +edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside. + +A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run +inside one try: an uncaught error is a failed check that names its section, and the result file is always written. +""" +import importlib.util +import json +import math +import os +import sys +import time +import traceback +from dataclasses import replace +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not Path(OUT).is_absolute(): + raise SystemExit(f"{OUT!r} is not an absolute path") +spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "brokkr_kitbash" / "ram.py") +R = importlib.util.module_from_spec(spec) # ram.py as the unit tests load it +sys.modules[spec.name] = R +spec.loader.exec_module(R) +Signed = R.Signed + +RES = {"blender": bpy.app.version_string, "checks": [], "readings": {}} +SECTION = ["setup"] +# Metres between the oracle's reading and 0.0225, on a grid a plate's thickness off a rocker plate's face. Shipped +# worst 1.3e-08 (float32 faces); least claimed mutant 0.045 (a sample signed inside reads -0.0225); the geometric mean. +FLAT = 2.4e-5 + +BORE, PIN, AXLE = 0.042, 0.026, 0.028 +SLAB_C, SLAB_R = (0.31, 0.345), (0.35, 0.385) # the twin link plates along the axis: the coupler's inside the rocker's +X_C, X_R = 0.5 * sum(SLAB_C), 0.5 * sum(SLAB_R) +HALF = 0.5 * (SLAB_R[1] - SLAB_R[0]) # half a plate's thickness +W_ROCKER, W_COUPLER, W_ARM, W_HORN, W_BRACKET, COLLAR = 0.045, 0.04, 0.04, 0.05, 0.055, 0.05 +CHEEK = (0.03, 0.05) # a clevis's cheeks, either side of the ram's eye +SLACK = 0.001 # a zone's depth over the burial it lets: a float32 face reads a burial to 1e-8 +# P2's seats, (y, z): the deep four-bar behind the knee and the bell crank in front of it +DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284), + "c": (0.06881023105761902, -0.3143743967236484), "d": (-0.43650046730511183, -0.017951928782268284)} +CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "p": (0.7282866960904424, 0.43261578669776135), + "c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)} +ROOTS = {"bell_crank": {"horn": (0.10, -0.40), "bracket": (0.10, 0.55)}, "four_bar": {"horn": (0.0, -0.42), "bracket": (-0.10, 0.55)}} +THIGH_FRONT, EMBED = 0.14, 0.01 # the thigh core's faces stand at y +-0.14; a foot runs this far into it + + +def check(name, ok, detail=None): + RES["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +def prism(outline, x0, x1): + """A closed shell: the convex (y, z) outline, counter-clockwise seen from +x, run from x0 to x1.""" + x0, x1 = min(x0, x1), max(x0, x1) + n = len(outline) + verts = [(x, y, z) for x in (x0, x1) for y, z in outline] + faces = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))] + [(k, (k + 1) % n, n + (k + 1) % n, n + k) for k in range(n)] + return np.array(verts, dtype=float), faces + + +def box(centre, size): + (cx, cy, cz), (sx, sy, sz) = centre, size + return prism([(cy - sy / 2, cz - sz / 2), (cy + sy / 2, cz - sz / 2), (cy + sy / 2, cz + sz / 2), (cy - sy / 2, cz + sz / 2)], cx - sx / 2, cx + sx / 2) + + +def disc(at, r, x0, x1, n=32): + return prism([(at[0] + r * math.cos(2 * math.pi * k / n), at[1] + r * math.sin(2 * math.pi * k / n)) for k in range(n)], x0, x1) + + +def bar(p, q, w, x0, x1, n=10): + """A link plate: the stadium of half width w about the segment p -> q.""" + p, q = np.array(p, float), np.array(q, float) + base = math.atan2(*((q - p) / np.linalg.norm(q - p))[::-1]) + pts = [(c[0] + w * math.cos(a0 + math.pi * k / n), c[1] + w * math.sin(a0 + math.pi * k / n)) for c, a0 in ((q, base - math.pi / 2), (p, base + math.pi / 2)) for k in range(n + 1)] + return prism(pts, x0, x1) + + +def knee(kind, pn, links=True): + """part -> [shell], part -> body: the knee at rest (angle 0, every frame the parent's).""" + shells, front = {}, kind == "bell_crank" + + def add(part, *made): + shells.setdefault(part, []).extend(made) + r, gap, cheek = 0.25, 0.22, 0.07 + half = gap / 2 + cheek + add("parent.body", box((0, 0, 0.725), (0.26, 2 * THIGH_FRONT, 0.85)), box((0, 0.185, 0.725), (0.34, 0.06, 0.77)), box((0, 0, 0.2), (gap - 0.03, 0.24, 0.4)), + disc((0, 0), 0.9 * r, -(gap - 0.03) / 2, (gap - 0.03) / 2)) + outline = [(r * math.cos(math.radians(a)), r * math.sin(math.radians(a))) for a in range(0, 181, 15)] + [(-0.12, -0.95), (0.12, -0.95)] + add("child.body", box((0, 0, -0.72), (gap, 0.22, 0.46)), box((0, 0.15, -0.62), (2 * half + 0.06, 0.06, 0.58))) + Rk, P, C, A, D = (pn[k] for k in ("rocker", "p", "c", "a", "d")) + for s in (-1, 1): + add("child.body", prism(outline, s * gap / 2, s * half), disc((0, 0), 0.19, s * half, s * (half + 0.025)), box((s * (half + 0.03), 0.0, -0.62), (0.045, 0.2, 0.5))) + add("child.horn", bar(ROOTS[kind]["horn"], C, W_HORN, s * (half + 0.05), s * SLAB_C[0])) + add("parent.bracket", bar(ROOTS[kind]["bracket"], Rk, W_BRACKET, s * 0.13, s * SLAB_R[0])) + # the base clevis: cheeks about the pin and a foot that runs into the thigh's core, toward it + toward = -1.0 if front else 1.0 + foot = (A[0] + toward * 0.2, A[1]) + add("parent.seat", bar(A, foot, 1.7 * BORE, s * CHEEK[0], s * CHEEK[1])) + if links: + add("rocker.plate", bar(Rk, P, W_ROCKER, s * SLAB_R[0], s * SLAB_R[1])) + add("coupler.plate", bar(P, C, W_COUPLER, s * SLAB_C[0], s * SLAB_C[1])) + add("rocker.seat", disc(D, COLLAR, s * CHEEK[0], s * CHEEK[1])) # the eye's collars on its pin + if front: + add("rocker.plate", bar(Rk, D, W_ARM, s * SLAB_R[0], s * SLAB_R[1])) + face = toward * (THIGH_FRONT - EMBED) + add("parent.seat", box((0, 0.5 * (face + foot[0]), A[1]), (2 * CHEEK[1], abs(foot[0] - face), 3.4 * BORE))) + if links: + add("rocker.pin.R", disc(Rk, AXLE, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + add("rocker.pin.p", disc(P, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + add("coupler.pin.c", disc(C, PIN, -SLAB_C[1] - 0.015, SLAB_C[1] + 0.015)) + if front: + add("rocker.pin.d", disc(D, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + return shells, {part: {"parent": "parent", "child": "child", "rocker": "rocker", "coupler": "coupler"}[part.split(".")[0]] for part in shells} + + +def near(ram, member): + return {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + ram.gap + ram.spacing() / 2 + + +def parting(ram, w, degrees): + """How far from a pin a link parts from a plate of half width w that stands beside it on the pin, a plate's + thickness off along the axis, the two crossing at `degrees` at the least: where the link's axis is what a link + keeps from the plate's edge, and never less than the plate's round end.""" + lateral = math.sqrt(near(ram, "rocker") ** 2 - HALF ** 2) + return max((w + lateral) / math.sin(math.radians(min(degrees, 90.0))), w + near(ram, "rocker")) + + +def crossing(m, kind): + """The least angle, over the range, at which the rocker, the rocker arm and the coupler cross what stands beside + them: the bracket's bar at the pivot, the horn's at c (seen from the shin), each other at p.""" + p, n = R.pose(m, np.linspace(m.lo, m.hi, 126)), m.axis + + def least(a, b): + a, b = R._flat(a, n), R._flat(np.broadcast_to(b, a.shape), n) + return float(np.degrees(np.arccos(np.clip((a * b).sum(axis=1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)), -1.0, 1.0))).min()) + root = {key: np.array((0.0, *value)) for key, value in ROOTS[kind].items()} + seen = R._into(m, p, "child", p.P[:, None, :])[:, 0, :] + return {"rocker": least(p.P - m.rocker, root["bracket"] - m.rocker), "rocker arm": least(p.eye - m.rocker, root["bracket"] - m.rocker), + "coupler": least(seen - m.c, root["horn"] - m.c), "p": float(p.mu_p.min())} + + +def zones(m, ram, parts): + """Each member's zones. About a pin: the pin's, collar's or cheek's radius plus what the member keeps, as deep as + the pin where it runs through the member's eye and 0 beside a collar, a cheek, the bracket or the horn; a link's + own plate about both its pins, each a little over half its length (a zone is no wider than its member), half + the plate's thickness deep; a plate beside a link as far as the two part. A depth that is not 0 is stated SLACK + over the burial.""" + kind, link, at = m.kind, near(ram, "rocker"), crossing(m, m.kind) + PIN, AXLE, HALF = (value + SLACK for value in (globals()["PIN"], globals()["AXLE"], globals()["HALF"])) + reach = {"pin": globals()["PIN"] + link, "axle": globals()["AXLE"] + link} + eye = "rocker.pin.d" if kind == "bell_crank" else "rocker.pin.p" + + def own(part, a, b, span): + return [(part, a, 0.51 * span, HALF), (part, b, 0.51 * span, HALF)] + + def parts_at(member, w, degrees): # never wider than the member: two that cross at a few degrees part beyond its length + return min(parting(ram, w, degrees), R._span(m, member)) + touch = {member: [("parent.seat", "a", 1.7 * BORE + near(ram, member), 0.0), ("rocker.seat", "d", COLLAR + near(ram, member), 0.0), + (eye, "d", globals()["PIN"] + near(ram, member), PIN if member == "rod" else 0.0)] for member in ("barrel", "rod")} + pivot = [("parent.bracket", "rocker", None, 0.0), ("rocker.pin.R", "rocker", reach["axle"], AXLE)] + touch["rocker"] = pivot + [("rocker.pin.p", "p", reach["pin"], PIN), *own("rocker.plate", "rocker", "p", m.lr), ("coupler.plate", "p", parts_at("rocker", W_COUPLER, at["p"]), 0.0)] + touch["coupler"] = [("child.horn", "c", parts_at("coupler", W_HORN, at["coupler"]), 0.0), ("coupler.pin.c", "c", reach["pin"], PIN), ("rocker.pin.p", "p", reach["pin"], PIN), + *own("coupler.plate", "p", "c", m.lc), ("rocker.plate", "p", parts_at("coupler", W_ROCKER, at["p"]), 0.0)] + if kind == "bell_crank": + touch["rocker arm"] = pivot + [("rocker.pin.d", "d", reach["pin"], PIN), *own("rocker.plate", "rocker", "d", R._span(m, "rocker arm"))] + for member in ("rocker", "rocker arm"): + if member in touch: + touch[member][0] = ("parent.bracket", "rocker", parts_at(member, W_BRACKET, at[member]), 0.0) + return {member: [zone for zone in given if zone[0] in parts] for member, given in touch.items()} + + +def pins3(pn, side=1.0, **moved): + at = {"a": 0.0, "p": 0.0, "d": 0.0, "rocker": side * X_R, "c": side * X_C, **moved} + return {k: (at[k], float(pn[k][0]), float(pn[k][1])) for k in pn} + + +def needs(m, ram, parts, distance, steps=49): + """(member, part) -> (pin, radius, depth): for every pair refused with nothing let, the least zone that lets it.""" + p = R.pose(m, np.linspace(m.lo, m.hi, steps)) + at = {"a": p.base, R.EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C} + step, out = ram.spacing(), {} + for member, label, start, end, radius, pins in R._members(m, ram, R.barrel_length(m, ram), p): + count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2) + pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] + for part, body in parts.items(): + got = distance(part, R._into(m, p, body, pts).reshape(-1, 3)).reshape(len(p.degrees), count) + bad = got < radius + ram.gap + step / 2 + if bad.any(): + best = None + for pin in pins: + across = np.linalg.norm(R._flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2) + reach = float(across[bad].max()) + if best is None or reach < best[1]: + best = (pin, reach, max(-float(got[across <= reach].min()), 0.0)) + out[(label, part)] = best + return out + + +def refused(f): + return sorted((pair, round(reading[0], 4), reading[1]) for pair, reading in f.pairs.items() if reading[0] < 0.0) + + +def label(member): + return member + "[0]" if member in ("barrel", "rod") else member + + +def hinge4(pivot, degrees): + return Matrix.Translation(Vector(pivot)) @ Matrix.Rotation(math.radians(degrees), 4, "X") @ Matrix.Translation(-Vector(pivot)) + + +def render(m, ram, f, shells, parts): + """The bell crank at 0, -62.5 and -125, each piece coloured by its part, the ram as the gate holds it.""" + scene = bpy.context.scene + colour = {"horn": (0.95, 0.45, 0.1, 1), "bracket": (0.15, 0.45, 0.9, 1), "plate": (0.75, 0.75, 0.78, 1), "seat": (0.55, 0.3, 0.6, 1), "pin": (0.9, 0.9, 0.3, 1)} + objects = [] + for part, made in shells.items(): + for k, (verts, faces) in enumerate(made): + me = bpy.data.meshes.new(f"{part}.{k}") + me.from_pydata(verts.tolist(), [], faces) + o = bpy.data.objects.new(me.name, me) + scene.collection.objects.link(o) + o.color = colour.get(part.split(".")[1], (0.33, 0.38, 0.24, 1) if parts[part] == "child" else (0.3, 0.32, 0.36, 1)) + objects.append((o, parts[part])) + + def tube(name, r, col): + me, bm = bpy.data.meshes.new(name), bmesh.new() + bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=r, radius2=r, depth=1.0) + bmesh.ops.translate(bm, verts=bm.verts[:], vec=(0, 0, 0.5)) + bm.to_mesh(me) + bm.free() + o = bpy.data.objects.new(name, me) + scene.collection.objects.link(o) + o.color = col + return o + barrel, rod = tube("ram.barrel", ram.barrel_r, (0.85, 0.15, 0.12, 1)), tube("ram.rod", ram.rod, (0.95, 0.95, 0.95, 1)) + scene.render.engine = "BLENDER_WORKBENCH" + scene.display.shading.light, scene.display.shading.color_type = "STUDIO", "OBJECT" + scene.display.shading.show_shadows = scene.display.shading.show_cavity = True + scene.render.resolution_x, scene.render.resolution_y, scene.render.film_transparent = 1400, 1500, False + scene.world = bpy.data.worlds.new("w") + scene.world.color = (0.82, 0.83, 0.85) + cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")) + scene.collection.objects.link(cam) + cam.data.type, cam.data.ortho_scale = "ORTHO", 2.75 + target = Vector((0.0, 0.1, 0.12)) + cam.location = target + Vector((0.72, 0.62, 0.22)).normalized() * 8.0 + cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler() + scene.camera = cam + made = [] + for angle in (0.0, -62.5, -125.0): + p = R.pose(m, angle) + T = {"parent": Matrix.Identity(4), "child": hinge4((0, 0, 0), angle), "rocker": hinge4(m.rocker, math.degrees(p.phi[0])), + "coupler": Matrix.Translation(Vector(p.P[0] - m.p)) @ hinge4(m.p, math.degrees(p.psi[0]))} + for o, body in objects: + o.matrix_world = T[body] + u, base = Vector(p.u[0]), Vector(p.base[0]) + frame = u.to_track_quat("Z", "Y").to_matrix().to_4x4() + barrel.matrix_world = Matrix.Translation(base + u * ram.back) @ frame @ Matrix.Diagonal((1, 1, f.barrel, 1)) + rod.matrix_world = Matrix.Translation(base + u * (ram.back + f.barrel)) @ frame @ Matrix.Diagonal((1, 1, float(p.L[0]) - ram.back - f.barrel, 1)) + scene.render.filepath = f"{OUT}.r3_{abs(angle):g}".replace(".5", "p5") + ".png" + bpy.ops.render.render(write_still=True) + made.append(scene.render.filepath) + return made + + +try: + bpy.ops.wm.read_factory_settings(use_empty=True) + ram = R.Ram(BORE) + HINGE = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), -125.0, 0.0) + + SECTION[0] = "oracle" + shells, parts = knee("bell_crank", CRANK) + rows = [] + for name, part, point, depth in (("the thigh core's centre", "parent.body", (0.0, 0.0, 0.7), -0.13), ("0.02 inside the thigh's wall", "parent.body", (0.11, 0.0, 0.7), -0.02), + ("the shin's leg centre", "child.body", (0.0, 0.0, -0.7), -0.11), ("0.125 off the thigh's plate", "parent.body", (0.0, 0.34, 0.7), 0.125)): + capped, free = (float(Signed(shells, cap)(part, np.array([point]))[0]) for cap in (ram.reach(), None)) + rows.append((name, capped, free, abs(free - depth) < FLAT and capped == (free if depth < 0 else min(free, ram.reach())))) + check("inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", all(row[3] for row in rows), rows) + # a grid a plate's thickness off the rocker plates' inner face, over the knee: every point is 0.0225 or more from the + # plates and none is inside; where the plate is under the point the reading is the 0.0225 + ys, zs = np.meshgrid(np.linspace(0.1, 0.9, 96), np.linspace(0.1, 0.7, 72)) + plane = np.stack([np.full(ys.size, X_C), ys.ravel(), zs.ravel()], axis=1) + three, one = Signed(shells)("rocker.plate", plane), Signed(shells, rays=1)("rocker.plate", plane) + def off(a, b): # each grid point's distance from the segment a -> b, across the axis + a, b = np.array(a), np.array(b) + t = np.clip(((plane[:, 1:] - a) @ (b - a)) / ((b - a) @ (b - a)), 0.0, 1.0) + return np.linalg.norm(plane[:, 1:] - a - t[:, None] * (b - a), axis=1) + under = (off(CRANK["rocker"], CRANK["p"]) < W_ROCKER - 0.005) | (off(CRANK["rocker"], CRANK["d"]) < W_ARM - 0.005) + RES["readings"]["FLAT"] = float(np.abs(three[under] - (SLAB_R[0] - X_C)).max()) + RES["readings"]["one ray: samples signed inside, of %d" % len(plane)] = int((one < 0).sum()) + check("three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", + (three >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(three.min()), int(under.sum()), RES["readings"]["FLAT"]]) + # against shells whose inside is known in closed form: a box and a disc, random points, each ray's edges and vertices among them + rng = np.random.default_rng(7) + cloud = rng.uniform((-0.2, -0.2, 0.2), (0.2, 0.2, 1.25), (4000, 3)) + core = Signed({"core": [box((0, 0, 0.725), (0.26, 0.28, 0.85))]})("core", cloud) + exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425]) + check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum())) + + # the ray count: the jointlib rocker plates, and points between them aimed along the first ray at an edge or a vertex + fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8")) + plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"]) + made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed) + RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum()) + RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum()) + # one ray reads all 24 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 24 + check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", + (np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())]) + + SECTION[0] = "seat" + seat = np.concatenate([v for v, _ in shells["parent.seat"]]) + deepest = float(Signed(shells)("parent.body", seat).min()) + RES["readings"]["the base clevis's foot inside the thigh"] = deepest + check("the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", abs(deepest + EMBED) < FLAT, deepest) + + SECTION[0] = "bell crank" + winner = None + for side in (1.0, -1.0): + m = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, side), parts=parts) + touch = zones(m, ram, parts) + m = replace(m, touch=touch) + zoned = {(label(member), zone[0]) for member, given in touch.items() for zone in given} + t0 = time.perf_counter() + f = R._fit(m, ram, steps=49, distance=Signed(shells, ram.reach())) + seconds = time.perf_counter() - t0 + check(f"bell-crank-clears-on-meshes (side {side:+.0f}): over 0..-125 at 49 steps every member is clear of every part, 5 x {len(parts)} pairs, beside its pins by the record's zones", + f.ok and len(f.pairs) == 5 * len(parts) and set(f.allowed) == zoned, [f.report(), refused(f)]) + fine = R._fit(m, ram, steps=251, distance=Signed(shells)) + check(f"bell-crank-clears-on-meshes (side {side:+.0f}): and at 251 steps with the oracle uncapped", fine.ok, [fine.report(), refused(fine)]) + bare = R._fit(replace(m, touch={}), ram, steps=49, distance=Signed(shells, ram.reach())) + need = needs(m, ram, parts, Signed(shells)) + stated = {} + for member, given in touch.items(): + for zone in given: + stated.setdefault((label(member), zone[0]), []).append(zone) + + def takes(given, pin, radius, depth): # one zone about the pin, or zones about both of the member's pins that meet + return all(zone[3] >= depth for zone in given) and (any(zone[1] == pin and zone[2] >= radius for zone in given) + or (len({zone[1] for zone in given}) == 2 and sum(zone[2] for zone in given) >= radius)) + slack = {pair: takes(stated[pair], *least) for pair, least in need.items() if pair in stated} + check(f"zones (side {side:+.0f}): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + {pair for pair, _, _ in refused(bare)} == set(need) and set(need) <= zoned and all(slack.values()), [refused(bare), sorted(set(need) - zoned), [k for k, v in slack.items() if not v]]) + if side > 0: + winner = (m, f) + def free(fit): # the least margin of the pairs no zone lets: a zoned pair's is its depth's slack at the pin + return min(reading[0] for pair, reading in fit.pairs.items() if pair not in zoned) + RES["readings"].update({"bell crank: least margin of a pair with no zone, 251 steps uncapped": free(fine), + "bell crank: least margin of a zoned pair, 251 steps uncapped": min(reading[0] for pair, reading in fine.pairs.items() if pair in zoned), + "bell crank: pairs": len(f.pairs), "bell crank: zoned pairs": len(f.allowed), "bell crank: pairs refused with nothing let": len(refused(bare)), + "bell crank: seconds, 49 steps capped": seconds}) + RES["zones"] = {f"{pair[0]} | {pair[1]}": {"stated": [list(zone[1:]) for zone in stated[pair]], "least": [pin, round(radius, 4), round(depth, 4)]} for pair, (pin, radius, depth) in sorted(need.items()) if pair in stated} + RES["least pairs"] = sorted((round(v[0], 4), v[1], k[0], k[1]) for k, v in fine.pairs.items() if k not in zoned)[:8] + + SECTION[0] = "zones end" + m, f = winner + for member, part in (("rocker", "parent.bracket"), ("coupler", "child.horn"), ("rod", "rocker.pin.d")): + short = {**m.touch, member: tuple((p_, pin, 0.5 * radius, depth) if p_ == part else (p_, pin, radius, depth) for p_, pin, radius, depth in m.touch[member])} + got = R._fit(replace(m, touch=short), ram, steps=49, distance=Signed(shells, ram.reach())) + check(f"a zone ends at its radius: {member}'s about {part} cut to half, that pair alone is refused", [pair for pair, _, _ in refused(got)] == [(label(member), part)], refused(got)) + + SECTION[0] = "moved x" + # Soul's let_hide probes: a link's place along the axis moved from beside the bracket or horn into it + for name, moved, expect in (("the rocker at x 0.25, inside the bracket's 0.13..0.35", {"rocker": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket")}), + ("the coupler at x 0.25, inside the horn's 0.23..0.31", {"c": 0.25}, {("coupler", "child.horn")}), + ("both", {"rocker": 0.25, "c": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket"), ("coupler", "child.horn")})): + mm = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, 1.0, **moved), parts=parts, touch=m.touch) + got = R._fit(mm, ram, steps=49, distance=Signed(shells, ram.reach())) + inside = {pair: reading for pair, reading, _ in refused(got)} + RES["readings"]["moved x: " + name] = min(inside.values()) if inside else 0.0 + check(f"a pin stood inside what it stands beside is refused: {name}", not got.ok and expect <= set(inside) and all(inside[pair] < -0.015 for pair in expect), refused(got)) + + SECTION[0] = "four bar" + shells4, parts4 = knee("four_bar", DEEP) + m4 = R.Mechanism("four_bar", *HINGE, **pins3(DEEP), parts=parts4) + m4 = replace(m4, touch=zones(m4, ram, parts4)) + f4 = R._fit(m4, ram, steps=49, distance=Signed(shells4, ram.reach())) + hit = {pair: reading for pair, reading, _ in refused(f4)} + RES["readings"]["four bar: barrel inside the shin's clearance"] = hit.get(("barrel[0]", "child.body"), 0.0) + check("third-body: the deep four-bar's ram is refused on the shin, which folds into it", not f4.ok and {("barrel[0]", "child.body"), ("rod[0]", "child.body")} <= set(hit) and f4.clear_at[2] == "child.body", refused(f4)) + + SECTION[0] = "search" + seats = {"rocker": [(X_R, *CRANK["rocker"]), (X_R, CRANK["rocker"][0] - 0.07, CRANK["rocker"][1] + 0.03)], "c": [(X_C, *CRANK["c"]), (X_C, CRANK["c"][0] - 0.05, CRANK["c"][1] + 0.03)], + "a": [(0.0, *CRANK["a"]), (0.0, 0.4, 1.0)], "link": (0.35, 0.5, 3), "d": (0.2, 0.26, 2)} + built = [] + + def world(mech): + made, bodies = knee("bell_crank", {k: (float(getattr(mech, k)[1]), float(getattr(mech, k)[2])) for k in CRANK}) + built.append(mech) + return bodies, zones(mech, ram, bodies), Signed(made, ram.reach()) + t0 = time.perf_counter() + s = R.search("bell_crank", {"pivot": HINGE[0], "axis": HINGE[1], "lo": -125, "hi": 0}, ram, seats, world=world, steps=49) + RES["readings"].update({"search: seconds": time.perf_counter() - t0, "search: candidates": s.tried, "search: pass the gates before clearance": s.fits, + "search: worlds built": len(built), "search: refused on their own parts": s.tally.get("clash", 0)}) + RES["search"] = {"report": s.report(), "seat": {k: np.round(v, 4).tolist() for k, v in (s.seat or {}).items()}, "tally": s.tally} + again = R._fit(s.best.m, ram, steps=251, distance=world(s.best.m)[2]) if s.found else None + check("search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps", + s.found and s.best.ok and len(built) - 1 == s.tally.get("clash", 0) + 1 and again.ok and len(s.best.pairs) == 5 * len(parts), [s.report(), refused(again) if again else None]) + + SECTION[0] = "render" + RES["renders"] = render(winner[0], ram, winner[1], shells, parts) + check("the bell crank is drawn at 0, -62.5 and -125", all(Path(path).is_file() for path in RES["renders"]), RES["renders"]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-8:]) +finally: + RES["ok"] = all(c["ok"] for c in RES["checks"]) + RES["readings"] = {name: (float(f"{value:.3g}") if isinstance(value, float) else value) for name, value in sorted(RES["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(RES, indent=1, default=str), encoding="utf-8") + for c in RES["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", RES["readings"], flush=True) +sys.exit(0 if RES["ok"] else 1) diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json new file mode 100644 index 0000000..8bd0d66 --- /dev/null +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -0,0 +1,504 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", + "ok": true, + "detail": null + }, + { + "name": "three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", + "ok": true, + "detail": null + }, + { + "name": "three-rays: 4000 random points about a box are signed as the box signs them", + "ok": true, + "detail": null + }, + { + "name": "ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", + "ok": true, + "detail": null + }, + { + "name": "the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side +1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side +1): and at 251 steps with the oracle uncapped", + "ok": true, + "detail": null + }, + { + "name": "zones (side +1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side -1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side -1): and at 251 steps with the oracle uncapped", + "ok": true, + "detail": null + }, + { + "name": "zones (side -1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: rocker's about parent.bracket cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: coupler's about child.horn cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: rod's about rocker.pin.d cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: the rocker at x 0.25, inside the bracket's 0.13..0.35", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: the coupler at x 0.25, inside the horn's 0.23..0.31", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: both", + "ok": true, + "detail": null + }, + { + "name": "third-body: the deep four-bar's ram is refused on the shin, which folds into it", + "ok": true, + "detail": null + }, + { + "name": "search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps", + "ok": true, + "detail": null + }, + { + "name": "the bell crank is drawn at 0, -62.5 and -125", + "ok": true, + "detail": null + } + ], + "readings": { + "FLAT": 8.34e-09, + "bell crank: least margin of a pair with no zone, 251 steps uncapped": 0.0336, + "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, + "bell crank: pairs": 60, + "bell crank: pairs refused with nothing let": 19, + "bell crank: seconds, 49 steps capped": 2.12, + "bell crank: zoned pairs": 20, + "four bar: barrel inside the shin's clearance": -0.122, + "jointlib plates: points one ray signs inside, of 24": 24, + "jointlib plates: points the oracle signs inside": 0, + "moved x: both": -0.0543, + "moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02, + "moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543, + "one ray: samples signed inside, of 6912": 0, + "search: candidates": 13824, + "search: pass the gates before clearance": 78, + "search: refused on their own parts": 21, + "search: seconds": 43.3, + "search: worlds built": 22, + "the base clevis's foot inside the thigh": -0.01 + }, + "zones": { + "barrel[0] | parent.seat": { + "stated": [ + [ + "a", + 0.15645000000000003, + 0.0 + ] + ], + "least": [ + "a", + 0.1222, + 0.0 + ] + }, + "barrel[0] | rocker.pin.d": { + "stated": [ + [ + "d", + 0.11105000000000001, + 0.0 + ] + ], + "least": [ + "d", + 0.1108, + 0.0 + ] + }, + "barrel[0] | rocker.seat": { + "stated": [ + [ + "d", + 0.13505, + 0.0 + ] + ], + "least": [ + "d", + 0.1263, + 0.0 + ] + }, + "coupler | child.horn": { + "stated": [ + [ + "c", + 0.11195, + 0.0 + ] + ], + "least": [ + "c", + 0.0947, + 0.0 + ] + }, + "coupler | coupler.pin.c": { + "stated": [ + [ + "c", + 0.08795, + 0.027 + ] + ], + "least": [ + "c", + 0.0474, + 0.0259 + ] + }, + "coupler | coupler.plate": { + "stated": [ + [ + "p", + 0.24152975906703586, + 0.018500000000000016 + ], + [ + "c", + 0.24152975906703586, + 0.018500000000000016 + ] + ], + "least": [ + "p", + 0.4736, + 0.0175 + ] + }, + "coupler | rocker.pin.p": { + "stated": [ + [ + "p", + 0.08795, + 0.027 + ] + ], + "least": [ + "p", + 0.0474, + 0.0259 + ] + }, + "coupler | rocker.plate": { + "stated": [ + [ + "p", + 0.2818973893266964, + 0.0 + ] + ], + "least": [ + "p", + 0.2368, + 0.0 + ] + }, + "rocker | coupler.plate": { + "stated": [ + [ + "p", + 0.26840002998268986, + 0.0 + ] + ], + "least": [ + "p", + 0.2366, + 0.0 + ] + }, + "rocker | parent.bracket": { + "stated": [ + [ + "rocker", + 0.11695, + 0.0 + ] + ], + "least": [ + "rocker", + 0.0946, + 0.0 + ] + }, + "rocker | rocker.pin.R": { + "stated": [ + [ + "rocker", + 0.08995, + 0.029 + ] + ], + "least": [ + "rocker", + 0.0473, + 0.0279 + ] + }, + "rocker | rocker.pin.p": { + "stated": [ + [ + "p", + 0.08795, + 0.027 + ] + ], + "least": [ + "p", + 0.0473, + 0.0259 + ] + }, + "rocker | rocker.plate": { + "stated": [ + [ + "rocker", + 0.2172005150345214, + 0.018500000000000016 + ], + [ + "p", + 0.2172005150345214, + 0.018500000000000016 + ] + ], + "least": [ + "rocker", + 0.4259, + 0.0175 + ] + }, + "rocker arm | parent.bracket": { + "stated": [ + [ + "rocker", + 0.11695, + 0.0 + ] + ], + "least": [ + "rocker", + 0.096, + 0.0 + ] + }, + "rocker arm | rocker.pin.R": { + "stated": [ + [ + "rocker", + 0.08995, + 0.029 + ] + ], + "least": [ + "rocker", + 0.048, + 0.0279 + ] + }, + "rocker arm | rocker.pin.d": { + "stated": [ + [ + "d", + 0.08795, + 0.027 + ] + ], + "least": [ + "d", + 0.048, + 0.0259 + ] + }, + "rocker arm | rocker.plate": { + "stated": [ + [ + "rocker", + 0.12240000000000001, + 0.018500000000000016 + ], + [ + "d", + 0.12240000000000001, + 0.018500000000000016 + ] + ], + "least": [ + "rocker", + 0.24, + 0.0175 + ] + }, + "rod[0] | rocker.pin.d": { + "stated": [ + [ + "d", + 0.07955, + 0.027 + ] + ], + "least": [ + "d", + 0.0794, + 0.0259 + ] + }, + "rod[0] | rocker.seat": { + "stated": [ + [ + "d", + 0.10355, + 0.0 + ] + ], + "least": [ + "d", + 0.0938, + 0.0 + ] + } + }, + "least pairs": [ + [ + 0.0336, + -125.0, + "rocker", + "rocker.pin.d" + ], + [ + 0.0393, + -125.0, + "rod[0]", + "rocker.pin.R" + ], + [ + 0.0417, + 0.0, + "coupler", + "parent.bracket" + ], + [ + 0.0579, + 0.0, + "rocker arm", + "coupler.plate" + ], + [ + 0.0687, + 0.0, + "coupler", + "rocker.pin.R" + ], + [ + 0.0766, + 0.0, + "rocker", + "child.horn" + ], + [ + 0.0766, + 0.0, + "rocker arm", + "child.horn" + ], + [ + 0.0808, + -125.0, + "coupler", + "child.body" + ] + ], + "search": { + "report": "78 of 13824 candidates pass the gates before clearance (failed: arm 1406, assembly 4800, clash 21, load 1355, stroke 1160, toggle 7352); best: OK: L 0.664..0.968, barrel 0.513, stroke 0.458 for travel 0.304 (spare +0.137), arm >= 0.090, rocker swing 99.9, pin load <= 0.73, transmission >= 17.3 deg, clear +0.000", + "seat": { + "a": [ + 0.0, + 0.45, + 1.15 + ], + "rocker": [ + 0.3675, + 0.3171, + 0.3217 + ], + "p": [ + 0.3675, + 0.7683, + 0.5372 + ], + "c": [ + 0.3275, + 0.3493, + 0.1486 + ], + "d": [ + 0.0, + 0.4303, + 0.4866 + ] + }, + "tally": { + "assembly": 4800, + "toggle": 7352, + "arm": 1406, + "stroke": 1160, + "load": 1355, + "clash": 21 + } + }, + "renders": [ + "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_0.png", + "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_62p5.png", + "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_125.png" + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 2651e8c..6b5da5f 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1941,7 +1941,7 @@ class OwnershipTests(unittest.TestCase): return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")} def test_no_pattern_matches(self): - self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "route.py"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "ram.py", "route.py"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): if pattern is self.PACKAGE[2] and name == "__init__.py": diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py new file mode 100644 index 0000000..1fbe829 --- /dev/null +++ b/surfaces/blender/tests/test_ram.py @@ -0,0 +1,1180 @@ +"""brokkr_kitbash/ram.py under plain Python: each case is a mechanism whose answer is known by hand, by a second +method (central differences, loop closure) or from the R-3 knee probes the docs cite. Bodies are analytic signed +distance oracles: boxes, capsules and cylinders across x, each a named part of a body. They defend the gate's rule; +the R-3 knee's clearance on meshes is tests/live/ram_knee.py's, in a Blender, not these stand-ins. + +Bounds follow lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped reading and the least +mutant's, both written beside the constant.""" +import importlib.util +import json +import math +import sys +import unittest +from dataclasses import replace +from pathlib import Path + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +SURFACE = Path(__file__).resolve().parents[1] +if np is not None: + spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "brokkr_kitbash" / "ram.py") + R = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = R + spec.loader.exec_module(R) + +X, O = (1.0, 0.0, 0.0), (0.0, 0.0, 0.0) + + +def turned(point, degrees, pivot=O, axis=X): + """A point turned about an axis: Rodrigues by matrix, a second route to ram._rot.""" + x, y, z = axis + c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) + k = np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]], dtype=float) + m = np.eye(3) * c + s * k + (1 - c) * np.outer(axis, axis) + return np.asarray(pivot, float) + m @ (np.asarray(point, float) - np.asarray(pivot, float)) + + +class Bodies: + """A signed distance oracle over analytic shapes. parts: name -> (body, shapes), a shape ("capsule", p, q, r), + ("box", lo, hi) or ("cyl", centre, r, half): a cylinder across x. Inside a shape the distance is negative, its + depth. `cap` caps what it returns outside. A part it was not given raises.""" + + def __init__(self, parts, cap=None): + self.parts = {name: body for name, (body, _) in parts.items()} + self.shapes = {name: list(shapes) for name, (_, shapes) in parts.items()} + self.cap, self.asked = cap, 0 + + @staticmethod + def one(shape, pts): + if shape[0] == "capsule": + p, q = np.asarray(shape[1], float), np.asarray(shape[2], float) + along = q - p + t = np.clip(((pts - p) @ along) / max(along @ along, 1e-18), 0.0, 1.0) + return np.linalg.norm(pts - p - t[:, None] * along, axis=1) - shape[3] + if shape[0] == "box": + out = np.maximum(np.asarray(shape[1], float) - pts, pts - np.asarray(shape[2], float)) + return np.linalg.norm(np.maximum(out, 0.0), axis=1) + np.minimum(out.max(axis=1), 0.0) + rel = pts - np.asarray(shape[1], float) + round_, flat = np.hypot(rel[:, 1], rel[:, 2]) - shape[2], np.abs(rel[:, 0]) - shape[3] + return np.hypot(np.maximum(round_, 0.0), np.maximum(flat, 0.0)) + np.minimum(np.maximum(round_, flat), 0.0) + + def __call__(self, part, pts): + self.asked += len(pts) + out = np.full(len(pts), math.inf) + for shape in self.shapes[part]: + out = np.minimum(out, self.one(shape, pts)) + return out if self.cap is None else np.minimum(out, self.cap) + + +def two(parent=(), child=(), cap=None, **more): + """Bodies of a direct ram: one part a body, named for it, and any more parts given as name=(body, shapes).""" + return Bodies({"parent": ("parent", parent), "child": ("child", child), **more}, cap) + + +def dressed(m, bodies, touch=None): + """The mechanism with the bodies' parts in its record, and each member's zones (part, pin, radius, depth).""" + return replace(m, parts=bodies.parts, touch=touch or {}) + + +def yz(p, x=0.0): + return (x, float(p[0]), float(p[1])) + + +def grid(lo, hi, counts): + lo, hi = np.asarray(lo, float), np.asarray(hi, float) + axes = [np.linspace(lo[k], hi[k], n) if n > 1 else np.array([(lo[k] + hi[k]) / 2]) for k, n in enumerate(counts)] + return [np.array((x, y, z)) for x in axes[0] for y in axes[1] for z in axes[2]] + + +# The R-3 knee (pivot at the origin, hinge x, shin hanging -z, flexing negative), bore 0.042: the bodies of the +# clevis knee as the joint library draws them, without its ram. +BORE = 0.042 +R3_THIGH = [("box", (-0.13, -0.14, 0.3), (0.13, 0.14, 1.15)), ("box", (-0.095, -0.12, 0.0), (0.095, 0.12, 0.4)), ("cyl", O, 0.225, 0.095)] +R3_SHIN = ([("cyl", O, 0.25, 0.18), ("cyl", O, 0.19, 0.205), ("box", (-0.11, -0.11, -0.95), (0.11, 0.11, -0.49)), + ("box", (-0.21, 0.12, -0.91), (0.21, 0.18, -0.33)), ("box", (-0.2325, -0.1, -0.87), (-0.1875, 0.1, -0.37)), + ("box", (0.1875, -0.1, -0.87), (0.2325, 0.1, -0.37))] + # the cheeks taper from the hub's 0.25 to 0.12 at the foot: five steps outside the taper + + [("box", (-0.18, -(0.25 - 0.026 * k), -0.19 * (k + 1)), (0.18, 0.25 - 0.026 * k, -0.19 * k)) for k in range(5)]) +AXLE, PIN = 0.028, 0.026 # the rocker's axle and a link pin, radius +X_COUPLER, X_ROCKER = 0.3275, 0.3675 # the twin link plates' centres as the R-3 probe stacks them (0.31..0.345, 0.35..0.385) + +# P2's deep knee: a four-bar behind the knee (y < 0), where the shin folds to. +DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284), + "c": (0.06881023105761902, -0.3143743967236484), "d": (-0.43650046730511183, -0.017951928782268284)} +# P2's bell crank: in front of the knee (y > 0), which the shin leaves as it folds. +CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "p": (0.7282866960904424, 0.43261578669776135), + "c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)} + + +def r3(kind, pins, side=1.0, lo=-125.0, hi=0.0): + """An R-3 linkage with its links' plates on one side of the knee: the ram on the centre plane.""" + at = {"a": 0.0, "p": 0.0, "d": 0.0, "rocker": side * X_ROCKER, "c": side * X_COUPLER} + return R.Mechanism(kind, O, X, lo, hi, **{name: yz(pins[name], at[name]) for name in pins}) + + +def r3_parts(m, ram, cap=None): + """Bodies of an R-3 linkage: the thigh and shin, the bracket the rocker's pivot stands in (a boss on the thigh, + x 0.13..0.35) and the horn c stands in (on the shin, 0.18..0.31), and the mechanism's own links as parts: twin + plates of link_r, the rocker's axle through the knee's width, and the pins at p, c and (a bell crank) d.""" + def twin(p, q, x): + return [("capsule", (s * x, p[1], p[2]), (s * x, q[1], q[2]), ram.link_r) for s in (-1.0, 1.0)] + + def across(at, r): + return [("capsule", (-X_ROCKER, at[1], at[2]), (X_ROCKER, at[1], at[2]), r)] + + def boss(at, r, x0, x1): + return [("cyl", (s * 0.5 * (x0 + x1), at[1], at[2]), r, 0.5 * (x1 - x0)) for s in (-1.0, 1.0)] + crank = m.kind == "bell_crank" + parts = {"thigh": ("parent", R3_THIGH), "shin": ("child", R3_SHIN), "bracket": ("parent", boss(m.rocker, 0.055, 0.13, 0.35)), + "horn": ("child", boss(m.c, 0.05, 0.18, 0.31)), + "rocker plates": ("rocker", twin(m.rocker, m.p, X_ROCKER) + (twin(m.rocker, m.d, X_ROCKER) if crank else [])), + "rocker axle": ("rocker", across(m.rocker, AXLE)), "pin p": ("rocker", across(m.p, PIN)), + "coupler plates": ("coupler", twin(m.p, m.c, X_COUPLER)), "pin c": ("coupler", across(m.c, PIN))} + if crank: + parts["pin d"] = ("rocker", across(m.d, PIN)) + return Bodies(parts, cap) + + +def near(ram, member, spacing=None): + """What a member's sample keeps from a part outside a zone: its radius, the gap and half the spacing.""" + radius = {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + return radius + ram.gap + ram.spacing(spacing) / 2 + + +def scissor(m, ram): + """How far from p a link and the plates beside it on p part: they cross at the transmission angle, their + centres X_ROCKER - X_COUPLER apart along the axis, and part where the bars' axes are link_r + near apart.""" + mu = math.radians(float(R.pose(m, np.linspace(m.lo, m.hi, 49)).mu_p.min())) + return math.sqrt((ram.link_r + near(ram, "rocker")) ** 2 - (X_ROCKER - X_COUPLER) ** 2) / math.sin(mu) + + +def r3_bodies(m, ram, cap=None): + """(Bodies, touch) of an R-3 linkage. A zone about a pin is the eye's radius plus what the member keeps: the + pin's or boss's radius plus near(member). Its depth is the pin's radius where the pin runs through the member's + eye, 0 for the boss or plate the member stands beside, link_r over a link's own plates, which are zoned about + both of the link's pins, each a little over half its length (a zone is no wider than its member). The plates + beside a link on p are let as far as the two part (scissor).""" + bodies, crank = r3_parts(m, ram, cap), m.kind == "bell_crank" + link, eye, cross = near(ram, "rocker"), "pin d" if crank else "pin p", scissor(m, ram) + arm = float(np.linalg.norm(R._flat(m.d - m.rocker, m.axis))) + + def own(part, a, b, span): + return [(part, a, 0.51 * span, ram.link_r), (part, b, 0.51 * span, ram.link_r)] + touch = {"barrel": [(eye, "d", PIN + near(ram, "barrel"), 0.0)], "rod": [(eye, "d", PIN + near(ram, "rod"), PIN)], + "rocker": [("bracket", "rocker", 0.055 + link, 0.0), ("rocker axle", "rocker", AXLE + link, AXLE), ("pin p", "p", PIN + link, PIN), + *own("rocker plates", "rocker", "p", m.lr), ("coupler plates", "p", cross, 0.0)], + "coupler": [("horn", "c", 0.05 + link, 0.0), ("pin c", "c", PIN + link, PIN), ("pin p", "p", PIN + link, PIN), + *own("coupler plates", "p", "c", m.lc), ("rocker plates", "p", cross, 0.0)]} + if crank: + touch["rocker arm"] = [("bracket", "rocker", 0.055 + link, 0.0), ("rocker axle", "rocker", AXLE + link, AXLE), ("pin d", "d", PIN + link, PIN), + *own("rocker plates", "rocker", "d", arm)] + return bodies, touch + + +def let(touch): + """(member, part) of every zone.""" + return {(member, zone[0]) for member, zones in touch.items() for zone in zones} + + +@unittest.skipIf(np is None, "numpy is not installed") +class HandCases(unittest.TestCase): + """The six hand cases of the solver this one replaces, on a direct ram.""" + A, B = (0, -0.3, 1.0), (0, -0.3, -1.0) + + def direct(self, lo, hi, a=None, b=None): + return R.Mechanism("direct", O, X, lo, hi, a=self.A if a is None else a, b=self.B if b is None else b) + + def test_lengths_by_hand(self): + m = self.direct(-60, 0) + rest = R.pose(m, 0.0) + self.assertAlmostEqual(float(rest.L[0]), 2.0, places=12) + # at rest the ram runs along z at y = -0.3: its arm about x is 0.3 + self.assertAlmostEqual(abs(float(rest.dL[0])), 0.3, places=12) + f = R.fit(m, R.Ram(0.05)) + eye = turned(self.B, -60) + self.assertAlmostEqual(f.l_min, float(np.linalg.norm(eye - np.array(self.A))), places=12) + self.assertAlmostEqual(f.barrel + f.ram.e_a + f.ram.e_b + f.ram.over, f.l_min, places=12) + self.assertAlmostEqual(float(R.extension(m, f.ram, 0.0)[0]), f.travel + f.ram.over, places=12) + self.assertAlmostEqual(float(R.extension(m, f.ram, -60.0)[0]), f.ram.over, places=12) + self.assertEqual(f.barrel, R.barrel_length(m, f.ram)) + + def test_stroke_refused_and_a_trunnion_holds_more(self): + m = self.direct(-120, 0, (0, -0.25, 0.3), (0, -0.25, -0.3)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(0.05)) + self.assertEqual((caught.exception.kind, caught.exception.gate), ("direct", "stroke")) + # the refusal names the angle of the shortest length and the eye's pin + angles = np.linspace(-120, 0, 25) + shortest = float(angles[int(np.argmin(R.length(m, angles)))]) + self.assertEqual((caught.exception.angle, caught.exception.pin), (shortest, "b")) + self.assertIn(f"direct ram: stroke at {shortest:g} deg (pin b)", str(caught.exception)) + trunnion = R._fit(m, R.Ram(0.05, tail=0.25)) + self.assertGreater(trunnion.barrel, caught.exception.fit.barrel + 0.3) + + def test_spare_counts_the_overtravel_at_both_ends(self): + # barrel = L_min - over - e_a - e_b and spare = barrel - gland - travel - 2 over, by hand + m, ram = self.direct(-60, 0), R.Ram(0.05) + f = R.fit(m, ram) + self.assertAlmostEqual(f.spare, f.l_min - 3 * ram.over - ram.e_a - ram.e_b - ram.gland - f.travel, places=12) + # a ram whose stroke fits only without the overtravel is refused + tight = R.Ram(0.05, over=(f.l_min - ram.e_a - ram.e_b - ram.gland - f.travel) / 3 + 1e-6) + with self.assertRaises(R.RamError) as caught: + R.fit(m, tight) + self.assertEqual(caught.exception.gate, "stroke") + + def test_toggle_refused(self): + # a ram whose line crosses the hinge axis inside the range has a dead centre; its arm is not small at + # either end, so only the sign tells + m = self.direct(-40, 40, (0, 0.0, 1.0), (0, 0.2, -1.0)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(0.04, min_arm=0.0)) + refusal = caught.exception + self.assertEqual(refusal.gate, "toggle") + self.assertEqual(refusal.fit.arm_sign, 0) + self.assertTrue(-40 < refusal.angle < 40, refusal.angle) + self.assertEqual(refusal.pin, "b") + self.assertIn(f"toggle at {refusal.angle:g} deg (pin b)", str(refusal)) + # the dead centre 1.7 degrees inside one end: past it the arm is 0.015 at most, and its sign still tells + edge = R._fit(self.direct(-13, 40, (0, 0.0, 1.0), (0, 0.2, -1.0)), R.Ram(0.04, min_arm=0.0)) + self.assertEqual([w[0] for w in edge.why], ["toggle"]) + self.assertLess(max(row[2] for row in edge.table), TOGGLE_ARM) + + def test_clash_and_which(self): + m, ram = self.direct(-60, 0), R.Ram(0.05) + thin = two(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.2)]) + f = R.fit(dressed(m, thin), ram, distance=thin, spacing=0.02) + self.assertGreater(f.clear_min, 0.0) + thick = two(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.3)]) + with self.assertRaises(R.RamError) as caught: + R.fit(dressed(m, thick), ram, distance=thick, spacing=0.02) + refusal = caught.exception + self.assertEqual(refusal.gate, "clash") + self.assertIn("part 'parent' (parent)", str(refusal)) + self.assertEqual(refusal.fit.clear_at[2], "parent") + # the refusal names the angle and the nearer pin of the member + self.assertEqual(refusal.pin, refusal.fit.clear_at[3]) + self.assertIn(refusal.pin, ("a", "b")) + self.assertIn(f"clash at {refusal.angle:g} deg (pin {refusal.pin})", str(refusal)) + # an obstacle that turns with the child is the same obstacle, turned, on the parent + p, q = np.array((-0.2, -0.6, -0.9)), np.array((0.2, -0.6, -0.5)) + wide = self.direct(-50, 35) + for angle in (-50.0, 0.0, 35.0): + on_child, on_parent = two(child=[("capsule", p, q, 0.1)]), two(parent=[("capsule", turned(p, angle), turned(q, angle), 0.1)]) + mine, theirs = R.clearance(dressed(wide, on_child), ram, angle, on_child), R.clearance(dressed(wide, on_parent), ram, angle, on_parent) + self.assertAlmostEqual(float(mine.margin[0]), float(theirs.margin[0]), places=9) + self.assertEqual(mine.where[2], "child") + box = two(parent=[("box", (-0.2, -0.36, -0.2), (0.2, -0.2, 0.2))]) + self.assertLess(R._fit(dressed(self.direct(-10, 0), box), ram, distance=box).clear_min, 0.0) + + def test_the_barrel_runs_from_its_back_end(self): + # a ball beside the barrel's last 0.03, 0.005 inside what the barrel keeps: refused naming the barrel, and + # clear of the rod by 0.0265. S1 (the barrel's front taken from the base pin, e_a = 0.085 short) reads the + # barrel +0.007 clear and fits + m, ram, spacing = self.direct(-60, 0), R.Ram(0.05), 0.005 + p = R.pose(m, 0.0) + side = np.cross(p.u[0], X) + front = p.base[0] + p.u[0] * (ram.back + R.barrel_length(m, ram)) + centre = front - 0.03 * p.u[0] + side * (near(ram, "barrel", spacing) + 0.01 - 0.005) + ball = two(parent=[("capsule", centre, centre, 0.01)]) + c = R.clearance(dressed(m, ball), ram, 0.0, ball, spacing) + self.assertAlmostEqual(c.pairs[("barrel[0]", "parent")][0], -0.005, places=6) # the nearest sample stands up to 0.0025 along + self.assertEqual(c.where[:3], (0.0, "barrel[0]", "parent")) + self.assertGreater(c.pairs[("rod[0]", "parent")][0], 0.02) + # and the rod from there: a ball beside the rod just past the front keeps the rod's need, not the barrel's + centre = front + 0.03 * p.u[0] + side * (near(ram, "rod", spacing) + 0.01 + 0.005) + ball = two(parent=[("capsule", centre, centre, 0.01)]) + c = R.clearance(dressed(m, ball), ram, 0.0, ball, spacing) + self.assertAlmostEqual(c.pairs[("rod[0]", "parent")][0], 0.005, places=6) + + def test_reach_is_the_widest_members(self): + fat = R.Ram(0.05, link_r=0.1) # S9: a link wider than the barrel + self.assertAlmostEqual(fat.reach(0.02), 0.1 + fat.gap + 0.01, places=15) + self.assertAlmostEqual(R.Ram(0.05).reach(), 0.0625 + 0.0075 + 0.03125, places=15) + + def test_search_tally_and_nearest_miss(self): + ram, hinge = R.Ram(0.05), {"pivot": O, "axis": X, "lo": -70, "hi": 0} + seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} + pin = two(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.18)]) + s = R.search("direct", hinge, ram, seats, world=lambda m: (pin.parts, {}, pin)) + self.assertTrue(s.found and s.best.ok and s.fits < s.tried == 225 and s.tally, s.report()) + for a in seats["a"]: # no fitting pair has a larger least arm + for b in seats["b"]: + f = R._fit(dressed(R.Mechanism("direct", O, X, -70, 0, a=a, b=b), pin), ram, distance=pin) + self.assertTrue(not f.ok or f.arm_min <= s.best.arm_min) # the same arithmetic on the same pins: no tolerance + none = R.search("direct", {**hinge, "lo": -100}, ram, {"a": [(0, -0.1, 0.2)], "b": [(0, -0.1, -0.2)]}) + self.assertFalse(none.found) + self.assertIn("stroke", none.tally) + self.assertIn("no candidate of 1 fits", none.report()) + self.assertFalse(none.best.ok) + self.assertEqual(tuple(none.seat["a"]), (0, -0.1, 0.2)) + + def test_swept_holds_the_ram(self): + f = R.fit(self.direct(-60, 0), R.Ram(0.05)) + for body in ("parent", "child"): + pts = R.swept(f, body, margin=0.02) + lo, hi = pts.min(axis=0), pts.max(axis=0) + p = R.pose(f.m, np.linspace(-60, 0, 31)) + line = p.base[:, None, :] + (p.eye - p.base)[:, None, :] * np.linspace(0, 1, 9)[None, :, None] + inside = R._into(f.m, p, body, line).reshape(-1, 3) + self.assertTrue((inside >= lo).all() and (inside <= hi).all(), body) # each end of the line is its ring's centre, to the bit + # seen from the child the eye stands still + self.assertLess(float(np.abs(R._into(f.m, p, "child", p.eye[:, None, :]) - np.array(self.B)).max()), EYE_STILL) + with self.assertRaises(R.RamError): + R.swept(f, "rocker") + + def test_swept_grows_by_the_margin_and_holds_a_trunnions_tail(self): + m = self.direct(-60, 0) + f = R.fit(m, R.Ram(0.05)) + bare, grown = R.swept(f, "parent"), R.swept(f, "parent", margin=0.02) + self.assertAlmostEqual(float(grown[:, 0].max() - bare[:, 0].max()), 0.02, places=12) # across the ram, along the axis + # a trunnion's barrel runs `tail` behind the base pin, here upward: the sweep reaches there + tail = R.swept(R._fit(m, R.Ram(0.05, tail=0.25)), "parent") + self.assertTrue(0.2 < float(tail[:, 2].max() - bare[:, 2].max()) <= 0.25) + + +# Frames, each bound the geometric mean of the shipped reading and its mutant's (scratch readings.py, h3). +EYE_STILL = 2.0e-8 # the eye seen from the child: shipped 2.2e-16, S4 (the child's frame turned the other way) 1.76, separation 9e7 +REST_BOUND = 9.6e-9 # the rest pose against the record: shipped 1.1e-16, the loop closed on the other branch 0.835, separation 9e7 +OWN_FRAME = 1.6e-8 # a member seen from its own body: shipped 3.3e-16, S3 (the coupler's frame turned by the rocker's angle) 0.742, S4 0.728, separation 5e7 + + +@unittest.skipIf(np is None, "numpy is not installed") +class Loop(unittest.TestCase): + def test_loop_closes(self): + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + p = R.pose(m, np.linspace(-125, 0, 49)) + n = np.array(X) + # the coupler keeps its length, the rocker its own + self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - p.C, n), axis=1) - m.lc).max()), LOOP_BOUND, kind) + self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - m.rocker, n), axis=1) - m.lr).max()), LOOP_BOUND, kind) + # the coupler body, carried by its angle from the rocker's pin, lands its c on the child's c + for i, angle in enumerate(p.degrees): + c_on_coupler = p.P[i] + R._flat(turned(m.c - m.p, math.degrees(p.psi[i]), O), n) + self.assertLess(float(np.linalg.norm(R._flat(c_on_coupler - turned(m.c, angle), n))), LOOP_BOUND, (kind, angle)) + # and the rest pose is the record's + self.assertLess(float(np.abs(p.P[-1] - m.p).max()), REST_BOUND) + self.assertLess(float(np.abs(p.eye[-1] - m.d).max()), REST_BOUND) + + def test_the_branch_is_the_rest_poses_at_every_angle(self): + # the pin p keeps its side of R -> c from rest: an angle alone gives the pose, in any order, and a mirror + # solution (the other circle crossing) is never taken, however close it comes + m = r3("four_bar", DEEP) + n = np.array(X) + angles = np.linspace(-125, 0, 49) + shuffled = np.random.default_rng(5).permutation(angles) + whole = R.pose(m, shuffled) + for i in (0, 17, 48): + alone = R.pose(m, float(shuffled[i])) + self.assertEqual(alone.P[0].tolist(), whole.P[i].tolist()) + side = np.cross(R._flat(whole.C - m.rocker, n), R._flat(whole.P - m.rocker, n)) @ n + self.assertTrue((np.sign(side) == m.branch).all()) + # a loop that all but reaches its dead centre (the two crossings 1 mm apart there) and leaves again: asked + # in any order, p keeps its side + near = near_dead_centre() + p = R.pose(near, np.random.default_rng(6).permutation(np.linspace(-60, 60, 241))) + side = np.cross(R._flat(p.C - near.rocker, n), R._flat(p.P - near.rocker, n)) @ n + self.assertTrue((np.sign(side) == near.branch).all()) + self.assertLess(float(np.abs(side).min()), NEAR_BOUND) + + def test_swing_counts_a_rocker_past_half_a_turn(self): + # a drag link (ground 0.2, crank 0.6, rocker 0.7, coupler 0.55) turns its rocker with the crank, past 180 + # degrees from rest: the swing is the travel, the integral of dphi/dtheta, not the spread of wrapped angles + Rk, c, lr, lc, n = np.array((0, 0.2, 0.0)), np.array((0, 0.0, -0.6)), 0.7, 0.55, np.array(X) + span = np.linalg.norm(c - Rk) + x = (lr * lr - lc * lc + span * span) / (2 * span) + p = Rk + (c - Rk) / span * x + np.cross(n, (c - Rk) / span) * math.sqrt(lr * lr - x * x) + m = R.Mechanism("four_bar", O, X, -300, 0, a=(0, -1.5, 1.0), rocker=Rk, p=p, c=c, d=p) + f = R._fit(m, R.Ram(0.03), steps=121) + at = R.pose(m, np.linspace(-300, 0, 121)) + travel = abs(math.degrees(float(((at.dphi[1:] + at.dphi[:-1]) / 2 * np.diff(np.radians(at.degrees))).sum()))) + self.assertAlmostEqual(travel, 291.40, places=1) + self.assertLess(abs(f.swing - travel), SWING_BOUND) + + def test_assembly_refused_naming_the_angle(self): + # the same loop with the child's pin 1 mm farther out: past 19 degrees the rocker and coupler cannot reach + with self.assertRaises(R.RamError) as caught: + R.pose(near_dead_centre(reach=-1e-3), np.linspace(-60, 60, 241)) + refusal = caught.exception + self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "assembly")) + self.assertTrue(10.0 < refusal.angle < 20.0, refusal.angle) + self.assertEqual(refusal.pin, "c") + self.assertIn(f"assembly at {refusal.angle:g} deg (pin c)", str(refusal)) + # a range that does not hold the rest pose is reached from rest: a dead centre on the way is refused, + # though every angle of the range itself assembles + far = near_dead_centre(reach=-1e-3, lo=30, hi=60) + self.assertEqual(len(R.pose(far, [30.0, 60.0]).L), 2) + with self.assertRaises(R.RamError) as caught: + R.fit(far, R.Ram(0.03)) + self.assertEqual(caught.exception.gate, "assembly") + self.assertTrue(0.0 < caught.exception.angle < 30.0) + + +def near_dead_centre(reach=1e-6, lo=-60.0, hi=60.0): + """A four-bar whose rocker (0.6) and coupler (0.5 + reach) lie all but in line at +20 degrees, where the child's + pin is farthest from R (1.1): with a negative reach they cannot span it.""" + Rk, lr, lc = np.array((0.0, -0.6, 0.0)), 0.6, 0.5 + reach + c = np.array((0.0, 0.5 * math.cos(math.radians(-20)), 0.5 * math.sin(math.radians(-20)))) + span = np.linalg.norm(c - Rk) + x = (lr * lr - lc * lc + span * span) / (2 * span) + across = (c - Rk) / span + p = Rk + across * x + np.cross(np.array(X), across) * math.sqrt(lr * lr - x * x) + return R.Mechanism("four_bar", O, X, lo, hi, a=(0, -0.9, 1.0), rocker=Rk, p=p, c=c, d=p) + + +@unittest.skipIf(np is None, "numpy is not installed") +class Rates(unittest.TestCase): + H = 1e-4 # degrees + + def central(self, m, angles, what): + up, down = R.pose(m, angles + self.H), R.pose(m, angles - self.H) + if what == "phi": + return (up.phi - down.phi) / math.radians(2 * self.H) + return (up.L - down.L) / math.radians(2 * self.H) + + def test_rates_equal_central_differences(self): + angles = np.linspace(-124.9, -0.1, 49) + worst = 0.0 + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + p = R.pose(m, angles) + worst = max(worst, float(np.abs(p.dphi - self.central(m, angles, "phi")).max()), float(np.abs(p.dL - self.central(m, angles, "L")).max())) + self.assertLess(worst, RATE_BOUND) + + def test_direct_rate_is_the_lever_arm(self): + m = R.Mechanism("direct", O, X, -60, 20, a=(0.1, -0.3, 1.0), b=(-0.05, -0.35, -0.8)) + angles = np.linspace(-59.9, 19.9, 33) + p = R.pose(m, angles) + arm = np.array([np.array(X) @ np.cross(turned(m.b, t), (turned(m.b, t) - m.a) / np.linalg.norm(turned(m.b, t) - m.a)) for t in angles]) + self.assertLess(float(np.abs(p.dL - arm).max()), LEVER_BOUND) + self.assertLess(float(np.abs(p.dL - self.central(m, angles, "L")).max()), RATE_BOUND) + + def test_load_is_the_coupler_force(self): + # virtual work: the ram's force F over dL is the coupler's force over the child pin's travel along the coupler + m = r3("bell_crank", CRANK) + angles = np.linspace(-124.9, -0.1, 25) + p = R.pose(m, angles) + up, down = R.pose(m, angles + self.H), R.pose(m, angles - self.H) + k = R._flat(p.P - p.C, np.array(X)) + k = k / np.linalg.norm(k, axis=1)[:, None] + along = ((up.C - down.C) * k).sum(axis=1) / math.radians(2 * self.H) + self.assertLess(float(np.abs(p.load - np.abs(self.central(m, angles, "L") / along)).max()), LOAD_WORK_BOUND) + + def test_transmission_at_p_is_the_angle_between_coupler_and_rocker(self): + m = r3("bell_crank", CRANK) + p = R.pose(m, np.linspace(-125, 0, 49)) + n = np.array(X) + k, link = R._flat(p.P - p.C, n), R._flat(p.P - m.rocker, n) + cos = np.abs((k * link).sum(axis=1)) / np.linalg.norm(k, axis=1) / np.linalg.norm(link, axis=1) + self.assertLess(float(np.abs(np.degrees(np.arccos(cos)) - p.mu_p).max()), MU_BOUND) + self.assertAlmostEqual(R._fit(m, R.Ram(BORE), steps=49).mu_p, 21.743, places=2) + + +# Each bound is the geometric mean of the shipped reading and the least mutant's (lodur:ruling:deterministic-bound-margin). +# The greatest gap between a closed-form rate and its central difference (h 1e-4 deg), per radian. +# Shipped 2.44e-10; M2 (the direct arm formula on a linkage, dphi/dtheta dropped) 0.741; separation 3.0e9. +RATE_BOUND = 1.34e-5 +# Loop closure, the links' lengths and the coupler's far end: shipped 2.2e-16; the rocker and coupler lengths +# swapped in the circle crossing 0.141; separation 6.4e14. +LOOP_BOUND = 5.6e-9 +# The direct ram's dL/dtheta against the lever arm by hand: shipped 0 (the same arithmetic by a second route; 1e-16, +# one rounding, stands for it); the arm taken at the rest eye 0.776; separation 7.8e15. +LEVER_BOUND = 8.8e-9 +# Pin load against virtual work by central differences: shipped 3.19e-10; X5 (the moment arm taken as the crank's +# length) 0.857; separation 2.7e9. +LOAD_WORK_BOUND = 1.65e-5 +# The transmission angle at p against the angle by hand, degrees: shipped 2.0e-13; X14 (mu_p read from the crank's) +# 11.3; separation 5.7e13. +MU_BOUND = 1.5e-6 +# How near its dead centre the fixture loop comes (|side|, a fixture guard): reach 1e-6 reads 8.12e-4; the next +# coarser fixture, reach 1e-5, 2.57e-3; separation 3.2. +NEAR_BOUND = 1.44e-3 +# The drag link's swing against its travel, degrees: shipped 0.00 (to the 0.01 the test reads); X2 (no unwrap) 65.9; +# 0.01 stands for the shipped reading; separation 6.6e3. +SWING_BOUND = 0.81 +# The greatest arm past the dead centre of the edge toggle case: shipped 0.0149; X12's threshold 0.1; separation 6.7. +TOGGLE_ARM = 0.0386 + + +@unittest.skipIf(np is None, "numpy is not installed") +class DeepKnee(unittest.TestCase): + """The R-3 knee over 0..-125 (probes P1 to P3).""" + + def test_four_bar_fits_and_reproduces_the_probe(self): + f = R.fit(r3("four_bar", DEEP), R.Ram(BORE), steps=49) + self.assertAlmostEqual(f.swing, 70.537, places=2) + self.assertAlmostEqual(f.l_min, 0.7220, places=3) + self.assertAlmostEqual(f.l_max, 1.1680, places=3) + self.assertAlmostEqual(f.spare, 0.0533, places=3) + self.assertAlmostEqual(f.mu_c, 16.50, places=1) + greatest = max(abs(row[2]) for row in f.table) + # the least and greatest knee arm and the greatest pin load, each under a bound the direct-arm mutant passes + self.assertAlmostEqual(f.arm_min, 0.0962, places=3) + self.assertLess(f.arm_min, ARM_LEAST) + self.assertLess(greatest, ARM_GREATEST) + self.assertLess(f.load_max, LOAD) + + def test_load_gate(self): + m = r3("four_bar", DEEP) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(BORE, max_load=LOAD_GATE), steps=49) + refusal = caught.exception + self.assertEqual((refusal.kind, refusal.gate, refusal.pin), ("four_bar", "load", "c")) + self.assertIn(f"load at {refusal.angle:g} deg (pin c)", str(refusal)) + self.assertTrue(R.fit(m, R.Ram(BORE), steps=49).ok) + + def test_the_same_seats_as_a_direct_ram_are_refused(self): + # the ram's own seats with no linkage, a on the thigh and the eye on the shin's pin: refused + direct = R.Mechanism("direct", O, X, -125, 0, a=yz(DEEP["a"]), b=yz(DEEP["c"])) + with self.assertRaises(R.RamError) as caught: + R.fit(direct, R.Ram(BORE), steps=49) + self.assertEqual(caught.exception.gate, "arm") + # and no direct seat of a wide grid behind the knee fits 0..-125 (P1), while the joint library's fits 0..-62 + ram = R.Ram(BORE) + bodies = two(R3_THIGH, R3_SHIN) + world = lambda m: (bodies.parts, {}, bodies) + wide = {"a": grid((0, -0.40, 0.35), (0, -0.16, 1.3), (1, 5, 10)), "b": grid((0, -0.40, -0.85), (0, -0.14, -0.25), (1, 5, 8))} + self.assertFalse(R.search("direct", {"pivot": O, "axis": X, "lo": -125, "hi": 0}, ram, wide, world=world).found) + seats = {"a": grid((0, -0.36, 0.45), (0, -0.24, 1.05), (1, 3, 6)), "b": grid((0, -0.34, -0.85), (0, -0.2, -0.35), (1, 3, 6))} + found = R.search("direct", {"pivot": O, "axis": X, "lo": -62, "hi": 0}, ram, seats, world=world) + self.assertTrue(found.found and found.best.clear_min >= 0.0, found.report()) + + def test_third_body(self): + # the four-bar's ram spans the thigh and the rocker; at -125 the shin has folded into it (P3's mesh check) + m, ram = r3("four_bar", DEEP), R.Ram(BORE) + bodies, touch = r3_bodies(m, ram) + with self.assertRaises(R.RamError) as caught: + R.fit(dressed(m, bodies, touch), ram, steps=49, distance=bodies) + refusal = caught.exception + self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "clash")) + self.assertEqual(refusal.fit.clear_at[2], "shin") + self.assertIn(refusal.fit.clear_at[1], ("barrel[0]", "rod[0]")) + self.assertIn("part 'shin' (child)", str(refusal)) + self.assertLess(refusal.angle, -100.0) + self.assertLess(refusal.fit.pairs[("barrel[0]", "shin")][0], 0.0) + # with the shin and the coupler's parts emptied, the thigh and the rocker the ram spans leave it clear + for part in ("shin", "coupler plates", "pin c"): + bodies.shapes[part] = [] + self.assertGreaterEqual(float(R.clearance(dressed(m, bodies, touch), ram, np.linspace(-125, 0, 49), bodies).margin.min()), 0.0) + + def test_a_part_in_the_rams_way_on_each_link(self): + # a lug on the rocker, then on the coupler, on the rod's axis 0.12 from the eye at -60: refused naming the part + # and its body. A zone about the eye lets the rod and the barrel by it only if it reaches the lug and is as + # deep as the lug; a zone of another member's changes nothing + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + at = R.pose(m, -60.0) + on_rod = (at.eye - 0.12 * at.u)[:, None, :] + for body in ("rocker", "coupler"): + bodies, touch = r3_bodies(m, ram) + spot = R._into(m, at, body, on_rod)[0, 0] + bodies.parts["lug"], bodies.shapes["lug"] = body, [("capsule", spot - (0.1, 0, 0), spot + (0.1, 0, 0), 0.02)] + + def zones(radius, depth, members=("rod", "barrel")): + return {**touch, **{member: touch[member] + [("lug", "d" if member != "coupler" else "p", radius, depth)] for member in members}} + for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)), + ("a zone too shallow", zones(0.4, 0.01))): + with self.assertRaises(R.RamError) as caught: + R.fit(dressed(m, bodies, given), ram, steps=49, distance=bodies) + self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), (body, label)) + self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) + self.assertIn(f"part 'lug' ({body})", str(caught.exception)) + f = R.fit(dressed(m, bodies, zones(0.4, 0.02)), ram, steps=49, distance=bodies) + self.assertIn(("rod[0]", "lug"), f.allowed) + self.assertNotIn(("rocker arm", "lug"), f.allowed) + self.assertIn(("rocker arm", "lug"), f.pairs) + + def test_bell_crank_clears_every_part_but_near_its_pins(self): + # the bell crank stands in front of the knee, its plates at the probe's stack: over 0..-125 the gate meets + # every member with every part, on either side, and all are clear: beside its pins by the record's zones + ram = R.Ram(BORE) + for side in (1.0, -1.0): + m = r3("bell_crank", CRANK, side) + bodies, touch = r3_bodies(m, ram) + m = dressed(m, bodies, touch) + f = R.fit(m, ram, steps=49, distance=bodies) + self.assertGreaterEqual(f.clear_min, 0.0) + self.assertAlmostEqual(f.swing, 105.732, places=2) + self.assertAlmostEqual(f.l_min, 0.6593, places=3) + self.assertAlmostEqual(f.l_max, 1.0376, places=3) + members = {"barrel[0]": "barrel", "rod[0]": "rod", "rocker": "rocker", "coupler": "coupler", "rocker arm": "rocker arm"} + zoned = {(label, part) for label, member in members.items() for part in bodies.parts if (member, part) in let(touch)} + self.assertEqual(set(f.allowed), zoned) + self.assertEqual(len(zoned), 1 + 1 + 5 + 5 + 4) # the ram its eye's pin; rocker, coupler and arm theirs + self.assertEqual(set(f.pairs), {(label, part) for label in members for part in bodies.parts}) + self.assertEqual(len(f.pairs), 5 * 10) + self.assertGreaterEqual(min(v[0] for v in f.pairs.values()), 0.0) + self.assertGreaterEqual(float(R.clearance(m, ram, np.linspace(-125, 0, 251), bodies).margin.min()), 0.0) + # asked for the fit's own angles, clearance reads what the fit read + same = R.clearance(m, ram, f.degrees, bodies) + self.assertEqual((same.pairs, same.where, sorted(same.allowed)), (f.pairs, f.clear_at, sorted(f.allowed))) + # with nothing let, the gate refuses, and only pairs the record zones: the pins a member rides + bare = R._fit(replace(m, touch={}), ram, steps=49, distance=bodies) + refused = {pair for pair, reading in bare.pairs.items() if reading[0] < 0.0} + self.assertEqual(refused, zoned) + self.assertEqual((len(bare.pairs), bare.allowed), (50, [])) + + def test_a_zone_ends_at_its_radius(self): + # each zone cut to half its radius: the pair is met beyond it like any other, and refused there. Soul's + # let_hide: the whole pair was skipped, whatever lay along the member + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies, touch = r3_bodies(m, ram) + for member, zones in touch.items(): + for k, (part, pin, radius, depth) in enumerate(zones): + short = {**touch, member: zones[:k] + [(part, pin, 0.5 * radius, depth)] + zones[k + 1:]} + f = R._fit(dressed(m, bodies, short), ram, steps=49, distance=bodies) + label = member + "[0]" if member in ("barrel", "rod") else member + self.assertEqual([pair for pair, reading in f.pairs.items() if reading[0] < 0.0], [(label, part)], (member, part)) + # a rail on the thigh the rocker runs into 0.25 from its pivot, at rest: a zone on the pivot that takes in the + # thigh's boss does not take in the rail, however deep it is stated + spot = m.rocker + 0.25 * R._flat(m.p - m.rocker, np.array(X)) / m.lr + bodies.parts["rail"], bodies.shapes["rail"] = "parent", [("capsule", spot - (0.05, 0, 0), spot + (0.05, 0, 0), 0.02)] + for radius, clear in ((0.117, False), (0.26, False), (0.34, True)): # the rail's 0.02 and what the rocker keeps past 0.25 + f = R._fit(dressed(m, bodies, {**touch, "rocker": touch["rocker"] + [("rail", "rocker", radius, ram.link_r)]}), ram, steps=49, distance=bodies) + self.assertEqual(f.pairs[("rocker", "rail")][0] >= 0.0, clear, radius) + + def test_a_zone_is_no_wider_or_deeper_than_its_member(self): + # Soul's absurd zones (radius 1e9, depth 1e9: every member read +1e9 clear inside a block). A radius or a + # depth past the member's length is refused by the record's pins alone; a depth past the member's eye on + # that pin by the gate and by from_record, which hold the ram + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies, _ = r3_bodies(m, ram) + self.assertEqual((R._span(m, "rocker"), R._span(m, "coupler")), (m.lr, m.lc)) + self.assertAlmostEqual(R._span(m, "rocker arm"), 0.24, places=9) + self.assertGreaterEqual(R._span(m, "rod"), float(R.pose(m, np.linspace(-125.0, 0.0, 126)).L.max())) + self.assertEqual([ram.eye(*of) for of in (("barrel", "a"), ("rod", "a"), ("rod", "d"), ("coupler", "c"))], [ram.e_a, ram.e_a, ram.e_b, ram.link_r]) + for member, pin in (("barrel", "a"), ("rod", "d"), ("rocker", "p"), ("coupler", "c"), ("rocker arm", "rocker")): + span, eye = R._span(m, member), ram.eye(member, pin) + + def zoned(radius, depth): + return dressed(m, bodies, {member: [("thigh", pin, radius, depth)]}) + zoned(span, 0.0) + for radius, depth, field in ((1.2 * span, 0.0, "radius"), (1e308, 0.0, "radius"), (1e9, 1e9, "radius"), (0.1, 1.2 * span, "depth"), (0.1, 1e308, "depth")): + with self.assertRaises(R.RamError) as caught: + zoned(radius, depth) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh {field}")) + self.assertIn(f"{member} is at most {span:.4f} from pin to pin", str(caught.exception)) + R.clearance(zoned(0.1, eye), ram, [-60.0], bodies) + wrote = R.record(zoned(0.1, eye), ram) + R.from_record(wrote) + wrote["touch"][member][0]["depth"] = 1.2 * eye + for read in (lambda: R.clearance(zoned(0.1, 1.2 * eye), ram, [-60.0], bodies), lambda: R.fit(zoned(0.1, 1.2 * eye), ram, steps=49, distance=bodies), + lambda: R.from_record(wrote)): + with self.assertRaises(R.RamError) as caught: + read() + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh depth")) + self.assertIn(f"{member}'s on {pin} is {eye:.4f}", str(caught.exception)) + + def test_a_wall_the_axis_crosses_in_a_zone_is_read_whatever_its_thickness(self): + # Soul's tunnel: a wall of the thigh across the coupler, midway between two of its samples, inside a zone + # about p of depth 0. Every sample stands outside it; the segment between them is what crosses + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + at = R.pose(m, -60.0) + start = at.P[0] - np.array(X) * ((at.P[0] - at.C[0]) @ np.array(X)) + count = int(math.ceil(m.lc / ram.spacing())) + 1 + samples = start + (at.C[0] - start) * np.linspace(0.0, 1.0, count)[:, None] + spot = 0.5 * (samples[2] + samples[3]) + along = (at.C[0] - start) / m.lc + k = 1 if abs(along[1]) > abs(along[2]) else 2 + + def reading(half, shift=0.0): + lo, hi = spot - 0.08, spot + 0.08 + lo[k], hi[k] = spot[k] - half, spot[k] + half + lo[0], hi[0] = X_COUPLER - 0.05 + shift, X_COUPLER + 0.05 + shift + bodies = r3_parts(m, ram) + bodies.parts["wall"], bodies.shapes["wall"] = "parent", [("box", lo, hi)] + self.assertGreater(float(bodies("wall", samples).min()), 0.0) + return R.clearance(dressed(m, bodies, {"coupler": [("wall", "p", 0.28, 0.0)]}), ram, [-60.0], bodies).pairs[("coupler", "wall")][0] + for half in (0.01, 0.003, 1e-4, 1e-7, 1e-10): + self.assertLess(reading(half), 0.0, half) + # the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let + for half in (0.01, 1e-7): + self.assertGreaterEqual(reading(half, 0.07), 0.02) + # nearer the axis than the floor of the halving, a part the axis is held outside reads as touched + self.assertLess(reading(0.01, 0.05 + 0.2 * ram.spacing() / R.FINE), 0.0) + self.assertGreaterEqual(reading(0.01, 0.05 + 1.2 * ram.spacing() / R.FINE), 0.0) + # a segment with one end in the zone is proved as well. Sampled 0.3 apart, the sample beyond the zone keeps its + # 0.186 from a bead on the axis 0.008 past the last sample in the zone; the bead is read all the same + wide = start + (at.C[0] - start) * np.linspace(0.0, 1.0, 3)[:, None] + bodies, spot = r3_parts(m, ram), wide[1] + 0.012 * along + bodies.parts["bead"], bodies.shapes["bead"] = "parent", [("capsule", spot, spot, 0.004)] + self.assertGreater(float(bodies("bead", wide[:2]).min()), 0.0) + self.assertGreaterEqual(float(bodies("bead", wide[2:])[0]), near(ram, "coupler", 0.3)) + got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "p", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3) + self.assertLess(got.pairs[("coupler", "bead")][0], 0.0) + + def test_two_zones_of_one_pair_and_a_sample_at_a_zones_radius(self): + # Soul's W1..W3. A pair zoned twice: a sample both reach is let the deeper, in either order, and each zone + # still ends at its own radius. A sample exactly at a zone's radius is in it + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies, touch = r3_bodies(m, ram) + rest = [zone for zone in touch["rocker"] if zone[0] != "rocker plates"] + + def reading(*zones, degrees=np.linspace(-125.0, 0.0, 49)): + return R.clearance(dressed(m, bodies, {**touch, "rocker": rest + list(zones)}), ram, degrees, bodies).pairs[("rocker", "rocker plates")][0] + deep, beside, far = ("rocker plates", "rocker", 0.6 * m.lr, ram.link_r), ("rocker plates", "rocker", 0.6 * m.lr, 0.0), ("rocker plates", "p", 0.51 * m.lr, ram.link_r) + self.assertAlmostEqual(reading(deep, beside, far), 0.0, places=12) + self.assertAlmostEqual(reading(beside, deep, far), 0.0, places=12) + self.assertAlmostEqual(reading(far, beside, deep), 0.0, places=12) + for short in ((beside, beside, far), (deep, beside), (far, deep[:2] + (0.3 * m.lr, ram.link_r))): + self.assertLess(reading(*short), -0.9 * ram.link_r, short) + at = R.pose(m, [-60.0]) + end = at.P - np.array(X) * ((at.P - m.rocker) @ np.array(X))[:, None] + count = int(math.ceil(m.lr / ram.spacing())) + 1 + pts = m.rocker + (end - m.rocker)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] + across = np.linalg.norm(R._flat(pts - m.rocker, np.array(X)), axis=2)[0] + edge, beyond = float(across[3]), m.lr - 0.5 * float(across[3] + across[4]) + self.assertAlmostEqual(reading(("rocker plates", "rocker", edge, ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), 0.0, places=12) + self.assertLess(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), -0.9 * ram.link_r) + + def test_a_pin_stood_inside_what_it_stands_beside_is_refused(self): + # Soul's moved-x probes: the rocker's x moved from its plate's place (0.3675) into the bracket's 0.13..0.35, + # the coupler's (0.3275) into the horn's 0.18..0.31. The zones are the shipped ones and take in the whole of + # each boss; the member's axis is inside the boss by its radius (0.055, 0.05), and a zone of depth 0 keeps it out + ram = R.Ram(BORE) + bodies, touch = r3_bodies(r3("bell_crank", CRANK), ram) + for moved, member, part, depth, pin in (("rocker", "rocker", "bracket", 0.055, "rocker"), ("c", "coupler", "horn", 0.05, "c")): + pins = {name: yz(CRANK[name], {"rocker": X_ROCKER, "c": X_COUPLER}.get(name, 0.0)) for name in CRANK} + pins[moved] = yz(CRANK[moved], 0.25) + m = R.Mechanism("bell_crank", O, X, -125.0, 0.0, **pins, parts=bodies.parts, touch=touch) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, steps=49, distance=bodies) + refusal = caught.exception + self.assertEqual((refusal.gate, refusal.pin), ("clash", pin)) + self.assertEqual(refusal.fit.clear_at[1:3], (member, part)) + self.assertAlmostEqual(refusal.fit.pairs[(member, part)][0], -depth, places=9) + # stated as deep as the boss, the zone is refused: a bar's eye is link_r, and no zone lets its axis deeper + deep = {**touch, member: [(part, pin, zone[2], depth) if zone[0] == part else zone for zone in touch[member]]} + with self.assertRaises(R.RamError) as caught: + R._fit(replace(m, touch=deep), ram, steps=49, distance=bodies) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} depth")) + + def test_a_member_stands_still_in_its_own_bodys_frame(self): + # what the oracle is asked: the coupler's samples in the coupler's frame, the rocker's and the arm's in the + # rocker's, the coupler's end at c in the child's and the rod's eye in the rocker's are the rest pose's at + # every angle + ram = R.Ram(BORE) + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + bodies, asked = r3_parts(m, ram), [] + + def spy(part, pts): + asked.append((part, np.array(pts))) + return bodies(part, pts) + angles = np.linspace(-125, 0, 26) + R.clearance(dressed(m, bodies), ram, angles, spy) + labels = [label for _, label, *_ in R._members(m, ram, R.barrel_length(m, ram), R.pose(m, angles))] + seen = {(labels[k // len(bodies.parts)], part): pts.reshape(len(angles), -1, 3) for k, (part, pts) in enumerate(asked)} + still = [seen[("coupler", "coupler plates")], seen[("rocker", "rocker plates")], seen[("coupler", "shin")][:, -1:], seen[("rod[0]", "pin p")][:, -1:]] + if kind == "bell_crank": + still.append(seen[("rocker arm", "pin d")]) + for pts in still: + self.assertLess(float(np.abs(pts - pts[-1]).max()), OWN_FRAME, kind) + self.assertLess(float(np.abs(seen[("coupler", "coupler plates")][-1, 0] - (X_COUPLER, m.p[1], m.p[2])).max()), OWN_FRAME) + + +# The R-3 four-bar's readings over 0..-125 at 49 steps, each bound the geometric mean of the shipped reading and +# M2's (the direct arm formula on a linkage). +ARM_LEAST = 0.205 # least knee arm: shipped 0.0962, M2 0.4367, separation 4.5 +ARM_GREATEST = 0.485 # greatest knee arm: shipped 0.2648, M2 0.8888, separation 3.4 +LOAD = 3.95 # greatest coupler pin load per unit ram force: shipped 1.609, M2 9.722, separation 6.0 +LOAD_GATE = 1.34 # a max_load the shipped four-bar's 1.609 exceeds by 1.2: with the gate off (M8) it fits + + +@unittest.skipIf(np is None, "numpy is not installed") +class OracleRule(unittest.TestCase): + def setUp(self): + self.m = R.Mechanism("direct", O, X, -30, 0, a=(0, -0.3, 1.0), b=(0, -0.3, -1.0)) + self.ram = R.Ram(0.05) + self.barrel = R._fit(self.m, self.ram).barrel + + def ball(self, at, r, cap=None): + return two(parent=[("capsule", at, at, r)], cap=cap) + + def test_need_is_radius_gap_and_half_the_spacing(self): + # a ball beside a sample of the barrel at rest, its surface at the need less or more a micron + ram, spacing = self.ram, 0.05 + p = R.pose(self.m, 0.0) + members = {label: (start, end, radius) for _, label, start, end, radius, _ in R._members(self.m, ram, self.barrel, p)} + start, end, radius = members["barrel[0]"] + count = int(math.ceil(float(np.linalg.norm(end - start)) / spacing)) + 1 + sample = (start + (end - start) * (3 / (count - 1)))[0] + need = radius + ram.gap + spacing / 2 + for slip, clear in ((-1e-6, False), (1e-6, True)): + centre = sample + np.array((0.0, -(need + slip + 0.2), 0.0)) + ball = self.ball(centre, 0.2) + c = R.clearance(dressed(self.m, ball), ram, 0.0, ball, spacing) + self.assertEqual(bool(c.margin[0] >= 0.0), clear, (slip, c.margin)) + self.assertAlmostEqual(float(c.margin[0]), slip, places=9) + self.assertEqual(c.where, (0.0, "barrel[0]", "parent", "a")) # sample 3 of the barrel: nearer the base + self.assertAlmostEqual(ram.reach(spacing), need, places=15) + + def test_a_zone_is_the_only_allowance(self): + # a clevis on the base pin and one on the eye, each a part (a ball of 0.03): with nothing let they refuse the + # ram at its own pins. A zone about the pin lets the member by: of the ball's radius plus what the member + # keeps, and for the rod, whose last sample is the pin's centre, as deep as the ball + ram, m = self.ram, self.m + seats = two(a=("parent", [("capsule", m.a, m.a, 0.03)]), b=("child", [("capsule", m.b, m.b, 0.03)])) + bare = R.clearance(dressed(m, seats), ram, 0.0, seats) + self.assertAlmostEqual(bare.pairs[("barrel[0]", "a")][0], ram.e_a - 0.03 - near(ram, "barrel"), places=12) # the barrel starts e_a from a + self.assertAlmostEqual(bare.pairs[("rod[0]", "b")][0], -0.03 - near(ram, "rod"), places=12) + self.assertEqual(bare.where, (0.0, "rod[0]", "b", "b")) # the least, and the pin at the rod's far end + self.assertEqual(bare.allowed, []) + zones = {"barrel": [("a", "a", 0.03 + near(ram, "barrel"), 0.0)], "rod": [("b", "b", 0.03 + near(ram, "rod"), 0.03)]} + let_ = R.clearance(dressed(m, seats, zones), ram, 0.0, seats) + self.assertGreaterEqual(float(let_.margin[0]), 0.0) + self.assertEqual(sorted(let_.allowed), [("barrel[0]", "a"), ("rod[0]", "b")]) + self.assertEqual(len(let_.pairs), 2 * 4) + self.assertAlmostEqual(let_.pairs[("rod[0]", "b")][0], 0.0, places=12) # at the pin's centre: the ball's depth, and the zone's + # a micron shallower and the rod is a micron inside; a zone that stops short of what the member keeps is refused + # beyond it; the other member's zone, or a zone about the member's other pin, lets nothing + shallow = R.clearance(dressed(m, seats, {**zones, "rod": [("b", "b", 0.03 + near(ram, "rod"), 0.03 - 1e-6)]}), ram, 0.0, seats) + self.assertAlmostEqual(shallow.pairs[("rod[0]", "b")][0], -1e-6, places=12) + self.assertEqual(shallow.where, (0.0, "rod[0]", "b", "b")) + short = R.clearance(dressed(m, seats, {**zones, "rod": [("b", "b", 0.02, 0.03)]}), ram, 0.0, seats, spacing=0.01) + rod = float(np.linalg.norm(m.b - m.a)) - ram.back - self.barrel + step = rod / math.ceil(rod / 0.01) + first = step * (math.floor(0.02 / step) + 1) # the first sample past the zone, from the eye + self.assertAlmostEqual(short.pairs[("rod[0]", "b")][0], first - 0.03 - near(ram, "rod", 0.01), places=12) + self.assertLess(first, 0.03) + # a zone names its part whole: a lug at the eye named for the pin's part is no part of the zone (S20) + lugged = two(a=seats.shapes["a"] and ("parent", seats.shapes["a"]), b=("child", seats.shapes["b"]), **{"b.lug": ("child", seats.shapes["b"])}) + got = R.clearance(dressed(m, lugged, zones), ram, 0.0, lugged) + self.assertEqual({pair: round(reading[0], 9) for pair, reading in got.pairs.items() if reading[0] < 0.0}, {("rod[0]", "b.lug"): round(-0.03 - near(ram, "rod"), 9)}) + for crossed in ({"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]}, {"barrel": [("a", "b", 0.2, 0.03)], "rod": [("b", "a", 0.2, 0.03)]}): + self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0) + + def test_every_body_owns_a_part(self): + ball = Bodies({"ball": ("parent", [("capsule", (0, 0, 0), (0, 0, 0), 0.1)])}) + with self.assertRaises(R.RamError) as caught: + R.fit(dressed(self.m, ball), self.ram, distance=ball) + self.assertEqual(caught.exception.gate, "record") + self.assertIn("no part turns with body child", str(caught.exception)) + + def test_inside_a_part_is_negative_however_deep(self): + # a ram down the core of a thick box (Soul's buried ram): every sample is deeper inside than the oracle's + # cap, and reads its depth, negative; the cap changes nothing inside + m = R.Mechanism("direct", O, X, -10, 0, a=(0, 0.0, 1.1), b=(0, 0.0, -0.5)) + ram = R.Ram(BORE) + core = [("box", (-0.13, -0.14, 0.3), (0.13, 0.14, 1.15))] + self.assertGreater(0.13, ram.reach()) + for cap in (None, ram.reach()): + thigh = two(core, cap=cap) + self.assertAlmostEqual(float(thigh("parent", np.array([(0.0, 0.0, 0.7)]))[0]), -0.13, places=12) + self.assertAlmostEqual(float(thigh("parent", np.array([(0.11, 0.0, 0.7)]))[0]), -0.02, places=12) + c = R.clearance(dressed(m, thigh), ram, 0.0, thigh) + self.assertAlmostEqual(c.pairs[("barrel[0]", "parent")][0], -0.13 - (ram.barrel_r + ram.gap + ram.barrel_r / 2), places=9) + # an oracle that answers nan is refused + with self.assertRaises(R.RamError) as caught: + R.clearance(dressed(m, thigh), ram, 0.0, lambda part, pts: np.full(len(pts), math.nan)) + self.assertEqual(caught.exception.gate, "oracle") + + def test_a_capped_oracle_gives_the_same_verdicts(self): + ram = R.Ram(BORE) + asked = [] + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + angles = np.linspace(-125, 0, 49) + bodies, touch = r3_bodies(m, ram) + free = R.clearance(dressed(m, bodies, touch), ram, angles, bodies).margin + capped = R.clearance(dressed(m, bodies, touch), ram, angles, r3_bodies(m, ram, cap=ram.reach())[0]).margin + self.assertEqual((free >= 0.0).tolist(), (capped >= 0.0).tolist(), kind) + self.assertTrue(np.array_equal(np.minimum(free, 0.0), np.minimum(capped, 0.0))) # a cap changes no reading under it + asked.append(bool((free < 0.0).any())) + self.assertEqual(asked, [True, False]) # one of each verdict was compared + + +@unittest.skipIf(np is None, "numpy is not installed") +class SearchBestFirst(unittest.TestCase): + HINGE = {"pivot": O, "axis": X, "lo": -60, "hi": 0} + + def test_the_best_arm_that_clashes_is_passed_over(self): + ram = R.Ram(0.05) + seats = {"a": [(0, -0.2, 1.0), (0, -0.3, 1.0), (0, -0.4, 1.0)], "b": [(0, -0.3, -1.0)]} + free = R.search("direct", self.HINGE, ram, seats) + arms = sorted((R._fit(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), ram).arm_min, a) for a in seats["a"]) + self.assertEqual(tuple(free.seat["a"]), arms[-1][1]) + # a ball in the way of the best seat's ram only + best = R.Mechanism("direct", O, X, -60, 0, a=arms[-1][1], b=seats["b"][0]) + mid = R.pose(best, 0.0) + away = math.copysign(0.14, arms[-1][1][1] - arms[-2][1][1]) + centre = mid.base[0] + 0.05 * (mid.eye[0] - mid.base[0]) + np.array((0.0, away, 0.0)) + block = two(parent=[("capsule", centre, centre, 0.07)]) + found = R.search("direct", self.HINGE, ram, seats, world=lambda m: (block.parts, {}, block)) + clear = [a for _, a in arms if R._fit(dressed(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), block), ram, distance=block).ok] + self.assertTrue(clear and arms[-1][1] not in clear, clear) + self.assertTrue(found.found) + self.assertEqual(tuple(found.seat["a"]), clear[-1]) # the best arm of those that are clear + self.assertGreaterEqual(found.best.clear_min, 0.0) + self.assertEqual(found.tally, {"clash": 3 - len(clear)}) + self.assertEqual(found.fits, 3) + # the caller's spacing is the winner's gate's (S12): its reading is the fit's at that spacing, not the default's + fine = R.search("direct", self.HINGE, ram, seats, world=lambda m: (block.parts, {}, block), spacing=0.01) + finely = [a for _, a in arms if R._fit(dressed(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), block), ram, distance=block, spacing=0.01).ok] + self.assertEqual(tuple(fine.seat["a"]), finely[-1]) + self.assertEqual(fine.best.clear_min, R._fit(dressed(fine.best.m, block), ram, distance=block, spacing=0.01).clear_min) + self.assertNotEqual((finely[-1], fine.best.clear_min), (clear[-1], found.best.clear_min)) + + def test_the_nearest_miss_counts_the_clash(self): + # a bar every seat's ram runs into, deepest for the best arm: the nearest miss is the shallowest clash, not + # the first met (S5: the shortfall without the clearance) + ram = R.Ram(0.05) + seats = {"a": [(0, -0.2, 1.0), (0, -0.3, 1.0), (0, -0.4, 1.0)], "b": [(0, -0.3, -1.0)]} + bar = two(parent=[("capsule", (-0.5, -0.7, 0.9), (0.5, -0.7, 0.9), 0.42)]) + fits = [R._fit(dressed(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), bar), ram, distance=bar) for a in seats["a"]] + self.assertTrue(all(f.why and f.why[0][0] == "clash" for f in fits), [f.report() for f in fits]) + first = max(range(3), key=lambda k: fits[k].arm_min) + nearest = max(range(3), key=lambda k: fits[k].clear_min) + self.assertNotEqual(first, nearest) + missed = R.search("direct", self.HINGE, ram, seats, world=lambda m: (bar.parts, {}, bar)) + self.assertFalse(missed.found) + self.assertEqual(missed.tally, {"clash": 3}) + self.assertEqual(tuple(missed.seat["a"]), seats["a"][nearest]) + self.assertEqual(missed.best.clear_min, fits[nearest].clear_min) + + def test_what_a_world_returns_is_read_as_a_record(self): + ram = R.Ram(0.05) + seats = {"a": [(0, -0.3, 1.0)], "b": [(0, -0.3, -1.0)]} + ball = two(parent=[("capsule", (0, 0.5, 0), (0, 0.5, 0), 0.05)]) + for made, gate, said in (((ball.parts, ball), "search", "world(m) returns (parts, touch, distance), got tuple"), (None, "search", "got NoneType"), + ((ball.parts, {}, None), "search", "world(m) returns"), ((ball.parts, {"rod": ["parent"]}, ball), "record", "zone is (part, pin, radius, depth)"), + ((ball.parts, {"rod": [("parent", "c", 1.0, 0.0)]}, ball), "record", "a pin it rides (a, b)"), + ((ball.parts, {"rod": [("thigh", "b", 1.0, 0.0)]}, ball), "record", "no part of the record"), + ((ball.parts, {"rod": [("parent", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("parent", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("parent", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("parent", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"), + ((ball.parts, {"rod": [("parent", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"), + ((ball.parts, {"rod": [("parent", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"), + (({"ball": "rocker"}, {}, ball), "record", "turns with 'rocker'"), (({"ball": "parent"}, {}, ball), "record", "no part turns with body child")): + with self.assertRaises(R.RamError) as caught: + R.search("direct", self.HINGE, ram, seats, world=lambda m: made) + self.assertEqual(caught.exception.gate, gate, said) + self.assertIn(said, str(caught.exception)) + self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {}, ball)).found) + self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("parent", "b", 0.5, ram.e_b)]}, ball)).found) + + def test_the_limit_is_refused_naming_the_count(self): + seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} + with self.assertRaises(R.RamError) as caught: + R.search("direct", self.HINGE, R.Ram(0.05), seats, limit=224) + self.assertIn("225 candidates", str(caught.exception)) + + def test_a_linkage_grid(self): + # a small grid about the probe's four-bar holds it: the search seats a linkage over 0..-125 + ram = R.Ram(BORE) + hinge = {"pivot": O, "axis": X, "lo": -125, "hi": 0} + seats = {"rocker": [yz(DEEP["rocker"])], "c": [yz(DEEP["c"])], "a": [yz(DEEP["a"]), yz((-0.3, 1.0))], "link": (0.4, 0.6, 5)} + self.assertEqual(len(R.candidates("four_bar", hinge, seats)), 2 * 5 * 24) + found = R.search("four_bar", hinge, ram, seats, steps=49) + self.assertTrue(found.found, found.report()) + self.assertIn("assembly", found.tally) + # with the links' plates at the probe's stack the ram still runs across the axis: a four-bar's eye is p, and + # both stand at a's place (S18: p left at the rocker's is a record no four-bar reads) + stacked = {**seats, "rocker": [yz(DEEP["rocker"], X_ROCKER)], "c": [yz(DEEP["c"], X_COUPLER)]} + self.assertTrue(all(seat["p"][0] == seat["a"][0] == 0.0 and np.array_equal(seat["p"], seat["d"]) for seat in R.candidates("four_bar", hinge, stacked))) + beside = R.search("four_bar", hinge, ram, stacked, steps=49) + self.assertTrue(beside.found and "record" not in beside.tally, beside.report()) + self.assertEqual((beside.tally, beside.fits, beside.best.arm_min), (found.tally, found.fits, found.best.arm_min)) + crank = R.candidates("bell_crank", hinge, {**seats, "d": (0.12, 0.24, 3)}) + self.assertEqual(len(crank), 2 * 5 * 24 * 3 * 12) + + def test_a_candidates_own_links_are_its_bodies(self): + # a bell-crank grid about the probe's, each candidate met with the parts its own pins place: its plates, + # axle and pins. The winner has met them; a world that leaves a link without a part is refused + ram = R.Ram(BORE) + hinge = {"pivot": O, "axis": X, "lo": -125, "hi": 0} + seats = {"rocker": [yz(CRANK["rocker"], X_ROCKER)], "c": [yz(CRANK["c"], X_COUPLER)], "a": [yz(CRANK["a"])], "link": (0.5, 0.5, 1), "d": (0.2, 0.26, 2)} + pins = R.candidates("bell_crank", hinge, seats) + self.assertEqual(len(pins), 24 * 2 * 12) + self.assertTrue(all(seat["d"][0] == seat["a"][0] and seat["p"][0] == X_ROCKER for seat in pins)) # the ram runs across the axis + seen = [] + + def world(m): + bodies, touch = r3_bodies(m, ram) + seen.append(m) + return bodies.parts, touch, bodies + found = R.search("bell_crank", hinge, ram, seats, world=world, steps=49) + self.assertTrue(found.found and found.best.ok, found.report()) + self.assertEqual(len(seen), found.tally.get("clash", 0) + 1) # a world for each candidate the gate met + self.assertTrue(np.array_equal(seen[-1].p, found.best.m.p) and np.array_equal(seen[-1].d, found.best.m.d)) + for pair in (("rod[0]", "rocker plates"), ("barrel[0]", "pin p"), ("rocker arm", "coupler plates"), ("coupler", "pin d"), ("rocker", "shin")): + self.assertGreaterEqual(found.best.pairs[pair][0], 0.0, pair) + bodies, touch = r3_bodies(found.best.m, ram) + self.assertTrue(R.fit(dressed(found.best.m, bodies, touch), ram, steps=49, distance=bodies).ok) + thigh_and_shin = two(R3_THIGH, R3_SHIN) + with self.assertRaises(R.RamError) as caught: + R.search("bell_crank", hinge, ram, seats, world=lambda m: (thigh_and_shin.parts, {}, thigh_and_shin), steps=49) + self.assertIn("no part turns with body rocker", str(caught.exception)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class RecordDrives(unittest.TestCase): + def test_round_trip_and_drive(self): + ram = R.Ram(BORE) + crank = r3("bell_crank", CRANK) + bodies, touch = r3_bodies(crank, ram) + for m in (r3("four_bar", DEEP), dressed(crank, bodies, touch), R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6), offsets=(-0.1, 0.1))): + f = R.fit(m, ram, steps=49) + data = R.record(m, ram) + wire = json.loads(json.dumps(data)) + self.assertEqual(wire, data) + self.assertEqual(sorted(data), ["compliance", "hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"]) + self.assertEqual((data["schema"], data["version"], data["compliance"]), ("brokkr.ram", 1, None)) + again, ram2 = R.from_record(wire) + self.assertEqual(R.record(again, ram2), data) + self.assertEqual((again.parts, again.touch), (m.parts, m.touch)) + self.assertEqual([sorted(zone) for zones in wire["touch"].values() for zone in zones], [sorted(R.ZONE)] * sum(len(z) for z in m.touch.values())) + angles = np.linspace(m.lo, m.hi, 49) + self.assertEqual(R.length(again, angles).tolist(), R.length(m, angles).tolist()) + ext = R.extension(again, ram2, angles) + self.assertEqual(ext.tolist(), (R.length(m, angles) - f.closed).tolist()) + # the extension follows the angle: home plus the overtravel at the short end, travel more at the long + self.assertAlmostEqual(float(ext.min()), ram.over, places=12) + self.assertAlmostEqual(float(ext.max()), ram.over + f.travel, places=12) + self.assertGreater(abs(float(ext[0] - ext[-1])), 0.3) + self.assertEqual(R.barrel_length(again, ram2), f.barrel) + + def test_nothing_derived_is_stored(self): + # the barrel comes from the pins and the ram: a record whose overtravel is edited drives a rod that keeps + # the new overtravel, and a trunnion's tail rides the record + m = R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)) + data = R.record(m, R.Ram(BORE, tail=0.2)) + self.assertEqual(data["ram"]["tail"], 0.2) + again, ram = R.from_record(data) + self.assertEqual((ram.tail, ram.back), (0.2, -0.2)) + self.assertAlmostEqual(R.barrel_length(again, ram) - R.barrel_length(m, R.Ram(BORE)), 0.2 + R.Ram(BORE).e_a, places=12) + data["ram"]["over"] = 2.0 * data["ram"]["over"] + again, ram = R.from_record(data) + self.assertAlmostEqual(float(R.extension(again, ram, np.linspace(-62, 0, 49)).min()), data["ram"]["over"], places=12) + + def test_a_record_this_version_cannot_read_is_refused_whole(self): + data = R.record(R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), R.Ram(BORE)) + settle = {"stiffness": 2.0e6, "damping": 4.0e3, "travel": 0.02} + self.assertEqual(tuple(settle), R.COMPLIANCE) + ram = dict(data["ram"], stiffness=2.0e6) + short = {k: v for k, v in data.items() if k != "touch"} + for change, said in (({"version": 2}, "version 2"), ({"version": 2, "compliance": settle}, "version 2"), ({"compliance": settle}, "compliance block"), + ({"schema": "brokkr.kit"}, "brokkr.kit"), ({"settle": settle}, "unknown ['settle']"), ({"ram": ram}, "unknown ['stiffness']"), + ({"hinge": dict(data["hinge"], rate=1.0)}, "unknown ['rate']"), + # a block that is falsy is a block (S23); the version is the integer 1 + ({"compliance": {}}, "compliance block"), ({"compliance": 0}, "compliance block"), ({"compliance": False}, "compliance block"), + ({"version": 1.0}, "version 1.0"), ({"version": True}, "version True"), ({"version": "1"}, "version '1'"), + ({"kind": "scissor"}, "kind is one of"), + # a pin this kind has not, or a key that is no pin, is refused by name; so is one missing + ({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 1's: unknown ['q']"), + ({"pins": dict(data["pins"], parts={})}, "unknown ['parts']"), ({"pins": {"a": data["pins"]["a"]}}, "missing ['b']"), + ({"pins": [1, 2]}, "(pin pins): an object, got list"), ({"ram": None}, "(pin ram): an object, got NoneType"), + # every number is a finite number, the bore over 0; three of them make a point + ({"ram": dict(data["ram"], bore=None)}, "(pin bore): a finite number, got None"), ({"ram": dict(data["ram"], bore=-1.0)}, "(pin bore): a number greater than 0, got -1.0"), + ({"ram": dict(data["ram"], bore=0)}, "(pin bore)"), ({"ram": dict(data["ram"], min_arm=float("nan"))}, "(pin min_arm): a finite number, got nan"), + ({"ram": dict(data["ram"], gap=float("inf"))}, "(pin gap)"), ({"ram": dict(data["ram"], rod=True)}, "(pin rod): a finite number, got True"), + ({"ram": dict(data["ram"], rod=None)}, "direct ram: record (pin rod): a finite number, got None"), # a record's ram holds every proportion: none defaults + ({"ram": dict(data["ram"], tail="0.2")}, "(pin tail): a finite number, got '0.2'"), + ({"hinge": dict(data["hinge"], lo="a")}, "(pin lo): a finite number, got 'a'"), ({"hinge": dict(data["hinge"], hi=None)}, "(pin hi)"), + ({"hinge": dict(data["hinge"], pivot=[0.0, 0.0])}, "(pin pivot): three finite numbers"), ({"hinge": dict(data["hinge"], axis="xyz")}, "(pin axis): three finite numbers"), + ({"pins": dict(data["pins"], a=["0", "1", "2"])}, "(pin a): a finite number, got '0'"), ({"pins": dict(data["pins"], b=[0.0, 1.0, float("inf")])}, "(pin b)"), + ({"offsets": "0"}, "(pin offsets)"), ({"offsets": [None]}, "(pin offsets): a finite number"), ({"offsets": []}, "at least one offset"), + ({"parts": ["knee"]}, "(pin parts)"), ({"parts": {"knee": 1}}, "(pin parts)"), ({"touch": []}, "(pin touch)"), + ({"parts": {"knee": "parent"}, "touch": {"rod": ["knee"]}}, "(pin rod zone): an object, got str"), + ({"parts": {"knee": "parent"}, "touch": {"rod": "knee"}}, "rod's zones are a list"), + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1}]}}, "missing ['depth']"), + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0, "whole": True}]}}, "unknown ['whole']"), + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)")): + with self.assertRaises(R.RamError) as caught: + R.from_record({**data, **change}) + self.assertEqual(caught.exception.gate, "record", change) + self.assertIn(said, str(caught.exception)) + with self.assertRaises(R.RamError) as caught: + R.from_record([data]) + self.assertIn("a record is an object, got list", str(caught.exception)) + zoned = R.from_record({**data, "parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0] + self.assertEqual(zoned.touch, {"rod": (("knee", "b", 0.1, 0.0),)}) + # a ram refuses the same numbers when built by hand + for bad in ({"bore": -0.05}, {"bore": 0.0}, {"bore": None}, {"bore": True}, {"bore": 0.05, "gap": float("nan")}, {"bore": 0.05, "tail": float("inf")}, {"bore": 0.05, "rod": "0.02"}): + with self.assertRaises(R.RamError) as caught: + R.Ram(**bad) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", list(bad)[-1])) + with self.assertRaises(R.RamError) as caught: + R.from_record(short) + self.assertIn("missing ['touch']", str(caught.exception)) + self.assertEqual(R.from_record(data)[0].kind, "direct") + + def test_offsets_stand_the_ram_along_the_axis(self): + m = R.Mechanism("direct", O, X, -60, 0, a=(0, -0.3, 1.0), b=(0, -0.3, -1.0), offsets=(-0.2, 0.2)) + ram = R.Ram(0.05) + # a ball beside the twin at +0.2 only + ball = two(parent=[("capsule", (0.2, -0.45, 0.5), (0.2, -0.45, 0.5), 0.06)]) + c = R.clearance(dressed(m, ball), ram, 0.0, ball) + self.assertLess(float(c.margin[0]), 0.0) + self.assertEqual(c.where[1], "barrel[0.2]") + self.assertGreaterEqual(c.pairs[("barrel[-0.2]", "parent")][0], 0.0) + + +@unittest.skipIf(np is None, "numpy is not installed") +class Refusals(unittest.TestCase): + def refused(self, gate, pin=None, **changes): + base = {"kind": "four_bar", "pivot": O, "axis": X, "lo": -125, "hi": 0, **{name: yz(DEEP[name]) for name in DEEP}} + base.update(changes) + with self.assertRaises(R.RamError) as caught: + R.Mechanism(**base) + self.assertEqual((caught.exception.gate, caught.exception.pin), (gate, pin), str(caught.exception)) + self.assertIn(str(base["kind"]), str(caught.exception)) + return caught.exception + + def test_every_record_refusal(self): + self.refused("record", kind="scissor") + self.refused("record", "axis", axis=(1.0, 0.1, 0.0)) + self.assertEqual(self.refused("record", lo=0, hi=0).angle, 0.0) # a range's refusal names its lo + self.assertEqual(self.refused("record", lo=-200, hi=200).angle, -200.0) + self.refused("record", "a", offsets=()) # the ram stands along the axis from a + self.assertIn("'knee' turns with 'foot'", str(self.refused("record", parts={"knee": "foot"}))) + self.assertIn("touch names 'piston'", str(self.refused("record", parts={"knee": "parent"}, touch={"piston": [("knee", "d", 0.1, 0.0)]}))) + self.assertIn("rod may touch 'hip'", str(self.refused("record", parts={"knee": "parent"}, touch={"rod": [("hip", "d", 0.1, 0.0)]}))) + # a zone is (part, a pin the member rides, radius over 0, depth of 0 or more): a bare part name lets nothing + knee = {"parts": {"knee": "parent"}} + self.assertIn("zone is (part, pin, radius, depth), got 'knee'", str(self.refused("record", **knee, touch={"rod": ["knee"]}))) + self.assertIn("zone is (part, pin, radius, depth)", str(self.refused("record", **knee, touch={"rod": [("knee", "d", 0.1)]}))) + self.assertIn("a pin it rides (a, d), not 'c'", str(self.refused("record", "c", **knee, touch={"rod": [("knee", "c", 0.1, 0.0)]}))) + self.assertIn("a pin it rides (p, c), not 'rocker'", str(self.refused("record", "rocker", **knee, touch={"coupler": [("knee", "rocker", 0.1, 0.0)]}))) + self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", 0.0, 0.0)]}) + self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", float("inf"), 0.0)]}) + self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", "0.1", 0.0)]}) + self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, -0.01)]}) + self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, float("nan"))]}) + self.refused("record", "a", a=(0, 1)) + self.refused("record", "c", c=(0, float("nan"), 1)) + self.refused("record", "b", b=(0, 0, -1)) # a four-bar has no b + self.refused("record", "rocker", rocker=None) + self.refused("record", "b", kind="direct", rocker=None, p=None, c=None, d=None) # a direct ram needs b + self.refused("record", "d", d=(0, -0.4, 0.0)) # a four-bar's eye is p + self.refused("record", "d", kind="bell_crank") # a bell crank's is not + self.refused("assembly", "p", p=yz((0.5 * (DEEP["rocker"][0] + DEEP["c"][0]), 0.5 * (DEEP["rocker"][1] + DEEP["c"][1]))), + d=yz((0.5 * (DEEP["rocker"][0] + DEEP["c"][0]), 0.5 * (DEEP["rocker"][1] + DEEP["c"][1])))) + + def test_a_bell_cranks_eye_stands_off_its_pin(self): + near = dict(CRANK, d=(CRANK["p"][0] + 2 * BORE - 1e-6, CRANK["p"][1])) + with self.assertRaises(R.RamError) as caught: + R.fit(r3("bell_crank", near), R.Ram(BORE)) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("pins", "d")) + + def test_arm_refused(self): + m = R.Mechanism("direct", O, X, -30, 0, a=(0, -0.05, 1.0), b=(0, -0.05, -1.0)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(0.05)) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("arm", "b")) + self.assertIn(f"arm at {caught.exception.angle:g} deg (pin b)", str(caught.exception)) + + def test_no_blender(self): + source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") + for word in ("bpy", "np.gradient"): + self.assertNotIn(word, source) + # the mesh oracle asks for mathutils when one is made: nothing above it does, and this file loaded without it + self.assertNotIn("mathutils", source.split("\nclass Signed:")[0]) + self.assertEqual(source.count("\nclass Signed:"), 1) + + +if __name__ == "__main__": + unittest.main()