Download tasks/015/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 9.81 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/015/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/015/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/015/simulate.py
9.81 kB
| """Index a STEP-derived wheel tooth past a radial pawl in both directions.""" | |
| 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("Wheel volume must be positive") | |
| bounds = shape.BoundingBox() | |
| inertia = props.MatrixOfInertia() | |
| density = setup["material_density_kg_m3"] | |
| disk = cq.Solid.makeCylinder(100, 20, cq.Vector(0, 0, -10)) | |
| bore = cq.Solid.makeCylinder(10, 20, cq.Vector(0, 0, -10)) | |
| envelope = cq.Solid.makeCylinder(130, 20, cq.Vector(0, 0, -10)) | |
| tooth_vertices = [[v.X, v.Y, v.Z] for v in shape.Vertices() | |
| if v.Y >= 94 and abs(v.X) <= 80] | |
| if len(tooth_vertices) < 8: | |
| raise ValueError("Wheel needs a STEP-resolved indexing tooth") | |
| tip = max(tooth_vertices, key=lambda v: v[0] ** 2 + v[1] ** 2) | |
| if math.hypot(tip[0], tip[1]) < 110: | |
| raise ValueError("Indexing tooth must extend beyond the base disk") | |
| 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(), | |
| "base_missing_mm3": disk.cut(bore).cut(shape).Volume(), | |
| "bore_intrusion_mm3": shape.intersect(bore).Volume(), | |
| "tip_angle_rad": math.atan2(tip[1], tip[0]), | |
| "tooth_collision_vertices_mm": tooth_vertices, | |
| } | |
| def dynamics(properties: dict, setup: dict) -> dict: | |
| import pychrono as ch | |
| ch.ChCollisionModel.SetDefaultSuggestedEnvelope(1e-5) | |
| ch.ChCollisionModel.SetDefaultSuggestedMargin(1e-5) | |
| material = ch.ChContactMaterialNSC() | |
| material.SetFriction(setup["contact_friction"]) | |
| center = [value / 1000 for value in properties["center_of_mass_mm"]] | |
| 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 direction, name in ((1, "forward"), (-1, "reverse")): | |
| system = ch.ChSystemNSC() | |
| system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET) | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) | |
| ground = ch.ChBody() | |
| ground.SetFixed(True) | |
| system.Add(ground) | |
| wheel = ch.ChBody() | |
| wheel.SetMass(properties["mass_kg"]) | |
| inertia = ch.ChMatrix33d() | |
| inertia.SetMatr(properties["inertia_tensor_kg_m2"]) | |
| wheel.SetInertia(inertia) | |
| angle = (math.pi / 2 - direction * setup["initial_tip_gap_rad"] | |
| - properties["tip_angle_rad"]) | |
| wheel.SetRot(ch.QuatFromAngleAxis(angle, ch.VECT_Z)) | |
| wheel.SetPos(ch.ChVector3d( | |
| center[0] * math.cos(angle) - center[1] * math.sin(angle), | |
| center[0] * math.sin(angle) + center[1] * math.cos(angle), center[2])) | |
| base_points = ch.vector_ChVector3d() | |
| for i in range(64): | |
| theta = 2 * math.pi * i / 64 | |
| for z in (-0.01, 0.01): | |
| base_points.push_back(ch.ChVector3d( | |
| 0.1 * math.cos(theta) - center[0], | |
| 0.1 * math.sin(theta) - center[1], z - center[2])) | |
| tooth_points = ch.vector_ChVector3d() | |
| for x, y, z in properties["tooth_collision_vertices_mm"]: | |
| tooth_points.push_back(ch.ChVector3d( | |
| x / 1000 - center[0], y / 1000 - center[1], z / 1000 - center[2])) | |
| wheel.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, base_points)) | |
| wheel.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, tooth_points)) | |
| wheel.EnableCollision(True) | |
| system.Add(wheel) | |
| hinge = ch.ChLinkLockRevolute() | |
| hinge.Initialize(wheel, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) | |
| system.Add(hinge) | |
| radius = setup["pawl_radius_m"] | |
| reference_y = setup["pawl_reference_y_m"] | |
| pawl = ch.ChBodyEasySphere(radius, setup["pawl_density_kg_m3"], | |
| False, True, material) | |
| pawl.SetPos(ch.ChVector3d(0, reference_y, 0)) | |
| system.Add(pawl) | |
| guide = ch.ChLinkLockPrismatic() | |
| guide.Initialize(pawl, ground, ch.ChFramed( | |
| ch.ChVector3d(0, reference_y, 0), | |
| ch.QuatFromAngleAxis(-math.pi / 2, ch.VECT_X))) | |
| system.Add(guide) | |
| spring = ch.ChForce() | |
| pawl.AddForce(spring) | |
| spring.SetMode(ch.ChForce.FORCE) | |
| spring.SetDir(ch.ChVector3d(0, 1, 0)) | |
| drive = ch.ChForce() | |
| wheel.AddForce(drive) | |
| drive.SetMode(ch.ChForce.TORQUE) | |
| drive.SetDir(ch.ChVector3d(0, 0, 1)) | |
| drive.SetMforce(direction * setup["wheel_drive_torque_N_m"]) | |
| damping = ch.ChForce() | |
| wheel.AddForce(damping) | |
| damping.SetMode(ch.ChForce.TORQUE) | |
| damping.SetDir(ch.ChVector3d(0, 0, 1)) | |
| rotation = 0.0 | |
| peak_pawl_y = reference_y | |
| for _ in range(steps): | |
| spring.SetMforce(-setup["pawl_preload_N"] - | |
| setup["pawl_spring_stiffness_N_m"] * | |
| (pawl.GetPos().y - reference_y)) | |
| damping.SetMforce(-setup["wheel_viscous_damping_N_m_s_rad"] * | |
| wheel.GetAngVelParent().z) | |
| system.DoStepDynamics(dt) | |
| rotation += wheel.GetAngVelParent().z * dt | |
| peak_pawl_y = max(peak_pawl_y, pawl.GetPos().y) | |
| if not math.isfinite(rotation + peak_pawl_y): | |
| raise ValueError("Nonfinite ratchet trajectory") | |
| results[name] = {"rotation_rad": rotation, | |
| "peak_pawl_y_m": peak_pawl_y} | |
| 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_stalls_forward": abs(bs["forward"]["rotation_rad"]) | |
| <= setup["maximum_baseline_forward_rotation_rad"], | |
| "indexes_forward": gs["forward"]["rotation_rad"] | |
| >= setup["minimum_forward_rotation_rad"], | |
| "holds_reverse": abs(gs["reverse"]["rotation_rad"]) | |
| <= setup["maximum_reverse_rotation_rad"], | |
| "pawl_contact_observed": gs["forward"]["peak_pawl_y_m"] | |
| >= setup["minimum_pawl_lift_y_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_radius_limited": ap["external_added_mm3"] | |
| <= setup["maximum_external_added_mm3"], | |
| "base_disk_intact": ap["base_missing_mm3"] | |
| <= setup["maximum_base_missing_mm3"], | |
| "shaft_bore_clear": ap["bore_intrusion_mm3"] | |
| <= setup["maximum_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"Forward rotation: {bs['forward']['rotation_rad']} -> " | |
| f"{gs['forward']['rotation_rad']} rad") | |
| print(f"Reverse rotation: {gs['reverse']['rotation_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() | |