"""Test holding and release torque of a CAD-derived over-center clamp.""" 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("Lever 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())) fixed = sorted([[x, y] for radius, x, y in holes if abs(radius - 5) < 1e-5]) spring_pins = [[x, y] for radius, x, y in holes if abs(radius - 3) < 1e-5] if len(fixed) != 2 or len(spring_pins) != 1: raise ValueError("Expected two 5 mm fixed bores and one 3 mm spring pin 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), (80, 0))] anchor_x, anchor_y = setup["spring_anchor_m"] pin_x, pin_y = (spring_pins[0][0] / 1000, spring_pins[0][1] / 1000) overcenter_angle = (math.atan2(anchor_y, anchor_x) - math.atan2(pin_y, pin_x)) margin = math.radians(setup["closed_angle_deg"]) - overcenter_angle 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], "fixed_pin_centers_mm": fixed, "spring_pin_center_mm": spring_pins[0], "overcenter_margin_rad": margin, "fixed_bore_intrusion_mm3": sum(shape.intersect(bore).Volume() for bore in bores), } def dynamics(properties: dict, setup: dict) -> dict: import pychrono as ch center = [value / 1000 for value in properties["center_of_mass_mm"]] pin = [(properties["spring_pin_center_mm"][i] / 1000 - center[i]) for i in (0, 1)] closed = math.radians(setup["closed_angle_deg"]) anchor_x, anchor_y = setup["spring_anchor_m"] 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") results = {} for release, name in ((False, "hold"), (True, "release")): system = ch.ChSystemNSC() system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) lever = ch.ChBody() lever.SetMass(properties["mass_kg"]) inertia = ch.ChMatrix33d() inertia.SetMatr(properties["inertia_tensor_kg_m2"]) lever.SetInertia(inertia) lever.SetRot(ch.QuatFromAngleAxis(closed, ch.VECT_Z)) lever.SetPos(ch.ChVector3d( center[0] * math.cos(closed) - center[1] * math.sin(closed), center[0] * math.sin(closed) + center[1] * math.cos(closed), center[2])) system.Add(lever) hinge = ch.ChLinkLockRevolute() hinge.Initialize(lever, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) system.Add(hinge) spring = ch.ChForce() lever.AddForce(spring) spring.SetMode(ch.ChForce.FORCE) spring.SetMforce(setup["spring_force_N"]) load = ch.ChForce() lever.AddForce(load) load.SetMode(ch.ChForce.TORQUE) load.SetDir(ch.ChVector3d(0, 0, 1)) stop = ch.ChForce() lever.AddForce(stop) stop.SetMode(ch.ChForce.TORQUE) stop.SetDir(ch.ChVector3d(0, 0, 1)) angle = closed minimum_angle = closed maximum_reaction = 0.0 for i in range(steps): pin_world = lever.TransformPointLocalToParent(ch.ChVector3d( pin[0], pin[1], -center[2])) dx, dy = pin_world.x - anchor_x, pin_world.y - anchor_y distance = math.hypot(dx, dy) if distance <= 1e-6: raise ValueError("Spring pin coincides with fixed spring anchor") spring.SetVpoint(pin_world) spring.SetDir(ch.ChVector3d(dx / distance, dy / distance, 0)) pulse = (setup["release_pulse_torque_N_m"] if release and i * dt < setup["release_pulse_s"] else 0) load.SetMforce(-setup["opening_load_torque_N_m"] - pulse) stop.SetMforce(-setup["stop_stiffness_N_m_rad"] * max(0, angle - closed) - setup["stop_damping_N_m_s_rad"] * lever.GetAngVelParent().z) system.DoStepDynamics(dt) angle += lever.GetAngVelParent().z * dt minimum_angle = min(minimum_angle, angle) reaction = hinge.GetReaction1().force maximum_reaction = max(maximum_reaction, math.hypot(reaction.x, reaction.y)) if not math.isfinite(angle + maximum_reaction): raise ValueError("Nonfinite clamp trajectory") results[name] = {"minimum_angle_rad": minimum_angle, "end_angle_rad": angle, "maximum_pivot_reaction_N": maximum_reaction} 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, 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_opens_under_load": bs["hold"]["minimum_angle_rad"] <= setup["maximum_baseline_held_angle_rad"], "closed_position_held": gs["hold"]["minimum_angle_rad"] >= setup["minimum_held_angle_rad"], "release_travel_kept": gs["release"]["end_angle_rad"] <= setup["maximum_released_angle_rad"], "overcenter_margin": ap["overcenter_margin_rad"] >= setup["minimum_overcenter_margin_rad"], "pivot_reaction_limited": max( result["maximum_pivot_reaction_N"] for result in gs.values()) <= setup["maximum_pivot_reaction_N"], "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"])), "fixed_pins_intact": all(math.hypot(a[0] - b[0], a[1] - b[1]) <= setup["maximum_fixed_pin_shift_mm"] for a, b in zip(ap["fixed_pin_centers_mm"], bp["fixed_pin_centers_mm"])), "fixed_bores_clear": ap["fixed_bore_intrusion_mm3"] <= setup["maximum_fixed_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"Minimum hold angle: {bs['hold']['minimum_angle_rad']} -> " f"{gs['hold']['minimum_angle_rad']} rad") print(f"Gold release end angle: {gs['release']['end_angle_rad']} rad") print(f"Task passed: {after['comparison_to_before']['passed']}") if not after["comparison_to_before"]["passed"]: raise SystemExit(1) if __name__ == "__main__": main()