Download tasks/009/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 8.91 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/009/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/009/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/009/simulate.py
8.91 kB
| """Measure target speed after a STEP-derived striker impact.""" | |
| 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("Striker volume must be positive") | |
| density = setup["material_density_kg_m3"] | |
| inertia = props.MatrixOfInertia() | |
| bounds = shape.BoundingBox() | |
| outer = cq.Workplane("XY").box(20, 95, 10).translate((0, 37.5, 0)) | |
| bore = cq.Workplane("XY").circle(5).extrude(12).translate((0, 0, -6)) | |
| exterior = outer.cut(bore).val() | |
| if len(exterior.Solids()) == 1: | |
| exterior = exterior.Solids()[0] | |
| allowed = cq.Solid.makeBox(17, 71, 9, cq.Vector(-8.5, 7, -4.5)) | |
| vertices, _ = shape.tessellate(0.25) | |
| 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(exterior).Volume(), | |
| "exterior_removed_mm3": exterior.cut(shape).cut(allowed).Volume(), | |
| "collision_vertices_mm": [[v.x, v.y, v.z] for v in 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 = -math.sqrt(2 * setup["initial_rotational_energy_J"] / pivot_inertia) | |
| angle = math.radians(setup["initial_angle_deg"]) | |
| 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) | |
| striker = ch.ChBody() | |
| striker.SetMass(mass) | |
| inertia = ch.ChMatrix33d() | |
| inertia.SetMatr(inertia_tensor) | |
| striker.SetInertia(inertia) | |
| striker.SetRot(ch.QuatFromAngleAxis(angle, ch.VECT_Z)) | |
| striker.SetPos(ch.ChVector3d(*pivot_to_center, center[2])) | |
| striker.SetAngVelParent(ch.ChVector3d(0, 0, speed)) | |
| striker.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])) | |
| striker.AddCollisionShape(ch.ChCollisionShapeConvexHull(material, points)) | |
| striker.EnableCollision(True) | |
| system.Add(striker) | |
| hinge = ch.ChLinkLockRevolute() | |
| hinge.Initialize(striker, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) | |
| system.Add(hinge) | |
| size = setup["target_size_m"] | |
| target = ch.ChBodyEasyBox( | |
| *size, setup["target_mass_kg"] / (size[0] * size[1] * size[2]), | |
| False, True, material) | |
| target.SetPos(ch.ChVector3d(*setup["target_center_m"])) | |
| system.Add(target) | |
| guide = ch.ChLinkLockPrismatic() | |
| guide.Initialize(target, ground, ch.ChFramed( | |
| ch.ChVector3d(*setup["target_center_m"]), | |
| ch.QuatFromAngleAxis(math.pi / 2, ch.VECT_Y))) | |
| system.Add(guide) | |
| 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 | |
| for _ in range(steps): | |
| system.DoStepDynamics(dt) | |
| if target.GetContactForce().Length() > 1e-8: | |
| contact_steps += 1 | |
| final_speed = target.GetLinVel().x | |
| if not math.isfinite(final_speed): | |
| raise ValueError("Nonfinite target speed") | |
| return { | |
| "target_final_speed_m_s": final_speed, | |
| "contact_steps": contact_steps, | |
| "initial_striker_angular_speed_rad_s": speed, | |
| "initial_striker_energy_J": 0.5 * pivot_inertia * speed * 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": { | |
| "runs": [invoke(args.physics_python, "dynamics", { | |
| "properties": properties, | |
| "setup": {**setup, "target_center_m": [x, *setup["target_center_m"][1:]]}, | |
| }) for x in setup["target_center_x_cases_m"]], | |
| }, | |
| } | |
| before = results["before"] | |
| after = results["after"] | |
| bp = before["step_properties"] | |
| ap = after["step_properties"] | |
| bruns = before["simulation_result"]["runs"] | |
| aruns = after["simulation_result"]["runs"] | |
| baseline = [run["target_final_speed_m_s"] for run in bruns] | |
| candidate = [run["target_final_speed_m_s"] for run in aruns] | |
| checks = { | |
| "baseline_impact_measurable": all(speed > 0.01 for speed in baseline), | |
| "target_speed_gain": all(a >= b * | |
| (1 + setup["required_relative_target_speed_gain"]) | |
| for a, b in zip(candidate, baseline)), | |
| "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"])), | |
| "pivot_and_strike_surface_fixed": ap["external_added_mm3"] | |
| <= setup["maximum_external_added_mm3"] | |
| and ap["exterior_removed_mm3"] <= setup["maximum_exterior_removed_mm3"], | |
| "centered_on_swing_plane": max(abs(ap["center_of_mass_mm"][i]) | |
| for i in (0, 2)) | |
| <= setup["maximum_center_xz_offset_mm"], | |
| "target_contact_observed": all(run["contact_steps"] > 0 | |
| for run in (*bruns, *aruns)), | |
| } | |
| after["comparison_to_before"] = { | |
| "target_center_x_cases_m": setup["target_center_x_cases_m"], | |
| "relative_target_speed_gain": [a / b - 1 for a, b in zip(candidate, baseline)], | |
| "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"Target speed: {baseline} -> {candidate} m/s") | |
| print(f"Task passed: {after['comparison_to_before']['passed']}") | |
| if not after["comparison_to_before"]["passed"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |