Download tasks/017/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 7.58 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/017/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/017/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/017/simulate.py
7.58 kB
| """Check ball containment under lateral vibration in a STEP-derived tray.""" | |
| 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 | |
| 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}") | |
| bounds = shape.BoundingBox() | |
| envelope = cq.Solid.makeBox(300, 100, 60, cq.Vector(-150, -100, -30)) | |
| floor = cq.Solid.makeBox(300, 20, 60, cq.Vector(-150, -100, -30)) | |
| mounts = [cq.Solid.makeBox(2.5, 80, 15, | |
| cq.Vector(x, -80, z)) | |
| for x in (-150, 147.5) for z in (-30, 15)] | |
| vertices, faces = shape.tessellate(1.0) | |
| if not vertices or not faces: | |
| raise ValueError("STEP tessellation has no triangles") | |
| return { | |
| "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), | |
| "volume_mm3": shape.Volume(), | |
| "mass_kg": shape.Volume() * setup["material_density_kg_m3"] * 1e-9, | |
| "bounds_mm": [bounds.xmin, bounds.xmax, bounds.ymin, bounds.ymax, | |
| bounds.zmin, bounds.zmax], | |
| "external_added_mm3": shape.cut(envelope).Volume(), | |
| "floor_missing_mm3": floor.cut(shape).Volume(), | |
| "mount_missing_mm3": sum(mount.cut(shape).Volume() for mount in mounts), | |
| "collision_vertices_m": [[v.x / 1000, v.y / 1000, v.z / 1000] | |
| for v in vertices], | |
| "collision_triangles": faces, | |
| } | |
| 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"]) | |
| material.SetRestitution(setup["contact_restitution"]) | |
| mesh = ch.ChTriangleMeshConnected() | |
| vertices = properties["collision_vertices_m"] | |
| for a, b, c in properties["collision_triangles"]: | |
| mesh.AddTriangle(ch.ChVector3d(*vertices[a]), ch.ChVector3d(*vertices[b]), | |
| ch.ChVector3d(*vertices[c])) | |
| 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") | |
| escape_times = [] | |
| maximum_excursions = [] | |
| for release_x in setup["release_x_m"]: | |
| system = ch.ChSystemNSC() | |
| system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET) | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 0)) | |
| tray = ch.ChBody() | |
| tray.SetFixed(True) | |
| tray.AddCollisionShape(ch.ChCollisionShapeTriangleMesh( | |
| material, mesh, True, False, 0)) | |
| tray.EnableCollision(True) | |
| system.Add(tray) | |
| ball = ch.ChBodyEasySphere(setup["ball_radius_m"], | |
| setup["ball_density_kg_m3"], False, True, material) | |
| ball.SetPos(ch.ChVector3d(release_x, setup["release_y_m"], 0)) | |
| system.Add(ball) | |
| planar = ch.ChLinkMateGeneric() | |
| planar.SetConstrainedCoords(False, False, True, False, False, False) | |
| planar.Initialize(ball, tray, ch.ChFramed( | |
| ch.ChVector3d(release_x, setup["release_y_m"], 0))) | |
| system.Add(planar) | |
| forcing = ch.ChForce() | |
| ball.AddForce(forcing) | |
| forcing.SetMode(ch.ChForce.FORCE) | |
| forcing.SetDir(ch.ChVector3d(1, 0, 0)) | |
| maximum_x = abs(release_x) | |
| escaped = None | |
| for i in range(steps): | |
| t = i * dt | |
| forcing.SetMforce(ball.GetMass() * setup["lateral_acceleration_m_s2"] * | |
| math.cos(2 * math.pi * | |
| setup["vibration_frequency_hz"] * t)) | |
| system.DoStepDynamics(dt) | |
| pos = ball.GetPos() | |
| if not math.isfinite(pos.x + pos.y): | |
| raise ValueError("Nonfinite ball trajectory") | |
| maximum_x = max(maximum_x, abs(pos.x)) | |
| if abs(pos.x) >= setup["escape_center_x_m"]: | |
| escaped = (i + 1) * dt | |
| break | |
| escape_times.append(escaped) | |
| maximum_excursions.append(maximum_x) | |
| return {"escape_times_s": escape_times, | |
| "escaped_count": sum(value is not None for value in escape_times), | |
| "maximum_center_excursions_m": maximum_excursions} | |
| 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_escapes": bs["escaped_count"] == len(setup["release_x_m"]), | |
| "all_releases_contained": gs["escaped_count"] == 0, | |
| "vibration_moves_ball": min(gs["maximum_center_excursions_m"]) | |
| >= setup["minimum_gold_ball_excursion_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"], | |
| "floor_intact": ap["floor_missing_mm3"] | |
| <= setup["maximum_floor_missing_mm3"], | |
| "mounting_strips_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"Escaped releases: {bs['escaped_count']} -> {gs['escaped_count']}") | |
| print(f"Task passed: {after['comparison_to_before']['passed']}") | |
| if not after["comparison_to_before"]["passed"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |