From e7b10342bcf364f64ae124acac84b262e4823976 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:01:36 +0100 Subject: [PATCH] tests/test_ram: zones end at their radius, a pin stood inside what it stands beside, frames, the barrel's back end, the record's wall, a world's answer Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_ram.py | 362 ++++++++++++++++++++++++----- 1 file changed, 303 insertions(+), 59 deletions(-) diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 314e747..b80d4ab 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -1,7 +1,7 @@ """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 the Blender reading docs/kitbash.md states, not these stand-ins. +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.""" @@ -75,7 +75,7 @@ def two(parent=(), child=(), cap=None, **more): def dressed(m, bodies, touch=None): - """The mechanism with the bodies' parts in its record, and what each member may touch.""" + """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 {}) @@ -98,6 +98,7 @@ R3_SHIN = ([("cyl", O, 0.25, 0.18), ("cyl", O, 0.19, 0.205), ("box", (-0.11, -0. ("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. @@ -114,26 +115,64 @@ def r3(kind, pins, side=1.0, lo=-125.0, hi=0.0): return R.Mechanism(kind, O, X, lo, hi, **{name: yz(pins[name], at[name]) for name in pins}) -def r3_bodies(m, ram, cap=None): - """(Bodies, touch) of an R-3 linkage: the thigh and shin, 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. Each member - may touch its own plates and pins and the plates stacked beside it on a pin it rides; the ram, its eye's pin.""" +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), + 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, 0.028)), "pin p": ("rocker", across(m.p, 0.026)), - "coupler plates": ("coupler", twin(m.p, m.c, X_COUPLER)), "pin c": ("coupler", across(m.c, 0.026))} - own = ["rocker plates", "rocker axle", "pin p"] + (["pin d"] if crank else []) - touch = {"barrel": ["pin p"], "rod": ["pin p"], "rocker": own + ["coupler plates"], "coupler": ["coupler plates", "pin c", "rocker plates", "pin p"]} + "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, 0.026)) - touch.update({"barrel": ["pin d"], "rod": ["pin d"], "rocker arm": own}) - return Bodies(parts, cap), touch + 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, whole length. 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(m.d - m.rocker)) + 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), + ("rocker plates", "rocker", 1.01 * m.lr, ram.link_r), ("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), + ("coupler plates", "p", 1.01 * m.lc, ram.link_r), ("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), + ("rocker plates", "rocker", 1.01 * arm, ram.link_r)] + 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") @@ -226,6 +265,31 @@ class HandCases(unittest.TestCase): 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))} @@ -235,7 +299,7 @@ class HandCases(unittest.TestCase): 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 + 1e-9) + 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) @@ -251,9 +315,9 @@ class HandCases(unittest.TestCase): 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 - 1e-9).all() and (inside <= hi + 1e-9).all(), body) + 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()), 1e-12) + 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") @@ -267,6 +331,12 @@ class HandCases(unittest.TestCase): 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): @@ -282,8 +352,8 @@ class Loop(unittest.TestCase): 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()), 1e-12) - self.assertLess(float(np.abs(p.eye[-1] - m.d).max()), 1e-12) + 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 @@ -487,8 +557,9 @@ class DeepKnee(unittest.TestCase): 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, where the rod runs at -60: refused naming the part and its - # body, unless the record lets the rod and the barrel touch it; letting another member touch it changes nothing + # 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, :] @@ -496,20 +567,24 @@ class DeepKnee(unittest.TestCase): 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)] - for allowed in ({}, {"coupler": touch["coupler"] + ["lug"]}): + + 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(1.0, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)), + ("a zone too shallow", zones(1.0, 0.01))): with self.assertRaises(R.RamError) as caught: - R.fit(dressed(m, bodies, {**touch, **allowed}), ram, steps=49, distance=bodies) - self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), body) + 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)) - free = {**touch, "rod": touch["rod"] + ["lug"], "barrel": touch["barrel"] + ["lug"]} - f = R.fit(dressed(m, bodies, free), ram, steps=49, distance=bodies) + f = R.fit(dressed(m, bodies, zones(1.0, 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_it_may_not_touch(self): + 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 but those the record lets it touch, on either side, and all are clear + # 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) @@ -520,24 +595,84 @@ class DeepKnee(unittest.TestCase): 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]", "rod[0]", "rocker", "coupler", "rocker arm") - let = {(label, part) for label in members for part in touch[label.split("[")[0]]} - self.assertEqual(set(f.allowed), let) - self.assertEqual(len(let), 1 + 1 + 5 + 4 + 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} - let) - self.assertEqual(len(f.pairs), 5 * 8 - 15) - self.assertEqual(sum(1 for _, part in f.pairs if part == "shin"), 5) - self.assertEqual(sum(1 for _, part in f.pairs if bodies.parts[part] == "coupler"), 2 * 2 + 1 + 2) # the rocker may touch the plates beside it on p + 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 lets: the pins a member rides + # 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.assertTrue(refused and refused <= let, refused - let) - self.assertEqual(len(bare.pairs), 40) + 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, 0.03)]}), ram, steps=49, distance=bodies) + self.assertEqual(f.pairs[("rocker", "rail")][0] >= 0.0, clear, radius) + + 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 lets it: the depth is the record's to state and to be read + deep = {**touch, member: [(part, pin, zone[2], depth) if zone[0] == part else zone for zone in touch[member]]} + self.assertGreaterEqual(R._fit(replace(m, touch=deep), ram, steps=49, distance=bodies).pairs[(member, part)][0], 0.0) + + 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 @@ -576,22 +711,40 @@ class OracleRule(unittest.TestCase): 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_touch_is_the_only_exemption(self): - # a clevis on the base pin and one on the eye, each a part: with nothing let they refuse the ram at its own - # pins; let to the member that rides the pin they are skipped; let to the other member they still refuse - ram = self.ram - seats = two(a=("parent", [("capsule", self.m.a, self.m.a, 0.03)]), b=("child", [("capsule", self.m.b, self.m.b, 0.03)])) - bare = R.clearance(dressed(self.m, seats), ram, 0.0, seats) - self.assertLess(bare.pairs[("barrel[0]", "a")][0], 0.0) - # the rod runs to the eye: its last sample is the pin's centre, the ball's depth inside it - self.assertAlmostEqual(bare.pairs[("rod[0]", "b")][0], -0.03 - (ram.rod + ram.gap + ram.barrel_r / 2), places=12) + 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, []) - let = R.clearance(dressed(self.m, seats, {"barrel": ["a"], "rod": ["b"]}), 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 - 2) - crossed = R.clearance(dressed(self.m, seats, {"barrel": ["b"], "rod": ["a"]}), ram, 0.0, seats) - self.assertLess(float(crossed.margin[0]), 0.0) + 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)])}) @@ -628,7 +781,7 @@ class OracleRule(unittest.TestCase): 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.allclose(np.minimum(free, 0.0), np.minimum(capped, 0.0), atol=1e-12)) + 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 @@ -657,6 +810,44 @@ class SearchBestFirst(unittest.TestCase): 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": "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) 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))} @@ -673,6 +864,13 @@ class SearchBestFirst(unittest.TestCase): 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) @@ -720,7 +918,8 @@ class RecordDrives(unittest.TestCase): 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, {k: tuple(v) for k, v in m.touch.items()})) + 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) @@ -752,11 +951,45 @@ class RecordDrives(unittest.TestCase): 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']")): + ({"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)) @@ -791,8 +1024,19 @@ class Refusals(unittest.TestCase): 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"]}))) - self.assertIn("rod may touch 'hip'", str(self.refused("record", parts={"knee": "parent"}, touch={"rod": ["hip"]}))) + 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