PhyCAD-Bench / tasks /032 /simulate.py
OrlaLabs's picture
Add PhyCAD-Bench benchmark
99510bd verified
Raw History Blame Contribute Delete
12.3 kB
"""Feed STEP-derived leaf stiffness into a reduced-order impact contact."""
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
import gmsh
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("Leaf volume must be positive")
pad0 = cq.Solid.makeBox(10, 20, 10, cq.Vector(0, -10, -5))
pad1 = cq.Solid.makeBox(10, 20, 10, cq.Vector(90, -10, -5))
slabs = [cq.Solid.makeBox(10, 20, 20, cq.Vector(x, -10, -10))
for x in (0, 90)]
envelope = cq.Solid.makeBox(100, 20, 14, cq.Vector(0, -10, -7))
pads = (pad0, pad1)
pad_overlap = sum(pad.intersect(shape).Volume() for pad in pads)
slab_overlap = sum(slab.intersect(shape).Volume() for slab in slabs)
result = {
"step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
"volume_mm3": props.Mass(),
"mass_kg": props.Mass() * setup["material_density_kg_m3"] * 1e-9,
"end_pad_missing_mm3": max(0.0, sum(p.Volume() for p in pads) - pad_overlap),
"end_pad_excess_mm3": max(0.0, slab_overlap - pad_overlap),
"envelope_excess_mm3": max(0.0, shape.Volume() -
shape.intersect(envelope).Volume()),
"meshes": {},
}
gmsh.initialize()
try:
gmsh.option.setNumber("General.Terminal", 0)
gmsh.model.add("leaf")
gmsh.model.occ.importShapes(str(step))
gmsh.model.occ.synchronize()
if len(gmsh.model.getEntities(3)) != 1:
raise ValueError("STEP import must produce one volume")
for size in setup["mesh_sizes_mm"]:
gmsh.model.mesh.clear()
gmsh.option.setNumber("Mesh.CharacteristicLengthMin", size)
gmsh.option.setNumber("Mesh.CharacteristicLengthMax", size)
gmsh.option.setNumber("Mesh.Algorithm3D", 1)
gmsh.model.mesh.generate(3)
tags, coordinates, _ = gmsh.model.mesh.getNodes()
nodes = {str(int(tag)): [coordinates[3 * i + axis] / 1000
for axis in range(3)]
for i, tag in enumerate(tags)}
types, _, element_nodes = gmsh.model.mesh.getElements(3)
tets = []
for kind, connectivity in zip(types, element_nodes):
if kind != 4:
raise ValueError(f"Expected first-order tetrahedra, got {kind}")
tets.extend([[int(value) for value in connectivity[i:i + 4]]
for i in range(0, len(connectivity), 4)])
if not nodes or not tets:
raise ValueError("Gmsh produced an empty mesh")
result["meshes"][str(size)] = {"nodes": nodes, "tets": tets}
finally:
gmsh.finalize()
return result
def dynamics(meshes: dict, setup: dict) -> dict:
import pychrono as ch
import pychrono.fea as fea
results = {}
for size, data in meshes.items():
system = ch.ChSystemSMC()
system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
system.SetSolver(ch.ChSolverSparseLU())
mesh = fea.ChMesh()
material = fea.ChContinuumElastic()
material.SetYoungModulus(setup["young_modulus_Pa"])
material.SetPoissonRatio(setup["poisson_ratio"])
material.SetDensity(setup["material_density_kg_m3"])
center_region = [(key, point) for key, point in data["nodes"].items()
if 0.045 <= point[0] <= 0.055]
if not center_region:
raise ValueError("Mesh is missing the center load patch")
top = max(point[2] for _, point in center_region)
load_ids = [key for key, point in center_region
if abs(point[2] - top) < 1e-8]
fixed_ids = [key for key, point in data["nodes"].items()
if abs(point[0]) < 1e-8 or abs(point[0] - 0.1) < 1e-8]
if len(load_ids) < 4 or len(fixed_ids) < 8:
raise ValueError("Mesh is missing a mount or center load face")
nodes = {}
for key, point in data["nodes"].items():
node = fea.ChNodeFEAxyz(ch.ChVector3d(*point))
if key in fixed_ids:
node.SetFixed(True)
if key in load_ids:
node.SetForce(ch.ChVector3d(
0, 0, setup["fea_probe_force_N"] / len(load_ids)))
mesh.AddNode(node)
nodes[int(key)] = node
for a, b, c, d in data["tets"]:
element = fea.ChElementTetraCorot_4()
element.SetNodes(nodes[a], nodes[b], nodes[c], nodes[d])
element.SetMaterial(material)
mesh.AddElement(element)
system.Add(mesh)
system.DoStaticLinear()
deflections = [data["nodes"][key][2] - nodes[int(key)].GetPos().z
for key in load_ids]
mean_deflection = sum(deflections) / len(deflections)
if not math.isfinite(mean_deflection) or mean_deflection <= 0:
raise ValueError("Invalid leaf deflection")
stiffness = abs(setup["fea_probe_force_N"]) / mean_deflection
impact = simulate_impact(stiffness, setup)
results[size] = {
"center_probe_deflection_m": mean_deflection,
"effective_spring_stiffness_N_m": stiffness,
"impact": impact,
"node_count": len(nodes),
"tetrahedron_count": len(data["tets"]),
"clamped_node_count": len(fixed_ids),
"loaded_node_count": len(load_ids),
}
return results
def simulate_impact(stiffness: float, setup: dict) -> dict:
import pychrono as ch
ch.ChCollisionModel.SetDefaultSuggestedEnvelope(1e-6)
ch.ChCollisionModel.SetDefaultSuggestedMargin(1e-6)
system = ch.ChSystemSMC()
system.UseMaterialProperties(False)
system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
material = ch.ChContactMaterialSMC()
material.SetFriction(0)
contact_stiffness = stiffness / math.sqrt(setup["reference_compression_m"])
material.SetKn(contact_stiffness)
material.SetGn(2 * setup["contact_damping_ratio"] *
math.sqrt(contact_stiffness * setup["impactor_mass_kg"]))
floor = ch.ChBodyEasyBox(0.3, 0.01, 0.3, 1000, False, True, material)
floor.SetPos(ch.ChVector3d(0, -0.01, 0))
floor.SetFixed(True)
system.Add(floor)
radius = setup["impactor_radius_m"]
mass = setup["impactor_mass_kg"]
ball = ch.ChBodyEasySphere(
radius, mass / (4 * math.pi * radius ** 3 / 3),
False, True, material)
ball.SetPos(ch.ChVector3d(0, setup["impactor_initial_center_y_m"], 0))
ball.SetLinVel(ch.ChVector3d(0, -setup["impactor_initial_speed_m_s"], 0))
system.Add(ball)
dt = setup["impact_time_step_s"]
steps = round(setup["impact_duration_s"] / dt)
if dt <= 0 or abs(steps * dt - setup["impact_duration_s"]) > 1e-12:
raise ValueError("Invalid impact duration or time step")
peak_force = 0.0
stroke = 0.0
contact_steps = 0
rebound_speed = None
for _ in range(steps):
system.DoStepDynamics(dt)
force = ball.GetContactForce().Length()
peak_force = max(peak_force, force)
stroke = max(stroke, radius - ball.GetPos().y)
if force > 1e-7:
contact_steps += 1
if (contact_steps and rebound_speed is None and
ball.GetPos().y > radius + 0.0001 and
ball.GetLinVel().y > 0):
rebound_speed = ball.GetLinVel().y
if not all(math.isfinite(x) for x in (peak_force, stroke)):
raise ValueError("Nonfinite impact response")
return {"peak_force_N": peak_force, "maximum_stroke_m": stroke,
"rebound_speed_m_s": rebound_speed, "contact_steps": contact_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)
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["meshes"], 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,
})
meshes = properties.pop("meshes")
results[name] = {
"step_properties": properties,
"simulation_result": invoke(args.physics_python, "dynamics", {
"meshes": meshes, "setup": setup,
}),
}
before = results["before"]
after = results["after"]
bp, ap = before["step_properties"], after["step_properties"]
bs, gs = before["simulation_result"], after["simulation_result"]
sizes = [str(size) for size in setup["mesh_sizes_mm"]]
baseline = [bs[size]["impact"]["peak_force_N"] for size in sizes]
candidate = [gs[size]["impact"]["peak_force_N"] for size in sizes]
reductions = [1 - a / b for a, b in zip(candidate, baseline)]
bk = [bs[size]["effective_spring_stiffness_N_m"] for size in sizes]
gk = [gs[size]["effective_spring_stiffness_N_m"] for size in sizes]
checks = {
"baseline_impact_measurable": min(baseline) >=
setup["minimum_baseline_peak_force_N"],
"peak_force_reduced_both_meshes": min(reductions) >=
setup["required_relative_peak_force_reduction"],
"stroke_and_rebound_limited": all(
gs[size]["impact"]["maximum_stroke_m"] <=
setup["maximum_impact_stroke_m"] and
gs[size]["impact"]["rebound_speed_m_s"] is not None and
setup["minimum_rebound_speed_m_s"] <=
gs[size]["impact"]["rebound_speed_m_s"] <=
setup["maximum_rebound_speed_m_s"]
for size in sizes),
"contact_observed": all(
bs[size]["impact"]["contact_steps"] > 0 and
gs[size]["impact"]["contact_steps"] > 0
for size in sizes),
"mesh_response_stable": all(
abs(values[1] / values[0] - 1) <=
setup["maximum_relative_mesh_stiffness_change"]
for values in (bk, gk)) and
max(reductions) - min(reductions) <=
setup["maximum_mesh_improvement_spread"],
"mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) <=
setup["maximum_relative_mass_change"],
"end_pads_fixed": ap["end_pad_missing_mm3"] <=
setup["maximum_end_pad_missing_mm3"] and
ap["end_pad_excess_mm3"] <= setup["maximum_end_pad_excess_mm3"],
"envelope_fixed": ap["envelope_excess_mm3"] <=
setup["maximum_envelope_excess_mm3"],
}
after["comparison_to_before"] = {
"relative_peak_force_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"Impact peak force: {baseline} -> {candidate} N")
print(f"Task passed: {all(checks.values())}")
if not all(checks.values()):
raise SystemExit(1)
if __name__ == "__main__":
main()