diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0473318..b1ddab5 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1583,16 +1583,23 @@ def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: HELD = 1e-5 # a connection or a closure holds when its residual is at most this: the add-on's HELD is this one # close_loop's three bounds, each read in FollowTests (lodur:ruling:deterministic-bound-margin). # Metres of in-plane closure error Newton stops at. Shipped worst error of an accepted solve 4.1e-11; the least -# error it was still iterating on 2.5e-10; the geometric mean, -# separation 2.4 each side (read by an instrumented copy over FollowTests' solves). +# error it was still iterating on 2.5e-10, which a tolerance of 3e-10 accepts; the geometric mean, separation 2.4 +# each side. FollowTests reads both from the solved frames: its sweep's worst error is under 1.0e-10. FOLLOW_TOLERANCE = 1e-10 # Newton steps one solve may take. Shipped worst 4 (a driver step of 5 degrees toward a dead centre, and one solve -# across a 40 degree jump); a rule, four times the worst. +# across a 40 degree jump); a rule, four times the worst, which FollowTests asserts of its sweep. FOLLOW_ITERATIONS = 16 -# The smaller singular value of the Jacobian with its two columns scaled to unit length (so a linkage's size and the -# metres-per-degree of a revolute column do not move it): about sin(angle between the columns) / sqrt(2), 0 at a dead -# centre, where the two unknowns move the closing pin along one line. Shipped least over the solves that are accepted -# 0.184; the greatest a refused solve reads 0.047 (the four-bar 6.7 degrees from straight); the geometric mean, separation 2.0 each side. +# The smaller singular value of the Jacobian with each column scaled by its lever: about sin(angle between the columns) +# / sqrt(2) for two revolute joints, 0 at a dead centre, where the two unknowns move the closing pin along one line. A +# revolute column is scaled to unit length (so a linkage's size and the metres-per-degree of a column do not move +# it), but for a ram, a revolute joint and then a prismatic one, by its lever with the slide at 0: that column is across +# the slide wherever the rod's end is on the bore's axis, and its dead centre is the rod's end on the barrel's pin, +# where the column vanishes; so a ram reads its lever over its closed lever, 1 at most. The reading is negative once +# the pair stands on the other assembly from its seed (the Jacobian's determinant about the pin has changed sign: an +# elbow bent the other way, a rod's end past its barrel's pin). Shipped least over the solves that are accepted 0.184 +# (the four-bar 30 degrees back from rest; a ram at 0.184 of its closed lever is accepted too); the greatest a refused +# solve reads 0.047 (the four-bar 6.7 degrees from straight; a ram at 0.047 of its closed lever); the geometric mean, +# separation 2.0 each side. FOLLOW_SINGULAR = 0.093 @@ -1606,8 +1613,9 @@ def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[t z x (q - o) pi / 180 for the joint's pin z through o, a prismatic one z), from `seed`: the root found is the one on the seed's assembly branch when the seed is near, so a caller steps its input. Refuses, naming which: pins that are not parallel (each revolute z along the target's z, each prismatic z across it, the closing z opposed - to it: the loop is planar); a dead centre (FOLLOW_SINGULAR); no convergence in FOLLOW_ITERATIONS; and a loop - that closes in the plane and misses along the pin (closure_residual over HELD).""" + to it: the loop is planar); a dead centre (FOLLOW_SINGULAR), and an iterate past one, on the other assembly from + the seed, so no solve answers the other branch; no convergence in FOLLOW_ITERATIONS; and a loop that closes in + the plane and misses along the pin (closure_residual over HELD).""" base, target = np.asarray(base_world, dtype=np.float64), np.asarray(target_world, dtype=np.float64) (parent_1, child_1, kind_1), (parent_2, child_2, kind_2) = joints n, values = target[:3, 2], np.array([float(seed[0]), float(seed[1])], dtype=np.float64) @@ -1629,14 +1637,22 @@ def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[t if float(np.abs(end[:3, 2] + n).max()) > HELD: raise KitError(f"the loop is not planar: closing socket {closing['name']!r} does not face the pin it closes on " f"(normals off by {float(np.abs(end[:3, 2] + n).max()):.6g})") + ram, side = (kind_1, kind_2) == ("revolute", "prismatic"), None for iteration in range(FOLLOW_ITERATIONS + 1): at_1, at_2, end = placed(values) error = target[:3, 3] - end[:3, 3] error = error - n * (error @ n) J = np.stack([np.cross(at[:3, 2], end[:3, 3] - at[:3, 3]) * (math.pi / 180.0) if kind == "revolute" else at[:3, 2] for kind, at in ((kind_1, at_1), (kind_2, at_2))], axis=1) - lengths = np.linalg.norm(J, axis=0) - singular = 0.0 if lengths.min() < 1e-12 else float(np.linalg.svd(J / lengths, compute_uv=False)[-1]) + levers = np.linalg.norm(J, axis=0) + if ram: # the barrel's lever with the rod's slide at 0 + levers[0] = np.linalg.norm(np.cross(at_1[:3, 2], placed((values[0], 0.0))[2][:3, 3] - at_1[:3, 3])) * (math.pi / 180.0) + singular = 0.0 if levers.min() < 1e-12 else float(np.linalg.svd(J / levers, compute_uv=False)[-1]) + here = float(n @ np.cross(J[:, 0], J[:, 1])) > 0.0 + side = here if side is None else side + if here != side: + raise KitError(f"the loop is past a dead centre (the step takes the two joints that move closing socket {closing['name']!r} to their " + f"other assembly: conditioning {singular:.3g} on that side)") if singular < FOLLOW_SINGULAR: raise KitError(f"the loop is at a dead centre (its two joints move closing socket {closing['name']!r} along one line: " f"conditioning {singular:.3g}, under {FOLLOW_SINGULAR:g})") @@ -1652,6 +1668,28 @@ def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[t return (float(values[0]), float(values[1])), iteration +def joint_rows(root_world, entries) -> tuple[list, int]: + """(the rows of a joints report, how many rigid connections folded into them). `entries` is every connection of + a tree in an order where a part comes after its parent: (id, the parent part's id, part name, parent socket, the + parent's 4x4 world, DOF kind or None for rigid, value, joint record, driven: what the report says drives it, or + None). A row is a revolute or prismatic connection; its parent is the nearest one above it (a rigid connection + belongs to the joint above it), its axis and origin the parent socket's z and origin in the frame of root_world, + and min and max what the limits leave of the value either way.""" + frame, nearest, rows, rigid = np.linalg.inv(np.asarray(root_world, dtype=np.float64)), {}, [], 0 + for name, parent, part_name, socket, parent_world, kind, value, record, driven in entries: + if kind is None: + nearest[name], rigid = nearest.get(parent), rigid + 1 + continue + at = frame @ np.asarray(parent_world, dtype=np.float64) @ socket["matrix"] + limits = record["limits"] and [round(v, 6) for v in record["limits"]] + rows.append({"id": name, "parent": nearest.get(parent), "part": part_name, "socket": f"{parent}:{socket['name']}", "kind": kind, + "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), + "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), + "mechanism": record["mechanism"], "compliance": record["compliance"], "driven": driven}) + nearest[name] = name + return rows, rigid + + EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 029da85..a8c4e41 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1594,6 +1594,35 @@ class JointRecordTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "it reaches -1.000000 m to 1.000000 m"): core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 1.5, 0.0, (0.0, 90.0)) + def test_joint_rows_are_the_tree_s_dof_connections_in_the_root_s_frame(self): + """core.joint_rows, what brokkr_kitbash.joints reports: a barrel on a strut's pin (revolute), its rod (prismatic) + and, on a root turned and moved in the world, a rigid part between two joints. Mutants J7 (a row's parent the + part's parent, not the nearest joint above: 'Plate'), J8 (min and max the limits themselves: -20 and 60 for + -50 and 30) and J11 (axis and origin in the world's frame: the origin stands 5.4 m off).""" + parts = self.kit["parts"] + strut, barrel, rod = (core.build(parts[name], {}) for name in ("strut", "ram_barrel", "ram_rod")) + socket = lambda built, name: next(s for s in built.sockets if s["name"] == name) # noqa: E731 + root = np.eye(4) + root[:3, :3] = core._rotation((20.0, -35.0, 50.0)) + root[:3, 3] = (1.0, -2.0, 5.0) + barrel_world = root @ core.mate(socket(strut, "end_b"), socket(barrel, "base"), 30.0) + record = {"limits": (-20.0, 60.0), "mechanism": "elbow", "compliance": None} + free = {"limits": None, "mechanism": None, "compliance": None} + rows, rigid = core.joint_rows(root, [ + ("Barrel", "Root", "ram_barrel", socket(strut, "end_b"), root, "revolute", 30.0, record, None), + ("Plate", "Barrel", "bracket", socket(barrel, "port_cap"), barrel_world, None, 0.0, free, None), + ("Rod", "Plate", "ram_rod", socket(barrel, "bore"), barrel_world, "prismatic", 0.125, free, {"by": "Barrel", "kind": "ratio", "k": 0.001, "offset": 0.095})]) + self.assertEqual(rigid, 1) + self.assertEqual([(row["id"], row["parent"], row["kind"], row["socket"]) for row in rows], + [("Barrel", None, "revolute", "Root:end_b"), ("Rod", "Barrel", "prismatic", "Plate:bore")]) + self.assertEqual((rows[0]["value"], rows[0]["limits"], rows[0]["min"], rows[0]["max"], rows[0]["mechanism"], rows[0]["driven"]), (30.0, [-20.0, 60.0], -50.0, 30.0, "elbow", None)) + self.assertEqual((rows[1]["value"], rows[1]["limits"], rows[1]["min"], rows[1]["max"], rows[1]["driven"]["by"]), (0.125, None, None, None, "Barrel")) + pin = socket(strut, "end_b")["matrix"] + self.assertEqual((rows[0]["axis"], rows[0]["origin"]), ([round(float(v), 6) for v in pin[:3, 2]], [round(float(v), 6) for v in pin[:3, 3]])) # in the root's frame: the socket as the part has it + bore = core.mate(socket(strut, "end_b"), socket(barrel, "base"), 30.0) @ socket(barrel, "bore")["matrix"] + self.assertEqual((rows[1]["axis"], rows[1]["origin"]), ([round(float(v), 6) for v in bore[:3, 2]], [round(float(v), 6) for v in bore[:3, 3]])) + self.assertGreater(float(np.linalg.norm((root @ pin)[:3, 3] - pin[:3, 3])), 5.0) # the world's frame is not the root's here + def test_limit_slack_sits_between_a_typed_end_and_the_least_refused(self): """joint-records-lows. core.LIMIT_SLACK at the midpoint of its readings (2.4e-07), read 1.2 either side: a slack of 1.9e-08 loses float32(-20.1) and the value 2e-07 off; one of 2e-06 or 2.9e-06 (or the 1e-06 there @@ -1618,6 +1647,7 @@ class FollowTests(unittest.TestCase): PHI = 2.8e-7 # degrees between the rocker's roll change and ram.pose's phi. shipped 1.9e-10; least mutant 4.0e-4 (T1); separation 1.4e3 each side SLID = 5.6e-10 # metres between the rod's slide and |pin - base| less the closed length. shipped 5.4e-13; least mutant 5.9e-7 (T1); separation 1.0e3 each side BRANCH = 1e-6 # degrees between one solve across a jump and the stepped answer. shipped 4e-12 (both converge to FOLLOW_TOLERANCE); a rule: the other branch stands tens of degrees off + CLOSED = 1.0e-10 # metres an accepted solve's closing origin stands from the pin, read from the frames. shipped worst 4.1e-11; a FOLLOW_TOLERANCE of 3e-10 reads 2.5e-10; separation 2.5 each side @classmethod def setUpClass(cls): @@ -1666,7 +1696,7 @@ class FollowTests(unittest.TestCase): return float(np.linalg.svd(np.stack(columns, axis=1), compute_uv=False)[-1]) def stepped(self, deltas): - seed, worst = self.REST, {"phi": 0.0, "iterations": 0, "conditioning": math.inf} + seed, worst = self.REST, {"phi": 0.0, "iterations": 0, "conditioning": math.inf, "closed": 0.0} rest = (core.mate(self.rocker_pin, self.rocker["end_a"], self.REST[0]) @ self.rocker["end_b"]["matrix"])[:3, 3] four_bar = self.ram.Mechanism("four_bar", pivot=self.ground["matrix"][:3, 3], axis=self.ground["matrix"][:3, 2], lo=-90, hi=130, a=np.array([0.3, 0.0, -0.4]), rocker=self.rocker_pin["matrix"][:3, 3], p=rest, c=self.crank_pin(self.D0)[:3, 3], d=rest) @@ -1674,15 +1704,21 @@ class FollowTests(unittest.TestCase): seed, iterations = self.solve(self.D0 + delta, seed) worst["phi"] = max(worst["phi"], abs(seed[0] - self.REST[0] - math.degrees(self.ram.pose(four_bar, delta).phi[0]))) worst["iterations"], worst["conditioning"] = max(worst["iterations"], iterations), min(worst["conditioning"], self.conditioning(seed)) + worst["closed"] = max(worst["closed"], float(np.linalg.norm(self.crank_pin(self.D0 + delta)[:3, 3] - self.coupler_end(self.rocker_pin, seed)[:3, 3]))) return seed, worst def test_a_four_bar_loop_matches_ram_pose(self): """loop-matches-ram-pose. 56 driver steps of 5 degrees, +120 and back to -30. Mutant F1 (a revolute Jacobian column's sign flipped: no solve converges). The readings here are the shipped side of core's three bounds: - conditioning least 0.184 (at -30), iterations at most 4 (the step to -30).""" + conditioning least 0.184 (at -30), iterations at most 4 (the step to -30), and the closing origin 4.1e-11 m + from the pin at worst: a FOLLOW_TOLERANCE of 3e-10 stops one step short on 2.5e-10. FOLLOW_ITERATIONS is its + rule, four times the worst.""" _, worst = self.stepped([*np.arange(0.0, 121.0, 5.0), *np.arange(120.0, -31.0, -5.0)]) self.assertLess(worst["phi"], self.PHI) self.assertEqual(worst["iterations"], 4) + self.assertEqual(core.FOLLOW_ITERATIONS, 4 * worst["iterations"]) + self.assertLess(worst["closed"], self.CLOSED) + self.assertLess(worst["closed"], core.FOLLOW_TOLERANCE) self.assertAlmostEqual(worst["conditioning"], 0.184, delta=0.001) self.assertGreater(worst["conditioning"], 1.2 * core.FOLLOW_SINGULAR) @@ -1699,14 +1735,46 @@ class FollowTests(unittest.TestCase): self.assertLess(worst, self.SLID) self.assertGreater(seed[1] - self.RAM_REST[1], 0.2) # the rod moved + def test_a_ram_s_dead_centre_is_its_rod_end_on_the_barrel_pin(self): + """A ram's conditioning is its lever over its lever closed, and its dead centre the rod's end on the barrel's + pin: drawn in along its own line the ram is accepted at 0.184 of the closed lever and refused at 0.047, the two + readings core.FOLLOW_SINGULAR sits between; and one solve to a pin on the far side of the barrel's, which + Newton answers in one step with the rod's end through the pin, is refused as past the dead centre and not + answered. Mutants C1 (the ram's revolute column scaled to unit length as a four-bar's: it reads 1 at 0.047) + and C2 (the side not read: the far pin is answered at a slide of -1.2 closed levers).""" + base, rest = self.barrel_pin["matrix"][:3, 3], self.crank_pin(self.D0, "end_b_back") + closed = float(np.linalg.norm(self.rod_end(self.barrel_pin, (self.RAM_REST[0], 0.0))[:3, 3] - base)) + along = (rest[:3, 3] - base) / np.linalg.norm(rest[:3, 3] - base) + + def pin(lever): + target = rest.copy() + target[:3, 3] = base + along * lever * closed + return target + + seed = self.RAM_REST + for lever in (1.0, 0.8, 0.6, 0.4, 0.3, 0.184): + seed, _ = core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(lever), seed) + self.assertAlmostEqual(seed[1], (lever - 1.0) * closed, delta=self.SLID) + self.assertAlmostEqual(seed[0], self.RAM_REST[0], delta=self.BRANCH) + self.assertGreater(0.184, 1.2 * core.FOLLOW_SINGULAR) + self.assertLess(0.047, core.FOLLOW_SINGULAR / 1.2) + with self.assertRaisesRegex(core.KitError, r"^the loop is at a dead centre \(its two joints move closing socket 'rod_end' along one line: conditioning 0\.047, under 0\.093\)$"): + core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(0.047), seed) + with self.assertRaisesRegex(core.KitError, r"^the loop is past a dead centre \(the step takes the two joints that move closing socket 'rod_end' to their other assembly: " + r"conditioning 0\.184 on that side\)$"): + core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(-0.184), seed) + def test_a_dead_centre_is_refused(self): """loop-refusals. Stepping the crank back, rocker and coupler straighten: the step to -35 stands 6.7 degrees - from straight, conditioning 0.047, the refused side of core.FOLLOW_SINGULAR; past it no pose closes the loop.""" + from straight, conditioning 0.047, the refused side of core.FOLLOW_SINGULAR; past it no pose closes the loop, + and at -60 Newton's first step bends the pair the other way, which is refused as past the dead centre.""" seed, _ = self.stepped(np.arange(0.0, -31.0, -5.0)) self.assertLess(0.047, core.FOLLOW_SINGULAR / 1.2) - for delta in (-35.0, -40.0, -60.0): + for delta in (-35.0, -40.0): with self.assertRaisesRegex(core.KitError, r"^the loop is at a dead centre \(its two joints move closing socket 'end_b' along one line"): self.solve(self.D0 + delta, seed) + with self.assertRaisesRegex(core.KitError, r"^the loop is past a dead centre \(the step takes the two joints that move closing socket 'end_b' to their other assembly"): + self.solve(self.D0 - 60.0, seed) near, _ = self.stepped(np.arange(0.0, -34.0, -1.0)) # by single degrees it is accepted to -33, and -34 reads 0.092 self.assertAlmostEqual(self.conditioning(near), 0.1212, delta=0.001) with self.assertRaisesRegex(core.KitError, r"conditioning 0\.0919, under 0\.093\)$"): @@ -1731,6 +1799,15 @@ class FollowTests(unittest.TestCase): core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], missed, self.REST) self.assertEqual(self.solve(self.D0, self.REST), (self.REST, 0)) # at rest it holds: no step is taken + def test_a_loop_that_does_not_converge_is_refused(self): + """loop-refusals. A pin 3.9 m out of the reach of a 0.9 and a 0.7 strut, where Newton from rest neither + straightens the pair nor bends it the other way in FOLLOW_ITERATIONS steps: refused by its own name, with + how far off it stands.""" + target = self.crank_pin(self.D0) + target[:3, 3] += (-1.2, 0.0, 3.8) + with self.assertRaisesRegex(core.KitError, r"^the loop did not close in 16 steps \(closing socket 'end_b' stands 3\.94584 m off in the plane\)$"): + core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], target, self.REST) + def test_stepping_keeps_the_assembly_branch(self): """branch-kept. One solve across a 40 degree jump lands on the stepped answer; one solve from near the toggle (-32) across 49 degrees does not: Newton's first step throws the pair through the dead centre, where it is @@ -2458,6 +2535,17 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("core.close_loop("), 1) self.assertIn("core.close_loop(", source.split("\ndef driven(")[1].split("\n\n\n")[0]) self.assertEqual(source.count("write_connections(["), 2) # write_connection, and follow clearing a statement + # every entry is checked before one is written (mutant J5, a refusal raised after the writes; F5 is its live twin): the writer's loop runs over the + # checks' whole answer and raises nothing itself, and the checks write nothing + self.assertIn(" for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in connection_checks(entries):\n child.parent = parent\n", writer) + self.assertNotIn("raise ", writer) + checks = source.split("\ndef connection_checks(")[1].split("\n\n\n")[0] + self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[\w+\]\s*=(?!=)|\bdel ", checks)) + self.assertEqual(checks.count("raise Refused("), 1) + # a hose keeps no roll range of its own (mutant J9, a default range for a pin that states no limits): it reads the record's limits and refuses without them + hose = source.split("class BROKKR_KITBASH_OT_hose(")[1].split("\n\n\n")[0] + self.assertEqual(re.findall(r"[^\n]*\blimits\s*=(?!=)[^\n]*", hose), [' limits = joint_record(child)["limits"] # the roll range the hose is proven over is the pin\'s own: its connection\'s limits']) + self.assertIn(' if limits is None:\n raise Refused(f"{child.name!r} on {child.parent.name!r}: the pin the hose crosses states no limits', hose) pose = source.split("\ndef pose(")[1].split("\n\n\n")[0] self.assertLess(pose.index("if follows is not None and not keeps:"), pose.index("= solve(child")) self.assertEqual(source.count("keeps=True"), 1) @@ -2638,7 +2726,9 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) self.assertIn(assigned[0], bodies["close"]) deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, \*RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) - self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen; mutant J10 (detach's keys without kit_min) dies on the first + record = re.search(r"^RECORD = \((.*)\)$", source, re.M).group(1).split(", ") + self.assertEqual(record, ["SLIDE", "LIMIT_MIN", "LIMIT_MAX", "MECHANISM", "COMPLIANCE", "FOLLOWS", "FOLLOWS_DRIVER"]) # the whole joint record: what detach clears self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" self.assertIsNone(re.search(placing, bodies["close"]))