PhyCAD-Bench / tasks /006 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
6.85 kB
"""Measure rotor tilt after a torque pulse on a free spherical gimbal."""
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("Rotor volume must be positive")
bounds = shape.BoundingBox()
inertia = props.MatrixOfInertia()
density = setup["material_density_kg_m3"]
half_length = setup["half_length_mm"]
shaft = cq.Solid.makeCylinder(setup["shaft_radius_mm"], 2 * half_length,
cq.Vector(0, 0, -half_length))
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],
"shaft_interface_missing_mm3": shaft.cut(shape).Volume(),
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
system = ch.ChSystemNSC()
system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
ground = ch.ChBody()
ground.SetFixed(True)
system.Add(ground)
rotor = ch.ChBody()
rotor.SetMass(properties["mass_kg"])
inertia = ch.ChMatrix33d()
inertia.SetMatr(properties["inertia_tensor_kg_m2"])
rotor.SetInertia(inertia)
rotor.SetAngVelParent(ch.ChVector3d(0, 0, setup["initial_spin_rad_s"]))
system.Add(rotor)
gimbal = ch.ChLinkLockSpherical()
gimbal.Initialize(rotor, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0)))
system.Add(gimbal)
torque = ch.ChForce()
rotor.AddForce(torque)
torque.SetMode(ch.ChForce.TORQUE)
torque.SetAlign(ch.ChForce.WORLD_DIR)
torque.SetDir(ch.ChVector3d(1, 0, 0))
torque.SetMforce(setup["pulse_torque_N_m"])
dt = setup["time_step_s"]
steps = round(setup["duration_s"] / dt)
pulse_steps = round(setup["pulse_duration_s"] / dt)
if dt <= 0 or steps <= pulse_steps or abs(steps * dt - setup["duration_s"]) > 1e-12:
raise ValueError("Invalid simulation duration or time step")
tilt_squared = 0.0
peak = 0.0
count = 0
for i in range(steps):
if i == pulse_steps:
torque.SetMforce(0)
system.DoStepDynamics(dt)
if i < pulse_steps:
continue
axis = rotor.GetRot().Rotate(ch.ChVector3d(0, 0, 1))
tilt = math.acos(max(-1.0, min(1.0, axis.z)))
if not math.isfinite(tilt):
raise ValueError("Nonfinite rotor tilt")
tilt_squared += tilt * tilt
peak = max(peak, tilt)
count += 1
return {
"post_pulse_rms_tilt_deg": math.degrees(math.sqrt(tilt_squared / count)),
"post_pulse_peak_tilt_deg": math.degrees(peak),
"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[-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"]
baseline = before["simulation_result"]["post_pulse_rms_tilt_deg"]
candidate = after["simulation_result"]["post_pulse_rms_tilt_deg"]
envelope = [-setup["outer_radius_mm"], setup["outer_radius_mm"],
-setup["outer_radius_mm"], setup["outer_radius_mm"],
-setup["half_length_mm"], setup["half_length_mm"]]
checks = {
"baseline_tilt_measurable": baseline > 0.1,
"rms_tilt_reduced": candidate <= baseline *
(1 - setup["required_relative_rms_tilt_reduction"]),
"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"], envelope)),
"shaft_interface_intact": ap["shaft_interface_missing_mm3"]
<= setup["maximum_interface_missing_mm3"],
"centered": max(abs(value) for value in ap["center_of_mass_mm"])
<= setup["maximum_center_offset_mm"],
"principal_spin_axis": all(abs(ap["inertia_tensor_kg_m2"][i][2])
<= setup["maximum_cross_inertia_kg_m2"]
for i in (0, 1)),
}
after["comparison_to_before"] = {
"relative_rms_tilt_reduction": 1 - candidate / baseline,
"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"Post-pulse RMS tilt: {baseline:.4f} -> {candidate:.4f} deg")
print(f"Task passed: {after['comparison_to_before']['passed']}")
if not after["comparison_to_before"]["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()