Download tasks/014/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 8.76 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/014/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/014/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/014/simulate.py
8.76 kB
| """Push and retract a STEP-derived wedge under a guided spring follower.""" | |
| 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 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("Wedge volume must be positive") | |
| bounds = shape.BoundingBox() | |
| inertia = props.MatrixOfInertia() | |
| density = setup["material_density_kg_m3"] | |
| envelope = cq.Solid.makeBox(500, 100, 50, cq.Vector(-250, 0, -25)) | |
| mount = cq.Solid.makeBox(10, 10, 50, cq.Vector(-250, 0, -25)) | |
| 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], | |
| "external_added_mm3": shape.cut(envelope).Volume(), | |
| "mount_missing_mm3": mount.cut(shape).Volume(), | |
| "collision_vertices_mm": [[v.X, v.Y, v.Z] for v in shape.Vertices()], | |
| } | |
| def dynamics(properties: dict, setup: dict) -> dict: | |
| import pychrono as ch | |
| ch.ChCollisionModel.SetDefaultSuggestedEnvelope(1e-5) | |
| ch.ChCollisionModel.SetDefaultSuggestedMargin(1e-5) | |
| system = ch.ChSystemNSC() | |
| system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET) | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 0)) | |
| material = ch.ChContactMaterialNSC() | |
| material.SetFriction(setup["contact_friction"]) | |
| ground = ch.ChBody() | |
| ground.SetFixed(True) | |
| system.Add(ground) | |
| radius = setup["follower_radius_m"] | |
| follower_mass = setup["follower_mass_kg"] | |
| follower = ch.ChBodyEasySphere( | |
| radius, follower_mass / (4 * math.pi * radius ** 3 / 3), | |
| False, True, material) | |
| reference_height = setup["follower_reference_height_m"] | |
| follower.SetPos(ch.ChVector3d(0, reference_height, 0)) | |
| system.Add(follower) | |
| follower_guide = ch.ChLinkLockPrismatic() | |
| follower_guide.Initialize(follower, ground, ch.ChFramed( | |
| ch.ChVector3d(0, reference_height, 0), | |
| ch.QuatFromAngleAxis(-math.pi / 2, ch.VECT_X))) | |
| system.Add(follower_guide) | |
| spring = ch.ChForce() | |
| follower.AddForce(spring) | |
| spring.SetMode(ch.ChForce.FORCE) | |
| spring.SetDir(ch.ChVector3d(0, 1, 0)) | |
| center = [value / 1000 for value in properties["center_of_mass_mm"]] | |
| origin = setup["wedge_initial_cad_origin_m"] | |
| wedge = ch.ChBody() | |
| wedge.SetMass(properties["mass_kg"]) | |
| inertia = ch.ChMatrix33d() | |
| inertia.SetMatr(properties["inertia_tensor_kg_m2"]) | |
| wedge.SetInertia(inertia) | |
| wedge.SetPos(ch.ChVector3d(*(origin[i] + center[i] for i in range(3)))) | |
| points = ch.vector_ChVector3d() | |
| for x, y, z in properties["collision_vertices_mm"]: | |
| points.push_back(ch.ChVector3d(x / 1000 - center[0], | |
| y / 1000 - center[1], | |
| z / 1000 - center[2])) | |
| wedge.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, points)) | |
| wedge.EnableCollision(True) | |
| system.Add(wedge) | |
| wedge_guide = ch.ChLinkLockPrismatic() | |
| wedge_guide.Initialize(wedge, ground, ch.ChFramed( | |
| ch.ChVector3d(*origin), ch.QuatFromAngleAxis(math.pi / 2, ch.VECT_Y))) | |
| system.Add(wedge_guide) | |
| push = ch.ChForce() | |
| wedge.AddForce(push) | |
| push.SetMode(ch.ChForce.FORCE) | |
| push.SetDir(ch.ChVector3d(1, 0, 0)) | |
| 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") | |
| peak_height = reference_height | |
| peak_wedge_x = origin[0] | |
| first_lift_s = None | |
| for i in range(steps): | |
| t = i * dt | |
| spring.SetMforce(follower_mass * setup["gravity_m_s2"] - | |
| setup["follower_spring_stiffness_N_m"] * | |
| (follower.GetPos().y - reference_height)) | |
| push.SetMforce(setup["push_force_N"] if t < setup["push_duration_s"] | |
| else -setup["reverse_force_N"]) | |
| system.DoStepDynamics(dt) | |
| height = follower.GetPos().y | |
| cad_x = wedge.GetPos().x - center[0] | |
| if not math.isfinite(height + cad_x): | |
| raise ValueError("Nonfinite wedge or follower trajectory") | |
| if t < setup["push_duration_s"]: | |
| peak_height = max(peak_height, height) | |
| peak_wedge_x = max(peak_wedge_x, cad_x) | |
| if height >= setup["target_follower_height_m"] and first_lift_s is None: | |
| first_lift_s = (i + 1) * dt | |
| return { | |
| "peak_push_follower_height_m": peak_height, | |
| "peak_push_wedge_cad_origin_x_m": peak_wedge_x, | |
| "first_target_lift_s": first_lift_s, | |
| "returned_follower_height_m": follower.GetPos().y, | |
| "retracted_wedge_cad_origin_x_m": wedge.GetPos().x - center[0], | |
| } | |
| 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_below_target": bs["first_target_lift_s"] is None, | |
| "target_lift_reached": gs["first_target_lift_s"] is not None, | |
| "lift_gain": gs["peak_push_follower_height_m"] - | |
| bs["peak_push_follower_height_m"] >= setup["minimum_lift_gain_m"], | |
| "wedge_retracted": gs["retracted_wedge_cad_origin_x_m"] | |
| <= setup["maximum_retracted_wedge_x_m"], | |
| "follower_returned": gs["returned_follower_height_m"] | |
| <= setup["maximum_returned_follower_height_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"])), | |
| "outer_envelope_kept": ap["external_added_mm3"] | |
| <= setup["maximum_external_added_mm3"], | |
| "mounting_foot_intact": ap["mount_missing_mm3"] | |
| <= setup["maximum_mount_missing_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"Peak follower height: {bs['peak_push_follower_height_m']} -> " | |
| f"{gs['peak_push_follower_height_m']} m") | |
| print(f"Task passed: {after['comparison_to_before']['passed']}") | |
| if not after["comparison_to_before"]["passed"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |