"""Drive a four-bar linkage using joint and tool locations from a STEP coupler.""" 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 from OCP.BRepAdaptor import BRepAdaptor_Surface from OCP.BRepGProp import BRepGProp from OCP.GProp import GProp_GProps shape = cq.importers.importStep(str(step)).val() if shape.ShapeType() != "Solid" or not shape.isValid() or len(shape.Solids()) != 1: raise ValueError(f"Expected one valid solid: {step}") props = GProp_GProps() BRepGProp.VolumeProperties_s(shape.wrapped, props) if props.Mass() <= 0: raise ValueError("Coupler volume must be positive") holes = [] for face in shape.Faces(): if face.geomType() != "CYLINDER": continue cylinder = BRepAdaptor_Surface(face.wrapped).Cylinder() axis = cylinder.Axis().Location() holes.append((cylinder.Radius(), axis.X(), axis.Y())) pivots = sorted([[x, y] for radius, x, y in holes if abs(radius - 5) < 1e-5]) markers = [[x, y] for radius, x, y in holes if abs(radius - 2) < 1e-5] if len(pivots) != 2 or len(markers) != 1: raise ValueError("Expected two 5 mm pivot bores and one 2 mm tool marker bore") bounds = shape.BoundingBox() inertia = props.MatrixOfInertia() density = setup["material_density_kg_m3"] bores = [cq.Solid.makeCylinder(5, 10, cq.Vector(x, y, -5)) for x, y in ((0, 0), (100, 0))] return { "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), "volume_mm3": props.Mass(), "mass_kg": props.Mass() * density * 1e-9, "center_of_mass_mm": list(props.CentreOfMass().Coord()), "inertia_tensor_kg_m2": [ [inertia.Value(i, j) * density * 1e-15 for j in (1, 2, 3)] for i in (1, 2, 3) ], "bounds_mm": [bounds.xmin, bounds.xmax, bounds.ymin, bounds.ymax, bounds.zmin, bounds.zmax], "pivot_centers_mm": pivots, "tool_marker_mm": markers[0], "pivot_bore_intrusion_mm3": sum(shape.intersect(bore).Volume() for bore in bores), } def dynamics(properties: dict, setup: dict) -> dict: import pychrono as ch crank_length = setup["crank_length_m"] rocker_length = setup["rocker_length_m"] ground_spacing = setup["ground_pivot_spacing_m"] pivot0, pivot1 = properties["pivot_centers_mm"] coupler_vector = [(pivot1[i] - pivot0[i]) / 1000 for i in (0, 1)] coupler_length = math.hypot(*coupler_vector) theta = math.radians(setup["initial_crank_angle_deg"]) a = (crank_length * math.cos(theta), crank_length * math.sin(theta)) d = (ground_spacing, 0.0) dx, dy = d[0] - a[0], d[1] - a[1] diagonal = math.hypot(dx, dy) along = (coupler_length ** 2 - rocker_length ** 2 + diagonal ** 2) / (2 * diagonal) height_sq = coupler_length ** 2 - along ** 2 if height_sq <= 0: raise ValueError("Coupler cannot close the fixed four-bar linkage") height = math.sqrt(height_sq) ex, ey = dx / diagonal, dy / diagonal b = (a[0] + along * ex - height * ey, a[1] + along * ey + height * ex) phi = (math.atan2(b[1] - a[1], b[0] - a[0]) - math.atan2(coupler_vector[1], coupler_vector[0])) psi = math.atan2(b[1] - d[1], b[0] - d[0]) system = ch.ChSystemNSC() system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) crank = ch.ChBodyEasyBox(crank_length, 0.01, 0.01, 7800, False, False) crank.SetPos(ch.ChVector3d(a[0] / 2, a[1] / 2, 0)) crank.SetRot(ch.QuatFromAngleAxis(theta, ch.VECT_Z)) system.Add(crank) rocker = ch.ChBodyEasyBox(rocker_length, 0.01, 0.01, 7800, False, False) rocker.SetPos(ch.ChVector3d((d[0] + b[0]) / 2, (d[1] + b[1]) / 2, 0)) rocker.SetRot(ch.QuatFromAngleAxis(psi, ch.VECT_Z)) system.Add(rocker) center = [value / 1000 for value in properties["center_of_mass_mm"]] center_from_pivot = (center[0] - pivot0[0] / 1000, center[1] - pivot0[1] / 1000) coupler = ch.ChBody() coupler.SetMass(properties["mass_kg"]) inertia = ch.ChMatrix33d() inertia.SetMatr(properties["inertia_tensor_kg_m2"]) coupler.SetInertia(inertia) coupler.SetPos(ch.ChVector3d( a[0] + center_from_pivot[0] * math.cos(phi) - center_from_pivot[1] * math.sin(phi), a[1] + center_from_pivot[0] * math.sin(phi) + center_from_pivot[1] * math.cos(phi), center[2])) coupler.SetRot(ch.QuatFromAngleAxis(phi, ch.VECT_Z)) system.Add(coupler) motor = ch.ChLinkMotorRotationSpeed() motor.Initialize(crank, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) motor.SetSpeedFunction(ch.ChFunctionConst(setup["crank_speed_rad_s"])) system.Add(motor) for first, second, point in ((crank, coupler, a), (coupler, rocker, b), (rocker, ground, d)): joint = ch.ChLinkLockRevolute() joint.Initialize(first, second, ch.ChFramed( ch.ChVector3d(point[0], point[1], 0))) system.Add(joint) def on_coupler(point_mm: list) -> object: return coupler.TransformPointLocalToParent(ch.ChVector3d( (point_mm[0] - properties["center_of_mass_mm"][0]) / 1000, (point_mm[1] - properties["center_of_mass_mm"][1]) / 1000, -center[2])) 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 simulation duration or time step") target_time = None maximum_joint_error = 0.0 maximum_marker_y = -math.inf for i in range(steps): system.DoStepDynamics(dt) marker = on_coupler(properties["tool_marker_mm"]) if not math.isfinite(marker.x + marker.y): raise ValueError("Nonfinite four-bar path") maximum_marker_y = max(maximum_marker_y, marker.y) if (setup["target_x_m"][0] <= marker.x <= setup["target_x_m"][1] and setup["target_y_m"][0] <= marker.y <= setup["target_y_m"][1] and target_time is None): target_time = (i + 1) * dt at_a = on_coupler(pivot0) crank_tip = crank.TransformPointLocalToParent(ch.ChVector3d( crank_length / 2, 0, 0)) at_b = on_coupler(pivot1) rocker_tip = rocker.TransformPointLocalToParent(ch.ChVector3d( rocker_length / 2, 0, 0)) maximum_joint_error = max( maximum_joint_error, math.hypot(at_a.x - crank_tip.x, at_a.y - crank_tip.y), math.hypot(at_b.x - rocker_tip.x, at_b.y - rocker_tip.y)) return { "target_reached_s": target_time, "maximum_marker_y_m": maximum_marker_y, "motor_rotation_rad": motor.GetMotorAngle(), "maximum_joint_closure_error_m": maximum_joint_error, } 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, check=False, ) 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["properties"], 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, }) results[name] = { "step_properties": properties, "simulation_result": invoke(args.physics_python, "dynamics", { "properties": properties, "setup": setup, }), } before = results["before"] after = results["after"] bp = before["step_properties"] ap = after["step_properties"] bs = before["simulation_result"] gs = after["simulation_result"] checks = { "baseline_misses_target": bs["target_reached_s"] is None, "tool_reaches_target": gs["target_reached_s"] is not None and gs["target_reached_s"] <= setup["maximum_target_time_s"], "motor_completes_cycle": min(bs["motor_rotation_rad"], gs["motor_rotation_rad"]) >= setup["minimum_motor_rotation_rad"], "joints_stay_closed": max(bs["maximum_joint_closure_error_m"], gs["maximum_joint_closure_error_m"]) <= setup["maximum_joint_closure_error_m"], "mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) <= setup["maximum_relative_mass_change"], "envelope_fixed": all(abs(a - b) <= setup["maximum_envelope_change_mm"] for a, b in zip(ap["bounds_mm"], bp["bounds_mm"])), "pivot_centers_fixed": all( math.hypot(a[0] - b[0], a[1] - b[1]) <= setup["maximum_pivot_center_shift_mm"] for a, b in zip(ap["pivot_centers_mm"], bp["pivot_centers_mm"])), "pivot_bores_clear": ap["pivot_bore_intrusion_mm3"] <= setup["maximum_pivot_bore_intrusion_mm3"], } after["comparison_to_before"] = {"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"Tool target time: {bs['target_reached_s']} -> {gs['target_reached_s']} s") print(f"Task passed: {after['comparison_to_before']['passed']}") if not after["comparison_to_before"]["passed"]: raise SystemExit(1) if __name__ == "__main__": main()