PhyCAD-Bench / tasks /007 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
6.31 kB
"""Measure yaw caused by a fixed push through a STEP-derived chassis."""
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("Chassis volume must be positive")
bounds = shape.BoundingBox()
inertia = props.MatrixOfInertia()
density = setup["material_density_kg_m3"]
pad = cq.Solid.makeBox(5, 10, 10, cq.Vector(-50, -5, -5))
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],
"push_pad_missing_mm3": pad.cut(shape).Volume(),
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
center = [value / 1000 for value in properties["center_of_mass_mm"]]
system = ch.ChSystemNSC()
system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
chassis = ch.ChBody()
chassis.SetMass(properties["mass_kg"])
inertia = ch.ChMatrix33d()
inertia.SetMatr(properties["inertia_tensor_kg_m2"])
chassis.SetInertia(inertia)
chassis.SetPos(ch.ChVector3d(*center))
system.Add(chassis)
push = ch.ChForce()
chassis.AddForce(push)
push.SetMode(ch.ChForce.FORCE)
push.SetAlign(ch.ChForce.WORLD_DIR)
push.SetDir(ch.ChVector3d(1, 0, 0))
push.SetVrelpoint(ch.ChVector3d(*[
point / 1000 - coordinate
for point, coordinate in zip(setup["push_point_mm"], center)
]))
push.SetMforce(setup["push_force_N"])
dt = setup["time_step_s"]
steps = round(setup["duration_s"] / dt)
pulse_steps = round(setup["push_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")
for i in range(steps):
if i == pulse_steps:
push.SetMforce(0)
system.DoStepDynamics(dt)
q = chassis.GetRot()
yaw = math.degrees(2 * math.atan2(q.e3, q.e0))
if not math.isfinite(yaw):
raise ValueError("Nonfinite yaw angle")
return {"absolute_yaw_deg": abs(yaw), "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"]["absolute_yaw_deg"]
candidate = after["simulation_result"]["absolute_yaw_deg"]
inertia_before = bp["inertia_tensor_kg_m2"][2][2]
inertia_after = ap["inertia_tensor_kg_m2"][2][2]
checks = {
"baseline_yaw_measurable": baseline > 1,
"yaw_reduced": candidate <= baseline * (1 - setup["required_relative_yaw_reduction"]),
"mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1)
<= setup["maximum_relative_mass_change"],
"footprint_and_height_fixed": all(
abs(a - b) <= setup["maximum_envelope_change_mm"]
for a, b in zip(ap["bounds_mm"], bp["bounds_mm"])),
"polar_inertia_in_band": abs(inertia_after / inertia_before - 1)
<= setup["maximum_relative_polar_inertia_change"],
"push_pad_intact": ap["push_pad_missing_mm3"]
<= setup["maximum_push_pad_missing_mm3"],
"planar_center": abs(ap["center_of_mass_mm"][2])
<= setup["maximum_center_z_offset_mm"],
"planar_inertia": all(abs(ap["inertia_tensor_kg_m2"][i][2])
<= setup["maximum_out_of_plane_cross_inertia_kg_m2"]
for i in (0, 1)),
}
after["comparison_to_before"] = {
"relative_yaw_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"Absolute yaw: {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()