PhyCAD-Bench / tasks /026 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
11.3 kB
"""Measure meshing torque ripple from a STEP-derived pinion tooth profile."""
import argparse
import hashlib
import json
import math
import statistics
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("Pinion volume must be positive")
density = setup["material_density_kg_m3"]
inertia = props.MatrixOfInertia()
bounds = shape.BoundingBox()
vertices = [[v.X, v.Y, v.Z] for v in shape.Vertices()]
tooth_vertices = []
tip_widths = []
for tooth in range(6):
center = tooth * math.pi / 3
selected = []
top_tip_angles = []
for x, y, z in vertices:
radius = math.hypot(x, y)
angle = math.atan2(y, x)
offset = (angle - center + math.pi) % (2 * math.pi) - math.pi
if radius >= 39.9 and abs(offset) <= math.pi / 6 + 1e-4:
selected.append([x, y, z])
if radius >= 49.9 and z >= 9.9 and abs(offset) < math.pi / 6:
top_tip_angles.append(offset)
if len(selected) < 8 or len(top_tip_angles) < 2:
raise ValueError("Expected six distinct STEP-resolved pinion teeth")
tooth_vertices.append(selected)
tip_widths.append(50 * (max(top_tip_angles) - min(top_tip_angles)))
bore = cq.Solid.makeCylinder(5, 20, cq.Vector(0, 0, -10))
core = cq.Solid.makeCylinder(30, 20, cq.Vector(0, 0, -10)).cut(bore)
pocket = cq.Solid.makeCylinder(8.31, 20, cq.Vector(20, 0, -10))
required_core = core.cut(pocket)
envelope = cq.Solid.makeCylinder(50.001, 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],
"tip_radius_mm": max(math.hypot(x, y) for x, y, _ in vertices),
"bore_intrusion_mm3": shape.intersect(bore).Volume(),
"core_missing_mm3": max(0.0, required_core.Volume() -
required_core.intersect(shape).Volume()),
"envelope_excess_mm3": shape.cut(envelope).Volume(),
"tip_widths_mm": tip_widths,
"tooth_collision_vertices_mm": tooth_vertices,
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
ch.ChCollisionModel.SetDefaultSuggestedEnvelope(1e-5)
ch.ChCollisionModel.SetDefaultSuggestedMargin(1e-5)
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)
def add_hull(body, points, center):
vertices = ch.vector_ChVector3d()
for x, y, z in points:
vertices.push_back(ch.ChVector3d(x - center[0], y - center[1],
z - center[2]))
body.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, vertices))
def add_base(body, count, radius, center):
points = []
for i in range(count * 16):
angle = 2 * math.pi * i / (count * 16)
for z in (-0.01, 0.01):
points.append((radius * math.cos(angle),
radius * math.sin(angle), z))
add_hull(body, points, center)
center = [value / 1000 for value in properties["center_of_mass_mm"]]
pinion = ch.ChBody()
pinion.SetMass(properties["mass_kg"])
pinion_inertia = ch.ChMatrix33d()
pinion_inertia.SetMatr(properties["inertia_tensor_kg_m2"])
pinion.SetInertia(pinion_inertia)
pinion.SetPos(ch.ChVector3d(*center))
add_base(pinion, 6, 0.04, center)
for tooth in properties["tooth_collision_vertices_mm"]:
add_hull(pinion, [(x / 1000, y / 1000, z / 1000)
for x, y, z in tooth], center)
pinion.EnableCollision(True)
system.Add(pinion)
pinion_motor = ch.ChLinkMotorRotationSpeed()
pinion_motor.Initialize(pinion, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0)))
pinion_motor.SetSpeedFunction(ch.ChFunctionConst(setup["pinion_speed_rad_s"]))
system.Add(pinion_motor)
mate = ch.ChBody()
mate.SetMass(setup["mating_gear_mass_kg"])
mate_inertia = ch.ChMatrix33d()
mate_inertia.SetMatr([[0.01, 0, 0], [0, 0.01, 0], [0, 0, 0.012]])
mate.SetInertia(mate_inertia)
mate.SetRot(ch.QuatFromAngleAxis(math.pi / 12, ch.VECT_Z))
mate.SetPos(ch.ChVector3d(setup["center_distance_m"], 0, 0))
mate.SetAngVelParent(ch.ChVector3d(0, 0, -setup["pinion_speed_rad_s"] / 2))
add_base(mate, 12, 0.08, (0, 0, 0))
for tooth in range(12):
center_angle = tooth * math.pi / 6
points = []
for offset, radius in ((-math.pi / 12, 0.08), (-0.2, 0.08),
(-0.06, 0.1), (0.06, 0.1), (0.2, 0.08)):
angle = center_angle + offset
for z in (-0.01, 0.01):
points.append((radius * math.cos(angle),
radius * math.sin(angle), z))
add_hull(mate, points, (0, 0, 0))
mate.EnableCollision(True)
system.Add(mate)
mate_motor = ch.ChLinkMotorRotationSpeed()
mate_motor.Initialize(mate, ground, ch.ChFramed(
ch.ChVector3d(setup["center_distance_m"], 0, 0)))
mate_motor.SetSpeedFunction(ch.ChFunctionConst(-setup["pinion_speed_rad_s"] / 2))
system.Add(mate_motor)
load = ch.ChForce()
mate.AddForce(load)
load.SetMode(ch.ChForce.TORQUE)
load.SetDir(ch.ChVector3d(0, 0, 1))
load.SetMforce(setup["output_load_torque_N_m"])
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")
torques = []
speeds = []
contact_steps = 0
for i in range(steps):
system.DoStepDynamics(dt)
if (i + 1) * dt < setup["startup_exclusion_s"]:
continue
torque = mate.GetContactTorque().z
torques.append(torque)
speeds.append(mate.GetAngVelParent().z)
if mate.GetContactForce().Length() > 1e-6:
contact_steps += 1
if not torques or not all(math.isfinite(x) for x in torques + speeds):
raise ValueError("Nonfinite or empty gear torque trace")
return {
"output_contact_torque_ripple_N_m": statistics.pstdev(torques),
"mean_output_contact_torque_N_m": statistics.mean(torques),
"contact_fraction": contact_steps / len(torques),
"mean_output_speed_rad_s": statistics.mean(speeds),
"pinion_rotation_rad": pinion_motor.GetMotorAngle(),
"output_rotation_rad": mate_motor.GetMotorAngle(),
}
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["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,
}),
}
bp = results["before"]["step_properties"]
ap = results["after"]["step_properties"]
bs = results["before"]["simulation_result"]
gs = results["after"]["simulation_result"]
checks = {
"baseline_ripple_measurable": bs["output_contact_torque_ripple_N_m"] >=
setup["minimum_baseline_torque_ripple_N_m"],
"torque_ripple_reduced": gs["output_contact_torque_ripple_N_m"] <=
bs["output_contact_torque_ripple_N_m"] *
(1 - setup["required_relative_torque_ripple_reduction"]),
"teeth_engaged": min(bs["contact_fraction"], gs["contact_fraction"]) >=
setup["minimum_contact_fraction"],
"gear_ratio_held": abs(gs["mean_output_speed_rad_s"] +
setup["pinion_speed_rad_s"] / 2) <=
setup["maximum_output_speed_error_rad_s"],
"minimum_tooth_tip_width": min(ap["tip_widths_mm"]) >=
setup["minimum_tooth_tip_width_mm"],
"mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) <=
setup["maximum_relative_mass_change"],
"envelope_fixed": abs(ap["tip_radius_mm"] - bp["tip_radius_mm"]) <=
setup["maximum_tip_radius_change_mm"] and
all(abs(ap["bounds_mm"][i] - bp["bounds_mm"][i]) <=
setup["maximum_thickness_change_mm"] for i in (4, 5)),
"core_and_bore_intact": ap["core_missing_mm3"] <=
setup["maximum_core_missing_mm3"] and
ap["bore_intrusion_mm3"] <= setup["maximum_bore_intrusion_mm3"],
"outer_envelope_intact": ap["envelope_excess_mm3"] <=
setup["maximum_envelope_excess_mm3"],
}
results["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"Output contact torque ripple: {bs['output_contact_torque_ripple_N_m']} -> "
f"{gs['output_contact_torque_ripple_N_m']} N m")
print(f"Task passed: {all(checks.values())}")
if not all(checks.values()):
raise SystemExit(1)
if __name__ == "__main__":
main()