PhyCAD-Bench / tasks /012 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
6.89 kB
"""Score passive ball capture against a STEP-derived guide contact mesh."""
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
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}")
bounds = shape.BoundingBox()
envelope = cq.Solid.makeBox(300, 100, 80, cq.Vector(-150, -100, -40))
mounts = [
cq.Solid.makeBox(20, 100, 80, cq.Vector(-150, -100, -40)),
cq.Solid.makeBox(20, 100, 80, cq.Vector(130, -100, -40)),
cq.Solid.makeBox(260, 10, 80, cq.Vector(-130, -100, -40)),
]
vertices, faces = shape.tessellate(1.0)
if not vertices or not faces:
raise ValueError("STEP tessellation has no triangles")
return {
"step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
"volume_mm3": shape.Volume(),
"bounds_mm": [bounds.xmin, bounds.xmax, bounds.ymin, bounds.ymax,
bounds.zmin, bounds.zmax],
"external_added_mm3": shape.cut(envelope).Volume(),
"mount_missing_mm3": sum(mount.cut(shape).Volume() for mount in mounts),
"collision_vertices_m": [[v.x / 1000, v.y / 1000, v.z / 1000]
for v in vertices],
"collision_triangles": faces,
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
ch.ChCollisionModel.SetDefaultSuggestedEnvelope(1e-5)
ch.ChCollisionModel.SetDefaultSuggestedMargin(1e-5)
material = ch.ChContactMaterialNSC()
material.SetFriction(setup["contact_friction"])
material.SetRestitution(setup["contact_restitution"])
mesh = ch.ChTriangleMeshConnected()
vertices = properties["collision_vertices_m"]
for a, b, c in properties["collision_triangles"]:
mesh.AddTriangle(ch.ChVector3d(*vertices[a]), ch.ChVector3d(*vertices[b]),
ch.ChVector3d(*vertices[c]))
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("Invalid simulation duration or time step")
capture_times = []
final_positions = []
for release_x in setup["release_x_m"]:
system = ch.ChSystemNSC()
system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 0))
guide = ch.ChBody()
guide.SetFixed(True)
guide.AddCollisionShape(ch.ChCollisionShapeTriangleMesh(
material, mesh, True, False, 0))
guide.EnableCollision(True)
system.Add(guide)
ball = ch.ChBodyEasySphere(setup["ball_radius_m"],
setup["ball_density_kg_m3"], True, True, material)
ball.SetPos(ch.ChVector3d(release_x, setup["release_y_m"], 0))
system.Add(ball)
planar = ch.ChLinkMateGeneric()
planar.SetConstrainedCoords(False, False, True, False, False, False)
planar.Initialize(ball, guide, ch.ChFramed(
ch.ChVector3d(release_x, setup["release_y_m"], 0)))
system.Add(planar)
captured = None
for i in range(steps):
system.DoStepDynamics(dt)
pos = ball.GetPos()
if not math.isfinite(pos.x + pos.y):
raise ValueError("Nonfinite ball trajectory")
if (abs(pos.x) <= setup["catch_half_width_m"]
and pos.y <= setup["catch_height_m"]):
captured = (i + 1) * dt
break
capture_times.append(captured)
final_positions.append([pos.x, pos.y])
return {"capture_times_s": capture_times,
"captured_count": sum(value is not None for value in capture_times),
"final_positions_m": final_positions}
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"]
captures = after["simulation_result"]["capture_times_s"]
checks = {
"baseline_misses": before["simulation_result"]["captured_count"] == 0,
"all_releases_captured": all(value is not None and value
<= setup["maximum_capture_time_s"]
for value in captures),
"envelope_fixed": all(abs(a - b) <= setup["maximum_envelope_change_mm"]
for a, b in zip(ap["bounds_mm"], bp["bounds_mm"])),
"outer_envelope_kept": ap["external_added_mm3"]
<= setup["maximum_external_added_mm3"],
"mounting_walls_intact": ap["mount_missing_mm3"]
<= setup["maximum_mount_missing_mm3"],
}
after["comparison_to_before"] = {"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"Ball captures: {before['simulation_result']['captured_count']} -> "
f"{after['simulation_result']['captured_count']}")
print(f"Task passed: {after['comparison_to_before']['passed']}")
if not after["comparison_to_before"]["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()