PhyCAD-Bench / tasks /002 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
6.29 kB
"""Measure both STEP wheels and roll each with the same PyChrono setup."""
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, 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,
"outer_diameter_mm": max(box.xlen, box.ylen),
"axial_thickness_mm": box.zlen,
"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
if max(abs(v) for v in p["center_of_mass_mm"]) > 1e-6:
raise ValueError("Wheel must be centered on the origin")
radius = p["outer_diameter_mm"] / 2000
thickness = p["axial_thickness_mm"] / 1000
angle = math.radians(setup["ramp_angle_deg"])
system = ch.ChSystemNSC()
system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(ch.ChVector3d(
setup["gravity_m_s2"] * math.sin(angle),
-setup["gravity_m_s2"] * math.cos(angle), 0,
))
material = ch.ChContactMaterialNSC()
material.SetFriction(setup["contact_friction"])
floor = ch.ChBodyEasyBox(3, 0.1, 0.3, 1000, False, True, material)
floor.SetPos(ch.ChVector3d(0, -0.05, 0))
floor.SetFixed(True)
system.Add(floor)
# The outer cylindrical surface is the only wheel surface that contacts the floor.
wheel = ch.ChBodyEasyCylinder(
ch.ChAxis_Z, radius, thickness, 1000, False, True, material
)
wheel.SetMass(p["mass_kg"])
inertia = ch.ChMatrix33d()
inertia.SetMatr(p["inertia_tensor_kg_m2"])
wheel.SetInertia(inertia)
wheel.SetPos(ch.ChVector3d(setup["initial_x_m"], radius, 0))
system.Add(wheel)
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")
for _ in range(steps):
system.DoStepDynamics(dt)
vx = wheel.GetLinVel().x
omega = wheel.GetAngVelParent().z
distance = wheel.GetPos().x - setup["initial_x_m"]
return {
"down_ramp_displacement_m": distance,
"final_linear_speed_m_s": vx,
"final_angular_velocity_z_rad_s": omega,
"rolling_slip_ratio": abs(vx + radius * omega) / max(abs(vx), 1e-12),
"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"]
bd = b["simulation_result"]["down_ramp_displacement_m"]
ad = a["simulation_result"]["down_ramp_displacement_m"]
gain = ad / bd - 1
checks = {
"displacement_gain": gain >= setup["required_relative_displacement_gain"],
"mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1)
<= setup["maximum_relative_mass_change"],
"outer_diameter_fixed": abs(ap["outer_diameter_mm"] - bp["outer_diameter_mm"])
<= setup["maximum_outer_diameter_change_mm"],
"both_wheels_roll_without_material_slip": all(
results[n]["simulation_result"]["rolling_slip_ratio"]
<= setup["maximum_rolling_slip_ratio"]
for n in ("before", "after")
),
}
a["comparison_to_before"] = {
"relative_displacement_gain": gain, "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"Ramp displacement: {bd:.6f} -> {ad:.6f} m ({gain:.1%} gain)")
print(f"Task passed: {a['comparison_to_before']['passed']}")
if not a["comparison_to_before"]["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()