PhyCAD-Bench / tasks /008 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
7.84 kB
"""Roll a STEP-derived convex rocker on a floor and time its return upright."""
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("Rocker volume must be positive")
density = setup["material_density_kg_m3"]
inertia = props.MatrixOfInertia()
bounds = shape.BoundingBox()
outer = (cq.Workplane("XY").moveTo(-50, 0)
.threePointArc((0, -50), (50, 0)).lineTo(-50, 0)
.close().extrude(20).translate((0, 0, -10)).val())
if len(outer.Solids()) == 1:
outer = outer.Solids()[0]
allowed = cq.Solid.makeBox(42, 40, 17, cq.Vector(-21, -41, -8.5))
vertices, _ = shape.tessellate(0.25)
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],
"external_added_mm3": shape.cut(outer).Volume(),
"exterior_removed_mm3": outer.cut(shape).cut(allowed).Volume(),
"collision_vertices_mm": [[v.x, v.y, v.z] for v in vertices],
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
system = ch.ChSystemNSC()
system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 0))
material = ch.ChContactMaterialNSC()
material.SetFriction(setup["contact_friction"])
material.SetRestitution(0)
floor = ch.ChBodyEasyBox(1, 0.1, 0.3, 1000, False, True, material)
floor.SetPos(ch.ChVector3d(0, -0.05, 0))
floor.SetFixed(True)
system.Add(floor)
rocker = ch.ChBody()
rocker.SetMass(properties["mass_kg"])
inertia = ch.ChMatrix33d()
inertia.SetMatr(properties["inertia_tensor_kg_m2"])
rocker.SetInertia(inertia)
center = [value / 1000 for value in properties["center_of_mass_mm"]]
angle = math.radians(setup["initial_angle_deg"])
rocker.SetRot(ch.QuatFromAngleAxis(angle, ch.VECT_Z))
rocker.SetPos(ch.ChVector3d(
center[0] * math.cos(angle) - center[1] * math.sin(angle),
0.05 + center[0] * math.sin(angle) + center[1] * math.cos(angle),
center[2],
))
points = ch.vector_ChVector3d()
for x, y, z in properties["collision_vertices_mm"]:
points.push_back(ch.ChVector3d(x / 1000 - center[0],
y / 1000 - center[1],
z / 1000 - center[2]))
rocker.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, points))
rocker.EnableCollision(True)
system.Add(rocker)
dt = setup["time_step_s"]
steps = round(setup["duration_s"] / dt)
if dt <= 0 or steps <= 0 or abs(steps * dt - setup["duration_s"]) > 1e-12:
raise ValueError("Invalid simulation duration or time step")
returned = None
contact_steps = 0
final_angle = None
for i in range(1, steps + 1):
system.DoStepDynamics(dt)
q = rocker.GetRot()
final_angle = math.degrees(2 * math.atan2(q.e3, q.e0))
if not math.isfinite(final_angle):
raise ValueError("Nonfinite rocker angle")
if rocker.GetContactForce().Length() > 1e-8:
contact_steps += 1
if returned is None and abs(final_angle) <= setup["upright_tolerance_deg"]:
returned = i * dt
return {
"initial_angle_deg": setup["initial_angle_deg"],
"time_to_upright_s": returned,
"final_angle_deg": final_angle,
"contact_steps": contact_steps,
"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": {
"runs": [invoke(args.physics_python, "dynamics", {
"properties": properties,
"setup": {**setup, "initial_angle_deg": angle},
}) for angle in setup["release_angles_deg"]],
},
}
before = results["before"]
after = results["after"]
bp = before["step_properties"]
ap = after["step_properties"]
bruns = before["simulation_result"]["runs"]
aruns = after["simulation_result"]["runs"]
btimes = [run["time_to_upright_s"] for run in bruns]
atimes = [run["time_to_upright_s"] for run in aruns]
checks = {
"baseline_misses_deadline": all(
time is None or time > setup["maximum_return_time_s"] for time in btimes),
"returns_before_deadline": all(
time is not None and time <= setup["maximum_return_time_s"] for time in atimes),
"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"], bp["bounds_mm"])),
"exterior_profile_fixed": ap["external_added_mm3"]
<= setup["maximum_external_added_mm3"]
and ap["exterior_removed_mm3"] <= setup["maximum_exterior_removed_mm3"],
"floor_contact_observed": all(run["contact_steps"] > 0
for run in (*bruns, *aruns)),
}
after["comparison_to_before"] = {
"release_angles_deg": setup["release_angles_deg"],
"time_to_upright_before_s": btimes,
"time_to_upright_after_s": atimes,
"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"Time to upright: {btimes} -> {atimes} s")
print(f"Task passed: {after['comparison_to_before']['passed']}")
if not after["comparison_to_before"]["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()