From d8cfa7d28da312a820b4ebb1896d5496d0d71dc7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:49:45 +0100 Subject: [PATCH] tests/test_ram: hand cases, loop closure, rates, the R-3 deep knee, the third body, the bell crank clear of every body test_kitbash's package file list admits ram.py, which puts it under the package's negative patterns. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_kitbash.py | 2 +- surfaces/blender/tests/test_ram.py | 618 +++++++++++++++++++++++++ 2 files changed, 619 insertions(+), 1 deletion(-) create mode 100644 surfaces/blender/tests/test_ram.py diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 1d66c66..6e7a0a5 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1690,7 +1690,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", "mechanical.v0.json"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "mechanical.v0.json", "ram.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..d47a760 --- /dev/null +++ b/surfaces/blender/tests/test_ram.py @@ -0,0 +1,618 @@ +"""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 distance +oracles: boxes, capsules and cylinders across x. + +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 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 distance oracle over analytic shapes per body: ("capsule", p, q, r), ("box", lo, hi), and + ("cyl", centre, r, half): a cylinder across x. Inside a shape the distance is 0. `cap` caps what it returns.""" + + def __init__(self, cap=None, **shapes): + self.shapes, self.cap, self.asked = shapes, 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.maximum(np.linalg.norm(pts - p - t[:, None] * along, axis=1) - shape[3], 0.0) + if shape[0] == "box": + out = np.maximum(np.maximum(np.asarray(shape[1], float) - pts, pts - np.asarray(shape[2], float)), 0.0) + return np.linalg.norm(out, axis=1) + centre = np.asarray(shape[1], float) + rel = pts - centre + return np.hypot(np.maximum(np.hypot(rel[:, 1], rel[:, 2]) - shape[2], 0.0), np.maximum(np.abs(rel[:, 0]) - shape[3], 0.0)) + + def __call__(self, body, pts): + self.asked += len(pts) + out = np.full(len(pts), math.inf) + for shape in self.shapes.get(body, ()): + out = np.minimum(out, self.one(shape, pts)) + return out if self.cap is None else np.minimum(out, self.cap) + + +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)]) +X_COUPLER, X_ROCKER = 0.33, 0.43 # where the twin link plates stand: outside the shin's side armour (0.2325) + +# 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_bodies(m, ram, cap=None): + """The R-3 thigh and shin, and the mechanism's own links as bodies: twin bars of link_r, and the rocker's axle + through the knee's width. The pins at p and d belong to the clevises that turn on them, not to a body.""" + 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)] + Rk = m.rocker + rocker = twin(Rk, m.p, X_ROCKER) + [("capsule", (-X_ROCKER, Rk[1], Rk[2]), (X_ROCKER, Rk[1], Rk[2]), 0.028)] + if m.kind == "bell_crank": + rocker += twin(Rk, m.d, X_ROCKER) + return Bodies(cap, parent=R3_THIGH, child=R3_SHIN, rocker=rocker, coupler=twin(m.p, m.c, X_COUPLER)) + + +@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, f.barrel, 0.0)[0]), f.travel + f.ram.over, places=12) + self.assertAlmostEqual(float(R.extension(m, f.ram, f.barrel, -60.0)[0]), f.ram.over, places=12) + + 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")) + self.assertIn("direct ram: stroke", 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.assertIn("toggle at", str(refusal)) + + def test_clash_and_which(self): + m, ram = self.direct(-60, 0), R.Ram(0.05) + f = R.fit(m, ram, distance=Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.2)]), spacing=0.02) + self.assertGreater(f.clear_min, 0.0) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, distance=Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.3)]), spacing=0.02) + self.assertEqual(caught.exception.gate, "clash") + self.assertIn("body parent", str(caught.exception)) + self.assertEqual(caught.exception.fit.clear_at[2], "parent") + # 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) + barrel = R._fit(wide, ram).barrel + for angle in (-50.0, 0.0, 35.0): + on_child, where = R.clearance(wide, ram, barrel, angle, Bodies(child=[("capsule", p, q, 0.1)])) + on_parent, _ = R.clearance(wide, ram, barrel, angle, Bodies(parent=[("capsule", turned(p, angle), turned(q, angle), 0.1)])) + self.assertAlmostEqual(float(on_child[0]), float(on_parent[0]), places=9) + self.assertEqual(where[2], "child") + box = Bodies(parent=[("box", (-0.2, -0.36, -0.2), (0.2, -0.2, 0.2))]) + self.assertLess(R._fit(self.direct(-10, 0), ram, distance=box).clear_min, 0.0) + + 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 = Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.18)]) + s = R.search("direct", hinge, ram, seats, distance=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(R.Mechanism("direct", O, X, -70, 0, a=a, b=b), ram, distance=pin) + self.assertTrue(not f.ok or f.arm_min <= s.best.arm_min + 1e-9) + 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 - 1e-9).all() and (inside <= hi + 1e-9).all(), body) + # 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) + with self.assertRaises(R.RamError): + R.swept(f, "rocker") + + +@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()), 1e-9, kind) + self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - m.rocker, n), axis=1) - m.lr).max()), 1e-9, 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))), 1e-9, (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) + + 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()), 1e-3) + + 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.assertIn(f"assembly at {refusal.angle:g} deg", 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()), 1e-9) + 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()), 1e-5) + + +# 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 + + +@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), ("four_bar", "load")) + self.assertIn("load at", 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 = Bodies(parent=R3_THIGH, child=R3_SHIN) + 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, distance=bodies).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, distance=bodies) + 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) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, steps=49, distance=r3_bodies(m, ram)) + refusal = caught.exception + self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "clash")) + self.assertEqual(refusal.fit.clear_at[2], "child") + self.assertIn("barrel", refusal.fit.clear_at[1]) + self.assertIn("body child", str(refusal)) + self.assertLess(refusal.angle, -100.0) + # against the thigh and the rocker alone, the two bodies the ram spans, the same ram is clear + two = r3_bodies(m, ram) + del two.shapes["child"], two.shapes["coupler"] + margin, _ = R.clearance(m, ram, refusal.fit.barrel, np.linspace(-125, 0, 49), two) + self.assertGreaterEqual(float(margin.min()), 0.0) + + def test_a_link_body_in_the_rams_way(self): + # a gusset on the bell crank's rocker, between its plates where the ram runs: refused naming the rocker + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies = r3_bodies(m, ram) + rest = R.pose(m, 0.0) + web = rest.eye[0] - 0.06 * rest.u[0] # on the rod's line at rest, clear of the eye's clevis + bodies.shapes["rocker"].append(("capsule", web - (0.1, 0, 0), web + (0.1, 0, 0), 0.02)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, steps=49, distance=bodies) + self.assertEqual(caught.exception.gate, "clash") + self.assertEqual(caught.exception.fit.clear_at[2], "rocker") + self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) + self.assertIn("body rocker", str(caught.exception)) + + def test_bell_crank_seats_and_clears_every_body(self): + # the bell crank stands in front of the knee: over 0..-125 its ram, rocker and coupler clear the thigh, the + # shin, and each other's bodies, with the links' plates on either side + ram = R.Ram(BORE) + for side in (1.0, -1.0): + m = r3("bell_crank", CRANK, side) + bodies = r3_bodies(m, ram) + 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) + # every member met every body but its own, the shin among them, at -125 as at every step + fine = np.linspace(-125, 0, 251) + seen = {} + for name, start, end, radius, own in R._members(m, ram, f.barrel, R.pose(m, fine)): + for body in R.BODIES["bell_crank"]: + if body == own: + continue + pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0, 1, 40)[None, :, None] + got = bodies(body, R._into(m, R.pose(m, fine), body, pts).reshape(-1, 3)).reshape(len(fine), 40) + seen[(name, body)] = float(got.min() - radius - ram.gap) + at_deep = float(got[0].min() - radius - ram.gap) + self.assertGreaterEqual(at_deep, 0.0, (name, body, "at -125")) + self.assertEqual(len(seen), 2 * 4 + 3 * 3) # barrel and rod meet four bodies; three bars meet three + self.assertGreaterEqual(min(seen.values()), 0.0, min(seen, key=seen.get)) + self.assertEqual(sum(1 for _, body in seen if body == "child"), 5) + + +# 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 Bodies(cap, parent=[("capsule", at, at, r)]) + + 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 = {name: (start, end, radius) for name, 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)) + margin, where = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(centre, 0.2), spacing) + self.assertEqual(bool(margin[0] >= 0.0), clear, (slip, margin)) + self.assertAlmostEqual(float(margin[0]), slip, places=9) + self.assertEqual(where, (0.0, "barrel[0]", "parent")) + self.assertAlmostEqual(ram.reach(spacing), need, places=15) + + def test_clevis_ends_are_exempt(self): + # a ball on the base pin and one on the eye touch no sample: the barrel starts e_a from the base, the rod + # stops 0.4 e_b short of the eye + ram = self.ram + for at, r in ((self.m.a, ram.e_a - ram.barrel_r - ram.gap - ram.barrel_r / 2 - 1e-6), (self.m.b, 0.4 * ram.e_b - ram.rod - ram.gap - ram.barrel_r / 2 - 1e-6)): + margin, _ = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(np.array(at, float), r)) + self.assertGreaterEqual(float(margin[0]), 0.0) + margin, _ = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(np.array(at, float), r + 2e-6)) + self.assertLess(float(margin[0]), 0.0) + + 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) + barrel = R._fit(m, ram, steps=49).barrel + angles = np.linspace(-125, 0, 49) + free, _ = R.clearance(m, ram, barrel, angles, r3_bodies(m, ram)) + capped, _ = R.clearance(m, ram, barrel, angles, r3_bodies(m, ram, cap=ram.reach())) + 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)) + 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 = Bodies(parent=[("capsule", centre, centre, 0.07)]) + found = R.search("direct", self.HINGE, ram, seats, distance=block) + clear = [a for _, a in arms if R._fit(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), 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) + + 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) + crank = R.candidates("bell_crank", hinge, {**seats, "d": (0.12, 0.24, 3)}) + self.assertEqual(len(crank), 2 * 5 * 24 * 3 * 12) + + +@unittest.skipIf(np is None, "numpy is not installed") +class RecordDrives(unittest.TestCase): + def test_round_trip_and_drive(self): + ram = R.Ram(BORE) + for m in (r3("four_bar", DEEP), r3("bell_crank", CRANK), 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, f.barrel) + wire = json.loads(json.dumps(data)) + self.assertEqual(wire, data) + again, ram2, barrel = R.from_record(wire) + self.assertEqual(R.record(again, ram2, barrel), data) + 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, barrel, angles) + self.assertEqual(ext.tolist(), (R.length(m, angles) - data["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.assertAlmostEqual(data["closed"], f.closed, places=15) + + 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) + barrel = R._fit(m, ram).barrel + # a ball beside the twin at +0.2 only + ball = Bodies(parent=[("capsule", (0.2, -0.45, 0.5), (0.2, -0.45, 0.5), 0.06)]) + margin, where = R.clearance(m, ram, barrel, 0.0, ball) + self.assertLess(float(margin[0]), 0.0) + self.assertEqual(where[1], "barrel[0.2]") + + +@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.refused("record", lo=0, hi=0) + self.refused("record", lo=-200, hi=200) + self.refused("record", offsets=()) + 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, "arm") + self.assertIn("arm at", str(caught.exception)) + + def test_no_blender(self): + source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") + for word in ("bpy", "mathutils", "np.gradient"): + self.assertNotIn(word, source) + + +if __name__ == "__main__": + unittest.main()