PhyCAD-Bench / tasks /041 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
8.76 kB
"""Run a STEP-contact track shoe over a rigid rock at fixed speeds."""
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 len(shape.Solids()) != 1 or not shape.isValid():
raise ValueError("Expected one valid track-shoe solid")
mount = cq.Solid.makeBox(100, 100, 10, cq.Vector(-50, -50, 20))
envelope = cq.Solid.makeBox(300, 100, 30, cq.Vector(-150, -50, 0))
vertices, faces = shape.tessellate(setup["cad_tessellation_tolerance_mm"])
if len(vertices) < 8 or len(faces) < 12:
raise ValueError("Track-shoe tessellation is incomplete")
return {
"step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
"volume_mm3": shape.Volume(),
"mount_missing_mm3": max(0.0, mount.Volume() - mount.intersect(shape).Volume()),
"envelope_excess_mm3": max(0.0, shape.Volume() -
shape.intersect(envelope).Volume()),
"collision_mesh": {
"vertices": [[axis / 1000 for axis in point.toTuple()]
for point in vertices],
"faces": faces,
},
}
def dynamics(collision_mesh: dict, setup: dict) -> dict:
import pychrono as ch
collision_mesh_ch = ch.ChTriangleMeshConnected()
vertices = [ch.ChVector3d(*point) for point in collision_mesh["vertices"]]
for a, b, c in collision_mesh["faces"]:
collision_mesh_ch.AddTriangle(vertices[a], vertices[b], vertices[c])
results = {}
for speed in setup["drive_speeds_m_s"]:
system = ch.ChSystemSMC()
system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(
ch.ChVector3d(0, 0, -setup["gravity_m_s2"]))
system.SetSolver(ch.ChSolverSparseLU())
material = ch.ChContactMaterialSMC()
material.SetFriction(setup["contact_friction"])
material.SetRestitution(0)
material.SetYoungModulus(setup["contact_young_modulus_Pa"])
floor = ch.ChBodyEasyBox(2, 1, 0.1, 1000, False, True, material)
floor.SetPos(ch.ChVector3d(0, 0, -0.05))
floor.SetFixed(True)
system.Add(floor)
rock = ch.ChBodyEasySphere(setup["rock_radius_m"], 1000,
False, True, material)
rock.SetPos(ch.ChVector3d(*setup["rock_center_m"]))
rock.SetFixed(True)
system.Add(rock)
shoe = ch.ChBody()
shoe.SetMass(setup["carrier_mass_kg"])
shoe.SetInertiaXX(ch.ChVector3d(*setup["carrier_inertia_kg_m2"]))
shoe.SetPos(ch.ChVector3d(*setup["initial_position_m"]))
shoe.AddCollisionShape(ch.ChCollisionShapeTriangleMesh(
material, collision_mesh_ch, False, False,
setup["collision_thickness_m"]))
shoe.EnableCollision(True)
system.Add(shoe)
guide = ch.ChLinkMateGeneric()
guide.SetConstrainedCoords(False, True, False, True, True, True)
guide.Initialize(shoe, floor, ch.ChFramed(shoe.GetPos()))
system.Add(guide)
motor = ch.ChLinkMotorLinearSpeed()
motor.SetGuideConstraint(ch.ChLinkMotorLinear.GuideConstraint_FREE)
motor.Initialize(shoe, floor, ch.ChFramed(
shoe.GetPos(), ch.QuatFromAngleY(math.pi / 2)))
motor.SetMotorFunction(ch.ChFunctionConst(speed))
system.Add(motor)
spring = ch.ChForce()
shoe.AddForce(spring)
spring.SetMode(ch.ChForce.FORCE)
spring.SetDir(ch.ChVector3d(0, 0, 1))
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 time grid")
peak_acceleration = 0.0
peak_height = setup["initial_position_m"][2]
for index in range(steps):
position = shoe.GetPos()
velocity = shoe.GetPosDt()
spring.SetMforce(
setup["carrier_mass_kg"] * setup["gravity_m_s2"] +
setup["spring_stiffness_N_m"] *
(setup["spring_rest_height_m"] - position.z) -
setup["spring_damping_N_s_m"] * velocity.z)
system.DoStepDynamics(dt)
if index * dt >= 0.3:
peak_acceleration = max(peak_acceleration,
abs(shoe.GetPosDt2().z))
peak_height = max(peak_height, shoe.GetPos().z)
if not all(math.isfinite(value) for value in (
peak_acceleration, peak_height, shoe.GetPos().x)):
raise ValueError("Non-finite shoe trajectory")
results[str(speed)] = {
"peak_vertical_acceleration_m_s2": peak_acceleration,
"rock_climb_m": peak_height - setup["initial_position_m"][2],
"final_x_m": shoe.GetPos().x,
"motor_speed_m_s": motor.GetMotorPosDt(),
"collision_triangle_count": collision_mesh_ch.GetNumTriangles(),
}
return results
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)
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["collision_mesh"], 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})
collision_mesh = properties.pop("collision_mesh")
results[name] = {
"step_properties": properties,
"simulation_result": invoke(args.physics_python, "dynamics", {
"collision_mesh": collision_mesh, "setup": setup}),
}
before, after = results["before"], results["after"]
bp, ap = before["step_properties"], after["step_properties"]
bs, gs = before["simulation_result"], after["simulation_result"]
speeds = [str(speed) for speed in setup["drive_speeds_m_s"]]
baseline = [bs[speed]["peak_vertical_acceleration_m_s2"] for speed in speeds]
candidate = [gs[speed]["peak_vertical_acceleration_m_s2"] for speed in speeds]
reductions = [1 - a / b for a, b in zip(candidate, baseline)]
checks = {
"baseline_acceleration_measurable": min(baseline) >=
setup["minimum_baseline_peak_acceleration_m_s2"],
"acceleration_reduced_both_speeds": min(reductions) >=
setup["required_relative_peak_acceleration_reduction"],
"candidate_acceleration_below_limit": max(candidate) <=
setup["maximum_candidate_peak_acceleration_m_s2"],
"rock_climbed": all(gs[speed]["rock_climb_m"] >=
setup["minimum_rock_climb_m"] for speed in speeds),
"motor_speeds_met": all(abs(gs[speed]["motor_speed_m_s"] - float(speed))
< 1e-6 for speed in speeds),
"course_traversed": all(gs[speed]["final_x_m"] > 0.25
for speed in speeds),
"volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <=
setup["maximum_relative_volume_change"],
"mount_fixed": ap["mount_missing_mm3"] <=
setup["maximum_mount_missing_mm3"],
"envelope_fixed": ap["envelope_excess_mm3"] <=
setup["maximum_envelope_excess_mm3"],
}
after["comparison_to_before"] = {
"relative_peak_acceleration_reductions": reductions,
"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"Peak acceleration: {baseline} -> {candidate} m/s2")
print(f"Task passed: {all(checks.values())}")
if not all(checks.values()):
raise SystemExit(1)
if __name__ == "__main__":
main()