brokkr_kitbash.ram: touch is zones about a member's pins, each a radius and a depth; a strict record; what a world returns is read as a record

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 20:01:36 +01:00
commit 9c19e7df87

View file

@ -26,10 +26,14 @@ the coupler bar at c's, the ram at a's plus each of `offsets`.
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], the parts it may touch. A member may touch what it is pinned to and what is
stacked on its pins: the pin, its own eye and clevis, the plates beside it on that pin, the bracket or horn the pin
stands in. Those pairs are skipped whole and every other (member, part) pair is checked; 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.
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.
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),
@ -50,8 +54,12 @@ BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker
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
@ -66,9 +74,19 @@ class RamError(ValueError):
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."""
"""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
@ -83,11 +101,13 @@ class Ram:
max_load: float = 3.0 # greatest coupler pin load per unit ram force
def __post_init__(self):
b = self.bore
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):
@ -133,7 +153,7 @@ class Mechanism:
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 -> the parts it may touch
touch: dict = field(default_factory=dict) # member -> zones (part, pin, radius, depth)
def __post_init__(self):
if self.kind not in KINDS:
@ -157,13 +177,25 @@ class Mechanism:
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])}")
self.touch = {member: tuple(parts) for member, parts in dict(self.touch).items()}
for member, parts in self.touch.items():
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])}")
for part in parts:
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")
touch[member].append((part, pin, radius, depth))
touch[member] = tuple(touch[member])
self.touch = touch
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:
@ -270,19 +302,19 @@ def extension(m, ram, degrees):
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, eye = m.axis, "b" if m.kind == "direct" else "d"
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, ("a", eye)
yield "rod", f"rod[{off:g}]", front, tip, ram.rod, ("a", eye)
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, ("rocker", "p")
yield "coupler", "coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, ram.link_r, ("p", "c")
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, ("rocker", "d")
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):
@ -301,15 +333,17 @@ def _into(m, p, body, pts):
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 checked
allowed: list # (member label, part) of every pair the record's `touch` skipped
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 but those `touch` gives it."""
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."""
return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing)
@ -320,27 +354,33 @@ def _clearance(m, ram, barrel, p, distance, spacing):
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 part in m.touch.get(member, ()):
out.allowed.append((label, part))
continue
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}")
row = got.min(axis=1) - need
keep = np.full(got.shape, need) # what each sample keeps from the part
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)
if zones:
out.allowed.append((label, part))
over = got - keep
row = over.min(axis=1)
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(got[i])) * 2 >= count])
out.where = (float(p.degrees[i]), label, part, pins[int(np.argmin(over[i])) * 2 >= count])
return out
@ -366,8 +406,8 @@ class Fit:
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 checked
allowed: list = field(default_factory=list) # (member, part) of every pair `touch` skipped
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
@ -394,7 +434,7 @@ def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True):
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 = "b" if m.kind == "direct" else "d"
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
@ -433,7 +473,7 @@ def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True):
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 and touch say what it meets).
(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:
@ -492,7 +532,8 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N
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. A grid past `limit` candidates is refused naming the count. A
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 or a zone that is not (part, pin the member rides, radius, depth) 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)
@ -524,7 +565,10 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N
for f, seat in passed:
if world is None:
return Search(f, True, len(pins), len(passed), tally, seat)
parts, touch, distance = world(f.m)
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)
@ -541,26 +585,60 @@ def record(m, ram):
"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), "touch": {member: list(parts) for member, parts in m.touch.items()}, "compliance": None}
"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, with a key this version does not
know, or with a compliance block is refused whole: nothing is read past and dropped."""
kind = str(data.get("kind"))
if data.get("schema") != SCHEMA or data.get("version") != VERSION:
raise RamError(kind, "record", f"this reader reads {SCHEMA} version {VERSION}; the record is {data.get('schema')} version {data.get('version')}")
keys = {"schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance"}
for name, given, known in (("record", set(data), keys), ("ram", set(data.get("ram", ())), {f.name for f in fields(Ram)}),
("hinge", set(data.get("hinge", ())), {"pivot", "axis", "lo", "hi"})):
if given != known:
raise RamError(kind, "record", f"the {name}'s keys are not version {VERSION}'s: unknown {sorted(given - known)}, missing {sorted(known - given)}")
"""(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) 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")
hinge = data["hinge"]
m = Mechanism(data["kind"], hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=tuple(data["offsets"]),
parts=data["parts"], touch=data["touch"], **data["pins"])
return m, Ram(**data["ram"])
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()})
return m, Ram(**ram)
def swept(f, body, margin=0.0, steps=13, around=8):