PhyCAD-Bench / tasks /010 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
9.41 kB
"""Measure axle height variation while a STEP-derived wheel rolls on a floor."""
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("Wheel volume must be positive")
bounds = shape.BoundingBox()
inertia = props.MatrixOfInertia()
density = setup["material_density_kg_m3"]
outer = cq.Solid.makeCylinder(50, 10, cq.Vector(0, 0, -5))
bore = cq.Solid.makeCylinder(10, 10, cq.Vector(0, 0, -5))
hub = cq.Solid.makeCylinder(15, 10, cq.Vector(0, 0, -5)).cut(bore)
full_cylindrical_tread = any(
face.geomType() == "CYLINDER"
and abs(face.Area() - 2 * math.pi * 50 * 10) < 0.001
and abs(face.BoundingBox().xlen - 100) < 1e-6
and abs(face.BoundingBox().ylen - 100) < 1e-6
and abs(face.BoundingBox().zlen - 10) < 1e-6
for face in shape.Faces()
)
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(),
"bore_intrusion_mm3": shape.intersect(bore).Volume(),
"hub_missing_mm3": hub.cut(shape).Volume(),
"full_cylindrical_tread": full_cylindrical_tread,
"collision_vertices_mm": [[v.x, v.y, v.z] for v in vertices],
}
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.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 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)
axle = setup["initial_axle_m"]
wheel = (ch.ChBodyEasyCylinder(ch.ChAxis_Z, 0.05, 0.01, 1000, False, True, material)
if properties["full_cylindrical_tread"] else ch.ChBody())
wheel.SetMass(properties["mass_kg"])
inertia = ch.ChMatrix33d()
inertia.SetMatr(properties["inertia_tensor_kg_m2"])
wheel.SetInertia(inertia)
wheel.SetPos(ch.ChVector3d(axle[0] + center[0],
axle[1] + center[1], axle[2] + 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]))
if not properties["full_cylindrical_tread"]:
wheel.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, points))
wheel.EnableCollision(True)
system.Add(wheel)
planar = ch.ChLinkLockPlanar()
planar.Initialize(wheel, floor, ch.ChFramed(ch.ChVector3d(*axle)))
system.Add(planar)
drive = ch.ChForce()
wheel.AddForce(drive)
drive.SetMode(ch.ChForce.TORQUE)
drive.SetDir(ch.ChVector3d(0, 0, 1))
dt = setup["time_step_s"]
steps = round(setup["duration_s"] / dt)
settle = round(setup["settling_s"] / dt)
if dt <= 0 or steps <= settle or abs(steps * dt - setup["duration_s"]) > 1e-12:
raise ValueError("Invalid simulation duration or time step")
heights = []
spin_errors = []
contact_steps = 0
for i in range(steps):
t = i * dt
target = setup["target_spin_rad_s"] * min(1.0, t / setup["spin_ramp_s"])
error = target - wheel.GetAngVelParent().z
command = setup["speed_controller_gain_N_m_s_rad"] * error
limit = setup["maximum_drive_torque_N_m"]
drive.SetMforce(max(-limit, min(limit, command)))
system.DoStepDynamics(dt)
if i >= settle:
heights.append(wheel.GetPos().y)
spin_errors.append(abs(wheel.GetAngVelParent().z / setup["target_spin_rad_s"] - 1))
if floor.GetContactForce().Length() > 1e-8:
contact_steps += 1
mean_height = sum(heights) / len(heights)
rms_height = math.sqrt(sum((value - mean_height) ** 2 for value in heights)
/ len(heights))
end = wheel.GetPos()
if not all(math.isfinite(value) for value in (rms_height, end.x, end.y)):
raise ValueError("Nonfinite wheel trajectory")
return {
"post_ramp_rms_axle_height_m": rms_height,
"mean_axle_height_m": mean_height,
"distance_m": end.x - axle[0],
"mean_relative_spin_error": sum(spin_errors) / len(spin_errors),
"floor_contact_fraction": contact_steps / len(heights),
"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_ramp_rms_axle_height_m"]
candidate = after["simulation_result"]["post_ramp_rms_axle_height_m"]
checks = {
"baseline_bump_measurable": baseline > 0.0005,
"axle_height_variation_reduced": candidate <= baseline *
(1 - setup["required_relative_axle_height_variation_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"], bp["bounds_mm"])),
"outer_radius_limited": ap["external_added_mm3"]
<= setup["maximum_external_added_mm3"],
"shaft_bore_clear": ap["bore_intrusion_mm3"]
<= setup["maximum_bore_intrusion_mm3"],
"hub_interface_intact": ap["hub_missing_mm3"]
<= setup["maximum_hub_missing_mm3"],
"both_roll_forward": all(result["simulation_result"]["distance_m"]
>= setup["minimum_rolling_distance_m"]
for result in (before, after)),
"spin_speed_held": all(result["simulation_result"]["mean_relative_spin_error"]
<= setup["maximum_relative_spin_error"]
for result in (before, after)),
"floor_contact_observed": all(result["simulation_result"]["floor_contact_fraction"]
>= setup["minimum_floor_contact_fraction"]
for result in (before, after)),
}
after["comparison_to_before"] = {
"relative_axle_height_variation_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"RMS axle height variation: {baseline} -> {candidate} m")
print(f"Task passed: {after['comparison_to_before']['passed']}")
if not after["comparison_to_before"]["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()