"""Map a STEP guide face to passive keyed-block yaw dynamics.""" import argparse import hashlib import json import math import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parent def measure(step: Path, setup: dict) -> dict: import cadquery as cq shape = cq.importers.importStep(str(step)).val() if shape.ShapeType() != "Solid" or len(shape.Solids()) != 1 or not shape.isValid(): raise ValueError("Expected one valid gripper guide finger") mount = cq.Solid.makeBox(2.5, 50, 20, cq.Vector(-40, -25, -10)) envelope = cq.Solid.makeBox(22.5, 50, 20, cq.Vector(-40, -25, -10)) minimum = setup["guide_y_min_mm"] maximum = setup["guide_y_max_mm"] pitch = setup["guide_profile_pitch_mm"] count = round((maximum - minimum) / pitch) + 1 profile = [] for index in range(count): y = minimum + index * pitch slab = cq.Solid.makeBox( 60, setup["guide_slice_width_mm"], 20, cq.Vector(-50, y - setup["guide_slice_width_mm"] / 2, -10)) section = shape.intersect(slab) if section.Volume() <= 0: raise ValueError("Guide face missing at a sampled y coordinate") profile.append(section.BoundingBox().xmax / 1000) return { "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), "volume_mm3": shape.Volume(), "mount_missing_mm3": max(0.0, mount.Volume() - mount.intersect(shape).Volume()), "envelope_excess_mm3": max(0.0, shape.Volume() - shape.intersect(envelope).Volume()), "guide_face_x_profile_m": profile, } def dynamics(profile: list, setup: dict) -> dict: import pychrono as ch y_min = setup["guide_y_min_mm"] / 1000 pitch = setup["guide_profile_pitch_mm"] / 1000 def guide_at(y): index_position = (min(max(y, y_min), setup["guide_y_max_mm"] / 1000) - y_min) / pitch index = min(int(index_position), len(profile) - 2) fraction = min(max(index_position - index, 0), 1) face_x = profile[index] * (1 - fraction) + profile[index + 1] * fraction slope = (profile[index + 1] - profile[index]) / pitch return face_x, slope results = {} for initial_yaw in setup["initial_yaw_angles_rad"]: system = ch.ChSystemSMC() system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) system.SetSolver(ch.ChSolverSparseLU()) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) block = ch.ChBody() block.SetMass(setup["block_mass_kg"]) inertia = setup["block_yaw_inertia_kg_m2"] block.SetInertiaXX(ch.ChVector3d(inertia, inertia, inertia)) block.SetRot(ch.QuatFromAngleZ(initial_yaw)) system.Add(block) hinge = ch.ChLinkLockRevolute() hinge.Initialize(block, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) system.Add(hinge) contact_torque = ch.ChForce() block.AddForce(contact_torque) contact_torque.SetMode(ch.ChForce.TORQUE) contact_torque.SetDir(ch.ChVector3d(0, 0, 1)) dt = setup["time_step_s"] steps = round(setup["duration_s"] / dt) if dt <= 0 or abs(steps * dt - setup["duration_s"]) > 1e-12: raise ValueError("Invalid jaw closing time grid") peak_force = 0.0 for index in range(steps): time = index * dt rotation = block.GetRot() yaw = 2 * math.atan2(rotation.e3, rotation.e0) yaw_rate = block.GetAngVelParent().z fraction = min(time / setup["closing_duration_s"], 1.0) smooth = 3 * fraction ** 2 - 2 * fraction ** 3 jaw_shift = ( setup["jaw_initial_translation_m"] + (setup["jaw_final_translation_m"] - setup["jaw_initial_translation_m"]) * smooth ) moment = -setup["rotational_damping_N_m_s_rad"] * yaw_rate total_force = 0.0 for local_x, local_y in setup["keyed_block_contact_points_m"]: x = local_x * math.cos(yaw) - local_y * math.sin(yaw) y = local_x * math.sin(yaw) + local_y * math.cos(yaw) face_x, slope = guide_at(y) left_boundary = face_x + jaw_shift left_penetration = max(0.0, left_boundary - x) right_penetration = max(0.0, x + left_boundary) for penetration, side in ( (left_penetration, 1), (right_penetration, -1)): if penetration <= 0: continue force = (setup["contact_penalty_stiffness_N_m"] * penetration) force_x = side * force force_y = -slope * force moment += x * force_y - y * force_x total_force += force contact_torque.SetMforce(moment) system.DoStepDynamics(dt) peak_force = max(peak_force, total_force) rotation = block.GetRot() final_yaw = 2 * math.atan2(rotation.e3, rotation.e0) if not math.isfinite(final_yaw + peak_force): raise ValueError("Non-finite keyed-block alignment response") results[str(initial_yaw)] = { "final_yaw_rad": final_yaw, "final_yaw_error_rad": abs(final_yaw), "peak_total_guide_force_N": peak_force, "contact_profile_sample_count": len(profile), } return results def invoke(python: str, phase: str, payload: dict) -> dict: run = subprocess.run([python, str(Path(__file__).resolve()), "--phase", phase], input=json.dumps(payload), text=True, capture_output=True) if run.returncode: raise RuntimeError(f"{phase} failed:\n{run.stderr[-1600:]}") return json.loads(run.stdout) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--cad-python", default=sys.executable) parser.add_argument("--physics-python", default=sys.executable) parser.add_argument("--phase", choices=("measure", "dynamics")) args = parser.parse_args() if args.phase: payload = json.load(sys.stdin) result = (measure(Path(payload["step"]), payload["setup"]) if args.phase == "measure" else dynamics(payload["profile"], payload["setup"])) print(json.dumps(result)) return setup = json.loads((ROOT / "setup.json").read_text()) results = {} for name in ("before", "after"): properties = invoke(args.cad_python, "measure", { "step": str(ROOT / f"{name}.step"), "setup": setup}) profile = properties.pop("guide_face_x_profile_m") results[name] = { "step_properties": properties, "simulation_result": invoke(args.physics_python, "dynamics", { "profile": profile, "setup": setup}), } before, after = results["before"], results["after"] bp, ap = before["step_properties"], after["step_properties"] bs, gs = before["simulation_result"], after["simulation_result"] cases = [str(angle) for angle in setup["initial_yaw_angles_rad"]] baseline = [bs[case]["final_yaw_error_rad"] for case in cases] candidate = [gs[case]["final_yaw_error_rad"] for case in cases] reductions = [1 - a / b for a, b in zip(candidate, baseline)] checks = { "target_yaw_met_both_starts": max(candidate) <= setup["target_yaw_error_rad"], "yaw_error_reduced_both_starts": min(reductions) >= setup["required_relative_yaw_error_reduction"], "guide_force_limited": all(gs[case]["peak_total_guide_force_N"] <= setup["maximum_total_guide_force_N"] for case in cases), "volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <= setup["maximum_relative_volume_change"], "mount_fixed": ap["mount_missing_mm3"] <= setup["maximum_mount_missing_mm3"], "envelope_fixed": ap["envelope_excess_mm3"] <= setup["maximum_envelope_excess_mm3"], } after["comparison_to_before"] = { "relative_yaw_error_reductions": reductions, "checks": checks, "passed": all(checks.values()), } for name, result in results.items(): (ROOT / f"{name}.results.json").write_text(json.dumps(result, indent=2) + "\n") print(f"Final keyed-block yaw error: {baseline} -> {candidate} rad") print(f"Task passed: {all(checks.values())}") if not all(checks.values()): raise SystemExit(1) if __name__ == "__main__": main()