Download tasks/043/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/043/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/043/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/043/simulate.py
7.97 kB
| """Map STEP rocker bores to a sprung body-roll experiment.""" | |
| 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 len(shape.Solids()) != 1 or not shape.isValid(): | |
| raise ValueError("Expected one valid suspension rocker solid") | |
| holes = [] | |
| expected_area = 2 * math.pi * 5 * 10 | |
| for face in shape.Faces(): | |
| if face.geomType() != "CYLINDER": | |
| continue | |
| bounds = face.BoundingBox() | |
| if (abs(face.Area() - expected_area) < 1e-3 and | |
| abs(bounds.zmin) < 1e-5 and abs(bounds.zmax - 10) < 1e-5): | |
| holes.append(face.Center().x) | |
| holes.sort() | |
| if len(holes) != 3: | |
| raise ValueError("Expected exactly three through bores of radius 5 mm") | |
| envelope = cq.Solid.makeBox(140, 30, 10, cq.Vector(-20, -15, 0)) | |
| return { | |
| "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), | |
| "volume_mm3": shape.Volume(), | |
| "pivot_x_mm": holes[0], | |
| "spring_pickup_x_mm": holes[1], | |
| "wheel_pickup_x_mm": holes[2], | |
| "envelope_excess_mm3": max(0.0, shape.Volume() - | |
| shape.intersect(envelope).Volume()), | |
| } | |
| def dynamics(properties: dict, setup: dict) -> dict: | |
| import pychrono as ch | |
| spring_arm = (properties["spring_pickup_x_mm"] - | |
| properties["pivot_x_mm"]) / 1000 | |
| wheel_arm = (properties["wheel_pickup_x_mm"] - | |
| properties["pivot_x_mm"]) / 1000 | |
| if spring_arm <= 0 or wheel_arm <= 0: | |
| raise ValueError("Rocker arm lengths must be positive") | |
| ratio = spring_arm / wheel_arm | |
| half_track = setup["track_width_m"] / 2 | |
| roll_stiffness = (2 * setup["spring_stiffness_N_m"] * | |
| ratio ** 2 * half_track ** 2) | |
| roll_damping = (2 * setup["spring_damping_N_s_m"] * | |
| ratio ** 2 * half_track ** 2) | |
| results = {} | |
| for acceleration in setup["lateral_acceleration_pulses_m_s2"]: | |
| system = ch.ChSystemSMC() | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) | |
| system.SetSolver(ch.ChSolverSparseLU()) | |
| ground = ch.ChBody() | |
| ground.SetFixed(True) | |
| system.Add(ground) | |
| body = ch.ChBody() | |
| body.SetMass(setup["body_mass_kg"]) | |
| inertia = setup["body_roll_inertia_kg_m2"] | |
| body.SetInertiaXX(ch.ChVector3d(inertia, 1000, 1000)) | |
| system.Add(body) | |
| hinge = ch.ChLinkLockRevolute() | |
| hinge.Initialize(body, ground, ch.ChFramed( | |
| ch.ChVector3d(0, 0, 0), ch.QuatFromAngleY(math.pi / 2))) | |
| system.Add(hinge) | |
| torque = ch.ChForce() | |
| body.AddForce(torque) | |
| torque.SetMode(ch.ChForce.TORQUE) | |
| torque.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 time grid") | |
| peak = 0.0 | |
| for index in range(steps): | |
| time = index * dt | |
| rotation = body.GetRot() | |
| roll = 2 * math.atan2(rotation.e1, rotation.e0) | |
| roll_rate = body.GetAngVelParent().x | |
| if setup["pulse_start_s"] <= time <= ( | |
| setup["pulse_start_s"] + setup["pulse_duration_s"]): | |
| phase = (time - setup["pulse_start_s"]) / setup["pulse_duration_s"] | |
| lateral_acceleration = acceleration * math.sin(math.pi * phase) | |
| else: | |
| lateral_acceleration = 0.0 | |
| external = (setup["body_mass_kg"] * lateral_acceleration * | |
| setup["roll_moment_arm_m"]) | |
| torque.SetMforce(external - roll_stiffness * roll - | |
| roll_damping * roll_rate) | |
| system.DoStepDynamics(dt) | |
| peak = max(peak, abs(roll)) | |
| if not math.isfinite(peak): | |
| raise ValueError("Non-finite body-roll response") | |
| results[str(acceleration)] = { | |
| "peak_roll_rad": peak, | |
| "effective_roll_stiffness_N_m_rad": roll_stiffness, | |
| "effective_roll_damping_N_m_s_rad": roll_damping, | |
| "available_wheel_travel_m": ( | |
| setup["available_spring_stroke_m"] / ratio), | |
| "spring_to_wheel_lever_ratio": ratio, | |
| } | |
| 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) | |
| 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, after = results["before"], results["after"] | |
| bp, ap = before["step_properties"], after["step_properties"] | |
| bs, gs = before["simulation_result"], after["simulation_result"] | |
| cases = [str(value) for value in setup["lateral_acceleration_pulses_m_s2"]] | |
| baseline = [bs[case]["peak_roll_rad"] for case in cases] | |
| candidate = [gs[case]["peak_roll_rad"] for case in cases] | |
| reductions = [1 - a / b for a, b in zip(candidate, baseline)] | |
| checks = { | |
| "peak_roll_reduced_both_pulses": min(reductions) >= | |
| setup["required_relative_peak_roll_reduction"], | |
| "candidate_roll_limit": max(candidate) <= | |
| setup["maximum_candidate_peak_roll_rad"], | |
| "wheel_travel_retained": all(gs[case]["available_wheel_travel_m"] >= | |
| setup["required_wheel_travel_m"] | |
| for case in cases), | |
| "spring_pickup_range": setup["spring_pickup_min_mm"] <= | |
| ap["spring_pickup_x_mm"] <= setup["spring_pickup_max_mm"], | |
| "pivot_fixed": abs(ap["pivot_x_mm"] - bp["pivot_x_mm"]) <= | |
| setup["maximum_pivot_error_mm"], | |
| "wheel_pickup_fixed": abs(ap["wheel_pickup_x_mm"] - | |
| bp["wheel_pickup_x_mm"]) <= | |
| setup["maximum_wheel_pickup_error_mm"], | |
| "volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <= | |
| setup["maximum_relative_volume_change"], | |
| "envelope_fixed": ap["envelope_excess_mm3"] <= | |
| setup["maximum_envelope_excess_mm3"], | |
| } | |
| after["comparison_to_before"] = { | |
| "relative_peak_roll_reductions": reductions, | |
| "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 roll: {baseline} -> {candidate} rad") | |
| print(f"Task passed: {all(checks.values())}") | |
| if not all(checks.values()): | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |