Download tasks/031/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/031/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/031/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/031/simulate.py
11.6 kB
| """Compare two-direction clip stiffness at two mesh resolutions.""" | |
| 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("Clip volume must be positive") | |
| base = cq.Solid.makeBox(20, 40, 10, cq.Vector(0, -20, -5)) | |
| hooks = [cq.Solid.makeBox(10, 10, 10, cq.Vector(80, y, -5)) | |
| for y in (-17, 7)] | |
| fixed_parts = (base, *hooks) | |
| fixed_overlap = sum(part.intersect(shape).Volume() for part in fixed_parts) | |
| slabs = [cq.Solid.makeBox(20, 40, 10, cq.Vector(0, -20, -5)), | |
| cq.Solid.makeBox(10, 40, 10, cq.Vector(80, -20, -5))] | |
| slab_overlap = sum(slab.intersect(shape).Volume() for slab in slabs) | |
| envelope = cq.Solid.makeBox(90, 40, 10, cq.Vector(0, -20, -5)) | |
| result = { | |
| "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), | |
| "volume_mm3": props.Mass(), | |
| "mass_kg": props.Mass() * setup["material_density_kg_m3"] * 1e-9, | |
| "fixed_feature_missing_mm3": max(0.0, | |
| sum(part.Volume() for part in fixed_parts) - fixed_overlap), | |
| "fixed_feature_excess_mm3": max(0.0, slab_overlap - fixed_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("clip") | |
| 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(): | |
| results[size] = {} | |
| for mode in ("insertion", "retention"): | |
| 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"]) | |
| top = [key for key, point in data["nodes"].items() | |
| if abs(point[0] - 0.09) < 1e-8 and point[1] > 0] | |
| bottom = [key for key, point in data["nodes"].items() | |
| if abs(point[0] - 0.09) < 1e-8 and point[1] < 0] | |
| fixed = [key for key, point in data["nodes"].items() | |
| if abs(point[0]) < 1e-8] | |
| if min(len(top), len(bottom), len(fixed)) < 4: | |
| raise ValueError("Mesh is missing a clamp or hook load face") | |
| nodes = {} | |
| for key, point in data["nodes"].items(): | |
| node = fea.ChNodeFEAxyz(ch.ChVector3d(*point)) | |
| if key in fixed: | |
| node.SetFixed(True) | |
| if key in top: | |
| if mode == "insertion": | |
| node.SetForce(ch.ChVector3d( | |
| 0, setup["insertion_probe_force_N"] / | |
| (2 * len(top)), 0)) | |
| else: | |
| node.SetForce(ch.ChVector3d( | |
| -setup["retention_probe_force_N"] / | |
| (2 * len(top)), 0, 0)) | |
| if key in bottom: | |
| if mode == "insertion": | |
| node.SetForce(ch.ChVector3d( | |
| 0, -setup["insertion_probe_force_N"] / | |
| (2 * len(bottom)), 0)) | |
| else: | |
| node.SetForce(ch.ChVector3d( | |
| -setup["retention_probe_force_N"] / | |
| (2 * len(bottom)), 0, 0)) | |
| mesh.AddNode(node) | |
| nodes[int(key)] = node | |
| elements = [] | |
| 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) | |
| elements.append(element) | |
| system.Add(mesh) | |
| system.DoStaticLinear() | |
| if mode == "insertion": | |
| top_motion = sum(nodes[int(key)].GetPos().y - | |
| data["nodes"][key][1] for key in top) / len(top) | |
| bottom_motion = sum(data["nodes"][key][1] - | |
| nodes[int(key)].GetPos().y | |
| for key in bottom) / len(bottom) | |
| probe_displacement = (top_motion + bottom_motion) / 2 | |
| probe_force = setup["insertion_probe_force_N"] | |
| target_stroke = setup["insertion_opening_per_arm_m"] | |
| else: | |
| probe_displacement = -sum( | |
| nodes[int(key)].GetPos().x - data["nodes"][key][0] | |
| for key in top + bottom) / (len(top) + len(bottom)) | |
| probe_force = setup["retention_probe_force_N"] | |
| target_stroke = setup["retention_pull_distance_m"] | |
| if not math.isfinite(probe_displacement) or probe_displacement <= 0: | |
| raise ValueError("Invalid clip compliance") | |
| strain = max(element.GetStrain().GetEquivalentVonMises() | |
| for element in elements) | |
| scale = target_stroke / probe_displacement | |
| results[size][mode] = { | |
| "equivalent_force_N": probe_force * scale, | |
| "probe_displacement_m": probe_displacement, | |
| "scaled_max_strain": strain * scale, | |
| "node_count": len(nodes), | |
| "tetrahedron_count": len(data["tets"]), | |
| "loaded_node_count": len(top) + len(bottom), | |
| } | |
| 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["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"]] | |
| bf = {mode: [bs[size][mode]["equivalent_force_N"] for size in sizes] | |
| for mode in ("insertion", "retention")} | |
| gf = {mode: [gs[size][mode]["equivalent_force_N"] for size in sizes] | |
| for mode in ("insertion", "retention")} | |
| checks = { | |
| "baseline_outside_bands": min(bf["insertion"]) > | |
| setup["maximum_insertion_force_N"] and | |
| min(bf["retention"]) > setup["maximum_retention_force_N"], | |
| "insertion_force_in_band": all( | |
| setup["minimum_insertion_force_N"] <= value <= | |
| setup["maximum_insertion_force_N"] | |
| for value in gf["insertion"]), | |
| "retention_force_in_band": all( | |
| setup["minimum_retention_force_N"] <= value <= | |
| setup["maximum_retention_force_N"] | |
| for value in gf["retention"]), | |
| "elastic_strain_limited": all( | |
| gs[size][mode]["scaled_max_strain"] <= | |
| setup["maximum_equivalent_strain"] | |
| for size in sizes for mode in ("insertion", "retention")), | |
| "mesh_response_stable": all( | |
| abs(values[1] / values[0] - 1) <= | |
| setup["maximum_relative_mesh_force_change"] | |
| for values in (*bf.values(), *gf.values())), | |
| "mass_not_increased": ap["mass_kg"] <= bp["mass_kg"] * | |
| (1 + setup["maximum_relative_mass_increase"]), | |
| "fixed_features_intact": ap["fixed_feature_missing_mm3"] <= | |
| setup["maximum_fixed_feature_missing_mm3"] and | |
| ap["fixed_feature_excess_mm3"] <= | |
| setup["maximum_fixed_feature_excess_mm3"], | |
| "envelope_fixed": ap["envelope_excess_mm3"] <= | |
| setup["maximum_envelope_excess_mm3"], | |
| } | |
| after["comparison_to_before"] = { | |
| "baseline_forces_N": bf, | |
| "candidate_forces_N": gf, | |
| "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"Clip forces: {bf} -> {gf} N") | |
| print(f"Task passed: {all(checks.values())}") | |
| if not all(checks.values()): | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |