PhyCAD-Bench / tasks /025 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
9.43 kB
"""Measure rotation and rebound against a STEP-derived rocker stop lug."""
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()
base = cq.Workplane("XY").box(120, 20, 20).translate((50, 0, 0)).val()
lug_region = cq.Solid.makeBox(20, 25, 20, cq.Vector(70, 10, -10))
pocket_region = cq.Solid.makeBox(30, 8, 20, cq.Vector(30, -4, -10))
bore = cq.Solid.makeCylinder(5, 20, cq.Vector(0, 0, -10))
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(base).cut(lug_region).Volume(),
"base_removed_mm3": base.cut(shape).cut(pocket_region).cut(bore).Volume(),
"pivot_bore_intrusion_mm3": shape.intersect(bore).Volume(),
"collision_vertices_mm": [[v.X, v.Y, v.Z] for v in shape.Vertices()],
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
center = [value / 1000 for value in properties["center_of_mass_mm"]]
mass = properties["mass_kg"]
inertia_tensor = properties["inertia_tensor_kg_m2"]
pivot_inertia = inertia_tensor[2][2] + mass * (center[0] ** 2 + center[1] ** 2)
speed = setup["angular_impulse_N_m_s"] / pivot_inertia
angle = 0.0
pivot_to_center = (
center[0] * math.cos(angle) - center[1] * math.sin(angle),
center[0] * math.sin(angle) + center[1] * math.cos(angle),
)
system = ch.ChSystemSMC()
system.UseMaterialProperties(False)
system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
material = ch.ChContactMaterialSMC()
material.SetFriction(setup["contact_friction"])
material.SetKn(setup["contact_stiffness_N_m"])
material.SetGn(setup["contact_damping_N_s_m"])
ground = ch.ChBody()
ground.SetFixed(True)
system.Add(ground)
stop = ch.ChBodyEasyBox(
*setup["stop_size_m"], 1000, False, True, material)
stop.SetPos(ch.ChVector3d(*setup["stop_center_m"]))
stop.SetFixed(True)
system.Add(stop)
rocker = ch.ChBody()
rocker.SetMass(mass)
inertia = ch.ChMatrix33d()
inertia.SetMatr(inertia_tensor)
rocker.SetInertia(inertia)
rocker.SetRot(ch.QuatFromAngleAxis(angle, ch.VECT_Z))
rocker.SetPos(ch.ChVector3d(*pivot_to_center, center[2]))
rocker.SetAngVelParent(ch.ChVector3d(0, 0, speed))
rocker.SetLinVel(ch.ChVector3d(-speed * pivot_to_center[1],
speed * pivot_to_center[0], 0))
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)
hinge = ch.ChLinkLockRevolute()
hinge.Initialize(rocker, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0)))
system.Add(hinge)
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")
contact_steps = 0
peak_angle = 0.0
peak_rebound_speed = 0.0
peak_pivot_reaction = 0.0
peak_stop_contact_force = 0.0
for _ in range(steps):
system.DoStepDynamics(dt)
q = rocker.GetRot()
current_angle = 2 * math.atan2(q.e3, q.e0)
peak_angle = max(peak_angle, current_angle)
contact_force = rocker.GetContactForce().Length()
peak_stop_contact_force = max(peak_stop_contact_force, contact_force)
if contact_force > 1e-8:
contact_steps += 1
if contact_steps:
peak_rebound_speed = max(peak_rebound_speed,
-rocker.GetAngVelParent().z)
reaction = hinge.GetReaction1().force
peak_pivot_reaction = max(peak_pivot_reaction,
math.hypot(reaction.x, reaction.y))
if not all(math.isfinite(x) for x in
(peak_angle, peak_rebound_speed, peak_pivot_reaction,
peak_stop_contact_force)):
raise ValueError("Nonfinite rocker response")
return {
"peak_angle_rad": peak_angle,
"peak_rebound_speed_rad_s": peak_rebound_speed,
"peak_pivot_reaction_N": peak_pivot_reaction,
"peak_stop_contact_force_N": peak_stop_contact_force,
"contact_steps": contact_steps,
"initial_angular_speed_rad_s": speed,
"angular_impulse_N_m_s": pivot_inertia * speed,
"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"]
bs = before["simulation_result"]
gs = after["simulation_result"]
checks = {
"baseline_rotates": bs["peak_angle_rad"] >=
setup["minimum_baseline_peak_angle_rad"],
"baseline_rebounds": bs["peak_rebound_speed_rad_s"] >=
setup["minimum_baseline_rebound_speed_rad_s"],
"rotation_limited": gs["peak_angle_rad"] <=
setup["maximum_peak_angle_rad"],
"rebound_limited": gs["peak_rebound_speed_rad_s"] <=
setup["maximum_peak_rebound_speed_rad_s"],
"pivot_reaction_limited": gs["peak_pivot_reaction_N"] <=
setup["maximum_peak_pivot_reaction_N"],
"mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1)
<= setup["maximum_relative_mass_change"],
"mount_envelope_fixed": all(
abs(ap["bounds_mm"][i] - bp["bounds_mm"][i]) <=
setup["maximum_mount_envelope_change_mm"]
for i in (0, 1, 2, 4, 5)) and
ap["bounds_mm"][3] <= setup["maximum_lug_height_mm"],
"edits_in_allowed_regions": ap["external_added_mm3"]
<= setup["maximum_external_added_mm3"] and
ap["base_removed_mm3"] <= setup["maximum_base_removed_mm3"],
"pivot_bore_clear": ap["pivot_bore_intrusion_mm3"]
<= setup["maximum_pivot_bore_intrusion_mm3"],
"stop_contact_observed": bs["contact_steps"] > 0 and
gs["contact_steps"] > 0,
}
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"Peak angle: {bs['peak_angle_rad']} -> {gs['peak_angle_rad']} rad")
print(f"Peak rebound speed: {bs['peak_rebound_speed_rad_s']} -> "
f"{gs['peak_rebound_speed_rad_s']} rad/s")
print(f"Task passed: {after['comparison_to_before']['passed']}")
if not after["comparison_to_before"]["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()