Download tasks/022/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 8.08 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/022/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/022/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/022/simulate.py
8.08 kB
| """Measure motor torque from an oblique load at a STEP-derived output bore.""" | |
| 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("Bell crank 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() | |
| if abs(cylinder.Radius() - 5) < 1e-5: | |
| holes.append([axis.X(), axis.Y()]) | |
| if len(holes) != 3: | |
| raise ValueError("Expected three 5 mm pin bores") | |
| pivot = min(holes, key=lambda p: math.hypot(p[0], p[1])) | |
| remaining = [p for p in holes if p is not pivot] | |
| input_bore = min(remaining, key=lambda p: math.hypot(p[0] - 80, p[1])) | |
| output_bore = next(p for p in remaining if p is not input_bore) | |
| bounds = shape.BoundingBox() | |
| inertia = props.MatrixOfInertia() | |
| density = setup["material_density_kg_m3"] | |
| fixed_bores = [cq.Solid.makeCylinder(5, 10, cq.Vector(x, y, -5)) | |
| for x, y in ((0, 0), (80, 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_center_mm": pivot, | |
| "input_bore_center_mm": input_bore, | |
| "output_bore_center_mm": output_bore, | |
| "fixed_bore_intrusion_mm3": sum(shape.intersect(bore).Volume() | |
| for bore in fixed_bores), | |
| } | |
| def dynamics(properties: dict, setup: dict) -> dict: | |
| import pychrono as ch | |
| system = ch.ChSystemNSC() | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) | |
| ground = ch.ChBody() | |
| ground.SetFixed(True) | |
| system.Add(ground) | |
| center = [value / 1000 for value in properties["center_of_mass_mm"]] | |
| pivot = [value / 1000 for value in properties["pivot_center_mm"]] | |
| crank = ch.ChBody() | |
| crank.SetMass(properties["mass_kg"]) | |
| inertia = ch.ChMatrix33d() | |
| inertia.SetMatr(properties["inertia_tensor_kg_m2"]) | |
| crank.SetInertia(inertia) | |
| crank.SetPos(ch.ChVector3d(center[0] - pivot[0], | |
| center[1] - pivot[1], center[2])) | |
| system.Add(crank) | |
| motor = ch.ChLinkMotorRotationSpeed() | |
| motor.Initialize(crank, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) | |
| motor.SetSpeedFunction(ch.ChFunctionConst(setup["motor_speed_rad_s"])) | |
| system.Add(motor) | |
| output = properties["output_bore_center_mm"] | |
| load = ch.ChForce() | |
| crank.AddForce(load) | |
| load.SetMode(ch.ChForce.FORCE) | |
| load.SetRelDir(ch.ChVector3d(*setup["load_direction_local_xy"], 0)) | |
| load.SetVrelpoint(ch.ChVector3d( | |
| output[0] / 1000 - center[0], output[1] / 1000 - center[1], -center[2])) | |
| load.SetMforce(setup["load_force_N"]) | |
| 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") | |
| torques = [] | |
| for i in range(steps): | |
| system.DoStepDynamics(dt) | |
| if (i + 1) * dt >= setup["startup_exclusion_s"]: | |
| torques.append(abs(motor.GetMotorTorque())) | |
| if not torques or not all(math.isfinite(value) for value in torques): | |
| raise ValueError("Nonfinite or empty motor torque trace") | |
| input_bore = properties["input_bore_center_mm"] | |
| arm = math.hypot(input_bore[0] - properties["pivot_center_mm"][0], | |
| input_bore[1] - properties["pivot_center_mm"][1]) / 1000 | |
| return { | |
| "steady_peak_motor_torque_N_m": max(torques), | |
| "steady_mean_motor_torque_N_m": sum(torques) / len(torques), | |
| "equivalent_input_force_N": max(torques) / arm, | |
| "motor_rotation_rad": motor.GetMotorAngle(), | |
| } | |
| 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"] | |
| baseline = bs["steady_peak_motor_torque_N_m"] | |
| candidate = gs["steady_peak_motor_torque_N_m"] | |
| checks = { | |
| "baseline_torque_measurable": baseline | |
| >= setup["minimum_baseline_motor_torque_N_m"], | |
| "motor_torque_reduced": candidate <= baseline * | |
| (1 - setup["required_relative_motor_torque_reduction"]), | |
| "motor_speed_held": all( | |
| setup["minimum_motor_rotation_rad"] <= result["motor_rotation_rad"] | |
| <= setup["maximum_motor_rotation_rad"] for result in (bs, gs)), | |
| "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_bore_centers": all( | |
| math.hypot(ap[key][0] - bp[key][0], ap[key][1] - bp[key][1]) | |
| <= setup["maximum_fixed_bore_shift_mm"] | |
| for key in ("pivot_center_mm", "input_bore_center_mm")), | |
| "fixed_bores_clear": ap["fixed_bore_intrusion_mm3"] | |
| <= setup["maximum_fixed_bore_intrusion_mm3"], | |
| } | |
| after["comparison_to_before"] = { | |
| "relative_motor_torque_reduction": 1 - candidate / baseline, | |
| "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"Steady peak motor torque: {baseline} -> {candidate} N m") | |
| print(f"Task passed: {after['comparison_to_before']['passed']}") | |
| if not after["comparison_to_before"]["passed"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |