Download tasks/004/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 6.41 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/004/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/004/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/004/simulate.py
6.41 kB
| """Measure both STEP pendulums and time their swings in PyChrono.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| import statistics | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent | |
| def measure(step: Path, density: float) -> 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(): | |
| raise ValueError(f"Expected one valid solid: {step}") | |
| props = GProp_GProps() | |
| BRepGProp.VolumeProperties_s(shape.wrapped, props) | |
| box = shape.BoundingBox() | |
| inertia = props.MatrixOfInertia() | |
| return { | |
| "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), | |
| "volume_mm3": props.Mass(), | |
| "mass_kg": props.Mass() * density * 1e-9, | |
| "overall_length_mm": box.ylen, | |
| "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) | |
| ], | |
| } | |
| def dynamics(p: dict, setup: dict) -> dict: | |
| import pychrono as ch | |
| cx, cy, cz = [v / 1000 for v in p["center_of_mass_mm"]] | |
| if abs(cx) > 1e-6 or abs(cz) > 1e-6 or cy >= 0: | |
| raise ValueError("Pendulum center of mass must be below the upper pivot") | |
| if setup["pivot_mm"] != [0.0, 0.0, 0.0]: | |
| raise ValueError("This task expects its pivot at the STEP origin") | |
| angle = math.radians(setup["initial_angle_deg"]) | |
| system = ch.ChSystemNSC() | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 0)) | |
| anchor = ch.ChBody() | |
| anchor.SetFixed(True) | |
| system.Add(anchor) | |
| pendulum = ch.ChBody() | |
| pendulum.SetMass(p["mass_kg"]) | |
| inertia = ch.ChMatrix33d() | |
| inertia.SetMatr(p["inertia_tensor_kg_m2"]) | |
| pendulum.SetInertia(inertia) | |
| pendulum.SetRot(ch.QuatFromAngleAxis(angle, ch.VECT_Z)) | |
| pendulum.SetPos(ch.ChVector3d( | |
| cx * math.cos(angle) - cy * math.sin(angle), | |
| cx * math.sin(angle) + cy * math.cos(angle), cz, | |
| )) | |
| system.Add(pendulum) | |
| hinge = ch.ChLinkLockRevolute() | |
| hinge.Initialize(pendulum, anchor, ch.ChFramed(ch.ChVector3d(0, 0, 0))) | |
| system.Add(hinge) | |
| 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("Duration must contain whole time steps") | |
| crossings = [] | |
| previous = angle | |
| for i in range(1, steps + 1): | |
| system.DoStepDynamics(dt) | |
| q = pendulum.GetRot() | |
| current = 2 * math.atan2(q.e3, q.e0) | |
| if previous > 0 and current <= 0: | |
| crossings.append((i - 1 + previous / (previous - current)) * dt) | |
| previous = current | |
| if len(crossings) < 3: | |
| raise ValueError("Too few swings to measure a period") | |
| periods = [b - a for a, b in zip(crossings, crossings[1:])] | |
| mass = p["mass_kg"] | |
| distance = -cy | |
| izz_about_pivot = p["inertia_tensor_kg_m2"][2][2] + mass * distance**2 | |
| analytic = 2 * math.pi * math.sqrt( | |
| izz_about_pivot / (mass * setup["gravity_m_s2"] * distance) | |
| ) | |
| return { | |
| "mean_period_s": statistics.mean(periods), | |
| "measured_periods_s": periods, | |
| "zero_crossings_s": crossings, | |
| "small_angle_analytic_period_s": analytic, | |
| "steps": steps, | |
| } | |
| 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}") | |
| 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) | |
| print(json.dumps( | |
| measure(Path(payload["step"]), payload["density"]) | |
| if args.phase == "measure" | |
| else dynamics(payload["properties"], payload["setup"]) | |
| )) | |
| return | |
| setup_path = ROOT / "setup.json" | |
| setup = json.loads(setup_path.read_text()) | |
| hashes = { | |
| "setup_sha256": hashlib.sha256(setup_path.read_bytes()).hexdigest(), | |
| "simulation_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), | |
| "engine": setup["engine"], | |
| "engine_version": setup["engine_version"], | |
| } | |
| results = {} | |
| for name in ("before", "after"): | |
| step = ROOT / f"{name}.step" | |
| p = invoke(args.cad_python, "measure", { | |
| "step": str(step), "density": setup["material_density_kg_m3"], | |
| }) | |
| results[name] = { | |
| "step": step.name, "setup": "setup.json", "simulation": "simulate.py", | |
| "step_properties": p, | |
| "simulation_result": invoke(args.physics_python, "dynamics", { | |
| "properties": p, "setup": setup, | |
| }), | |
| "provenance": hashes, | |
| } | |
| b, a = results["before"], results["after"] | |
| bp, ap = b["step_properties"], a["step_properties"] | |
| bt = b["simulation_result"]["mean_period_s"] | |
| at = a["simulation_result"]["mean_period_s"] | |
| reduction = 1 - at / bt | |
| checks = { | |
| "period_reduction": reduction >= setup["required_relative_period_reduction"], | |
| "mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) | |
| <= setup["maximum_relative_mass_change"], | |
| "length_fixed": abs(ap["overall_length_mm"] - bp["overall_length_mm"]) | |
| <= setup["maximum_length_change_mm"], | |
| } | |
| a["comparison_to_before"] = { | |
| "relative_period_reduction": reduction, | |
| "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"Swing period: {bt:.6f} -> {at:.6f} s ({reduction:.1%} shorter)") | |
| print(f"Task passed: {a['comparison_to_before']['passed']}") | |
| if not a["comparison_to_before"]["passed"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |