PhyCAD-Bench / tasks /016 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
10.3 kB
"""Measure lift dwell and filtered follower acceleration for a STEP cam."""
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("Cam volume must be positive")
bounds = shape.BoundingBox()
inertia = props.MatrixOfInertia()
density = setup["material_density_kg_m3"]
outer = cq.Solid.makeCylinder(120, 20, cq.Vector(0, 0, -10))
bore = cq.Solid.makeCylinder(10, 20, cq.Vector(0, 0, -10))
base_rim = (cq.Solid.makeCylinder(100, 20, cq.Vector(0, 0, -10))
.cut(cq.Solid.makeCylinder(90, 20, cq.Vector(0, 0, -10))))
hub = (cq.Solid.makeCylinder(20, 20, cq.Vector(0, 0, -10))
.cut(bore))
lobe_vertices = [[v.X, v.Y, v.Z] for v in shape.Vertices()
if v.Y >= 65 and abs(v.X) <= 85]
if len(lobe_vertices) < 6 or max(v[1] for v in lobe_vertices) < 110:
raise ValueError("Cam needs a STEP-resolved lift lobe")
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(),
"base_rim_missing_mm3": base_rim.cut(shape).Volume(),
"hub_missing_mm3": hub.cut(shape).Volume(),
"bore_intrusion_mm3": shape.intersect(bore).Volume(),
"lobe_collision_vertices_mm": lobe_vertices,
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
ch.ChCollisionModel.SetDefaultSuggestedEnvelope(1e-5)
ch.ChCollisionModel.SetDefaultSuggestedMargin(1e-5)
system = ch.ChSystemNSC()
system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
material = ch.ChContactMaterialNSC()
material.SetFriction(setup["contact_friction"])
ground = ch.ChBody()
ground.SetFixed(True)
system.Add(ground)
center = [value / 1000 for value in properties["center_of_mass_mm"]]
angle = setup["initial_cam_angle_rad"]
cam = ch.ChBody()
cam.SetMass(properties["mass_kg"])
inertia = ch.ChMatrix33d()
inertia.SetMatr(properties["inertia_tensor_kg_m2"])
cam.SetInertia(inertia)
cam.SetRot(ch.QuatFromAngleAxis(angle, ch.VECT_Z))
cam.SetPos(ch.ChVector3d(
center[0] * math.cos(angle) - center[1] * math.sin(angle),
center[0] * math.sin(angle) + center[1] * math.cos(angle), center[2]))
base_points = ch.vector_ChVector3d()
for i in range(64):
theta = 2 * math.pi * i / 64
for z in (-0.01, 0.01):
base_points.push_back(ch.ChVector3d(
0.1 * math.cos(theta) - center[0],
0.1 * math.sin(theta) - center[1], z - center[2]))
lobe_points = ch.vector_ChVector3d()
for x, y, z in properties["lobe_collision_vertices_mm"]:
lobe_points.push_back(ch.ChVector3d(
x / 1000 - center[0], y / 1000 - center[1], z / 1000 - center[2]))
cam.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, base_points))
cam.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, lobe_points))
cam.EnableCollision(True)
system.Add(cam)
hinge = ch.ChLinkLockRevolute()
hinge.Initialize(cam, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0)))
system.Add(hinge)
reference_y = setup["follower_reference_y_m"]
follower = ch.ChBodyEasySphere(setup["follower_radius_m"],
setup["follower_density_kg_m3"],
False, True, material)
follower.SetPos(ch.ChVector3d(0, reference_y, 0))
system.Add(follower)
guide = ch.ChLinkLockPrismatic()
guide.Initialize(follower, ground, ch.ChFramed(
ch.ChVector3d(0, reference_y, 0),
ch.QuatFromAngleAxis(-math.pi / 2, ch.VECT_X)))
system.Add(guide)
spring = ch.ChForce()
follower.AddForce(spring)
spring.SetMode(ch.ChForce.FORCE)
spring.SetDir(ch.ChVector3d(0, 1, 0))
drive = ch.ChForce()
cam.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)
if dt <= 0 or abs(steps * dt - setup["duration_s"]) > 1e-12:
raise ValueError("Invalid simulation duration or time step")
heights = []
speeds = []
for _ in range(steps):
spring.SetMforce(-setup["follower_preload_N"] -
setup["follower_spring_stiffness_N_m"] *
(follower.GetPos().y - reference_y))
error = setup["target_rotation_speed_rad_s"] - cam.GetAngVelParent().z
command = setup["speed_controller_gain_N_m_s_rad"] * error
limit = setup["maximum_motor_torque_N_m"]
drive.SetMforce(max(-limit, min(limit, command)))
system.DoStepDynamics(dt)
heights.append(follower.GetPos().y)
speeds.append(cam.GetAngVelParent().z)
if not all(math.isfinite(value) for value in heights + speeds):
raise ValueError("Nonfinite cam trajectory")
width = max(1, round(setup["acceleration_smoothing_s"] / dt))
smooth = []
for i in range(steps):
lo = max(0, i - width // 2)
hi = min(steps, i + width // 2 + 1)
smooth.append(sum(heights[lo:hi]) / (hi - lo))
span_s = width * dt
peak_acceleration = max(abs((smooth[i + width] - 2 * smooth[i]
+ smooth[i - width]) / span_s ** 2)
for i in range(width, steps - width))
return {
"peak_follower_height_m": max(heights),
"high_dwell_s": sum(value >= setup["high_follower_y_m"]
for value in heights) * dt,
"filtered_peak_follower_acceleration_m_s2": peak_acceleration,
"mean_rotation_speed_rad_s": sum(speeds) / len(speeds),
"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_has_short_dwell": bs["high_dwell_s"]
< setup["minimum_high_dwell_s"],
"useful_high_dwell": gs["high_dwell_s"]
>= setup["minimum_high_dwell_s"],
"peak_acceleration_reduced": gs["filtered_peak_follower_acceleration_m_s2"]
<= bs["filtered_peak_follower_acceleration_m_s2"] *
(1 - setup["required_relative_acceleration_reduction"]),
"rotation_speed_held": min(bs["mean_rotation_speed_rad_s"],
gs["mean_rotation_speed_rad_s"])
>= setup["minimum_mean_rotation_speed_rad_s"],
"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"],
"base_rim_intact": ap["base_rim_missing_mm3"]
<= setup["maximum_base_rim_missing_mm3"],
"hub_interface_intact": ap["hub_missing_mm3"]
<= setup["maximum_hub_missing_mm3"],
"shaft_bore_clear": ap["bore_intrusion_mm3"]
<= setup["maximum_bore_intrusion_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"High dwell: {bs['high_dwell_s']} -> {gs['high_dwell_s']} s")
print(f"Filtered peak acceleration: "
f"{bs['filtered_peak_follower_acceleration_m_s2']} -> "
f"{gs['filtered_peak_follower_acceleration_m_s2']} m/s^2")
print(f"Task passed: {after['comparison_to_before']['passed']}")
if not after["comparison_to_before"]["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()