"""Map STEP mass properties into a two-joint robot arm torque test.""" 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.BRepGProp import BRepGProp from OCP.GProp import GProp_GProps 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 industrial arm link") holes = [] for face in shape.Faces(): if face.geomType() != "CYLINDER": continue bounds = face.BoundingBox() if (abs(face.Area() - 2 * math.pi * 10 * 20) < 1e-3 and abs(bounds.zmin + 10) < 1e-5 and abs(bounds.zmax - 10) < 1e-5): holes.append(face.Center().x) holes.sort() if len(holes) != 2: raise ValueError("Expected two 10 mm radius through bores") pads = [] for x in (0, 300): pad = cq.Solid.makeBox(40, 50, 20, cq.Vector(x - 20, -25, -10)) bore = cq.Solid.makeCylinder(10, 20, cq.Vector(x, 0, -10), cq.Vector(0, 0, 1)) pads.append(pad.cut(bore)) envelope = cq.Solid.makeBox(340, 80, 20, cq.Vector(-20, -40, -10)) props = GProp_GProps() BRepGProp.VolumeProperties_s(shape.wrapped, props) density = setup["link_density_kg_m3"] inertia = props.MatrixOfInertia() return { "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), "volume_mm3": props.Mass(), "mass_kg": props.Mass() * density * 1e-9, "center_of_mass_m": [value / 1000 for value in 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)], "joint_bore_x_mm": holes, "joint_pad_missing_mm3": sum(max(0.0, pad.Volume() - pad.intersect(shape).Volume()) for pad in pads), "envelope_excess_mm3": max(0.0, shape.Volume() - shape.intersect(envelope).Volume()), } def dynamics(properties: dict, setup: dict) -> dict: import pychrono as ch results = {} for frequency in setup["trajectory_frequencies_Hz"]: system = ch.ChSystemSMC() system.SetGravitationalAcceleration( ch.ChVector3d(0, -setup["gravity_m_s2"], 0)) system.SetSolver(ch.ChSolverSparseLU()) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) proximal = ch.ChBody() proximal.SetMass(properties["mass_kg"]) inertia = ch.ChMatrix33d() inertia.SetMatr(properties["inertia_tensor_kg_m2"]) proximal.SetInertia(inertia) proximal.SetPos(ch.ChVector3d(*properties["center_of_mass_m"])) system.Add(proximal) distal = ch.ChBody() distal.SetMass(setup["distal_assembly_and_payload_mass_kg"]) distal.SetInertiaXX(ch.ChVector3d( *setup["distal_assembly_inertia_kg_m2"])) distal.SetPos(ch.ChVector3d( setup["distal_assembly_center_x_m"], 0, 0)) system.Add(distal) shoulder = ch.ChLinkMotorRotationAngle() shoulder.SetSpindleConstraint( ch.ChLinkMotorRotation.SpindleConstraint_REVOLUTE) shoulder.Initialize(proximal, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) shoulder.SetAngleFunction(ch.ChFunctionSine( setup["shoulder_sine_amplitude_rad"], frequency, -math.pi / 2, setup["shoulder_sine_shift_rad"])) system.Add(shoulder) elbow = ch.ChLinkMotorRotationAngle() elbow.SetSpindleConstraint( ch.ChLinkMotorRotation.SpindleConstraint_REVOLUTE) elbow.Initialize(distal, proximal, ch.ChFramed( ch.ChVector3d(setup["elbow_position_m"], 0, 0))) elbow.SetAngleFunction(ch.ChFunctionSine( setup["elbow_sine_amplitude_rad"], frequency, -math.pi / 2, setup["elbow_sine_shift_rad"])) system.Add(elbow) 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 arm trajectory grid") peak_shoulder_torque = 0.0 peak_elbow_torque = 0.0 for index in range(steps): system.DoStepDynamics(dt) if (index + 1) * dt >= setup["ignore_initial_torque_s"]: peak_shoulder_torque = max( peak_shoulder_torque, abs(shoulder.GetMotorTorque())) peak_elbow_torque = max( peak_elbow_torque, abs(elbow.GetMotorTorque())) if not all(math.isfinite(value) for value in ( peak_shoulder_torque, peak_elbow_torque)): raise ValueError("Non-finite arm motor torque") results[str(frequency)] = { "peak_shoulder_motor_torque_N_m": peak_shoulder_torque, "peak_elbow_motor_torque_N_m": peak_elbow_torque, "final_shoulder_angle_rad": shoulder.GetMotorAngle(), "final_elbow_angle_rad": elbow.GetMotorAngle(), } 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["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, after = results["before"], results["after"] bp, ap = before["step_properties"], after["step_properties"] bs, gs = before["simulation_result"], after["simulation_result"] cases = [str(frequency) for frequency in setup["trajectory_frequencies_Hz"]] baseline = [bs[case]["peak_shoulder_motor_torque_N_m"] for case in cases] candidate = [gs[case]["peak_shoulder_motor_torque_N_m"] for case in cases] reductions = [1 - a / b for a, b in zip(candidate, baseline)] checks = { "shoulder_torque_reduced_both_trajectories": min(reductions) >= setup["required_relative_peak_torque_reduction"], "candidate_torque_limit": max(candidate) <= setup["maximum_candidate_peak_torque_N_m"], "mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) <= setup["maximum_relative_mass_change"], "joint_pads_fixed": ap["joint_pad_missing_mm3"] <= setup["maximum_joint_pad_missing_mm3"], "joint_bores_fixed": max(abs(a - b) for a, b in zip( ap["joint_bore_x_mm"], bp["joint_bore_x_mm"])) <= setup["maximum_joint_bore_center_error_mm"], "envelope_fixed": ap["envelope_excess_mm3"] <= setup["maximum_envelope_excess_mm3"], } after["comparison_to_before"] = { "relative_shoulder_torque_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"Peak shoulder torque: {baseline} -> {candidate} N m") print(f"Task passed: {all(checks.values())}") if not all(checks.values()): raise SystemExit(1) if __name__ == "__main__": main()