Download tasks/023/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/023/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/023/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/023/simulate.py
11.2 kB
| """Compare payload acceleration for a STEP-derived isolator spring seat.""" | |
| 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.BRepAdaptor import BRepAdaptor_Surface | |
| 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("Arm volume must be positive") | |
| holes = [] | |
| for face in shape.Faces(): | |
| if face.geomType() != "CYLINDER": | |
| continue | |
| cylinder = BRepAdaptor_Surface(face.wrapped).Cylinder() | |
| axis = cylinder.Axis().Location() | |
| holes.append((cylinder.Radius(), axis.X(), axis.Y())) | |
| fixed = sorted([[x, y] for radius, x, y in holes | |
| if abs(radius - 5) < 1e-5]) | |
| seats = [[x, y] for radius, x, y in holes | |
| if abs(radius - 3) < 1e-5] | |
| if len(fixed) != 2 or len(seats) != 1: | |
| raise ValueError("Expected two 5 mm interface bores and one 3 mm spring seat") | |
| bounds = shape.BoundingBox() | |
| inertia = props.MatrixOfInertia() | |
| density = setup["material_density_kg_m3"] | |
| bores = [cq.Solid.makeCylinder(5, 10, cq.Vector(x, y, -5)) | |
| for x, y in ((0, 0), (100, 0))] | |
| return { | |
| "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), | |
| "volume_mm3": props.Mass(), | |
| "arm_mass_kg": props.Mass() * density * 1e-9, | |
| "arm_center_of_mass_m": [value / 1000 for value in props.CentreOfMass().Coord()], | |
| "arm_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], | |
| "fixed_hole_centers_mm": fixed, | |
| "spring_seat_center_mm": seats[0], | |
| "fixed_bore_intrusion_mm3": sum(shape.intersect(bore).Volume() | |
| for bore in bores), | |
| } | |
| def dynamics(properties: dict, setup: dict) -> dict: | |
| import pychrono as ch | |
| pivot = [value / 1000 for value in properties["fixed_hole_centers_mm"][0]] | |
| payload = [value / 1000 for value in properties["fixed_hole_centers_mm"][1]] | |
| seat = [value / 1000 for value in properties["spring_seat_center_mm"]] | |
| payload = [payload[i] - pivot[i] for i in (0, 1)] | |
| seat = [seat[i] - pivot[i] for i in (0, 1)] | |
| arm_center = properties["arm_center_of_mass_m"] | |
| arm_center = [arm_center[i] - (pivot[i] if i < 2 else 0) | |
| for i in range(3)] | |
| arm_mass = properties["arm_mass_kg"] | |
| payload_mass = setup["payload_mass_kg"] | |
| total_mass = arm_mass + payload_mass | |
| combined_center = [ | |
| (arm_mass * arm_center[i] + payload_mass * | |
| (payload[i] if i < 2 else 0)) / total_mass | |
| for i in range(3) | |
| ] | |
| inertia = [row[:] for row in properties["arm_inertia_tensor_kg_m2"]] | |
| for mass, point in ((arm_mass, arm_center), | |
| (payload_mass, [payload[0], payload[1], 0])): | |
| delta = [point[i] - combined_center[i] for i in range(3)] | |
| length_sq = sum(value * value for value in delta) | |
| for i in range(3): | |
| for j in range(3): | |
| inertia[i][j] += mass * ((length_sq if i == j else 0) - | |
| delta[i] * delta[j]) | |
| preload = setup["spring_preload_N"] | |
| stiffness = setup["spring_stiffness_N_m"] | |
| gravity = setup["gravity_m_s2"] | |
| def balance(angle: float) -> float: | |
| cosine, sine = math.cos(angle), math.sin(angle) | |
| seat_x = seat[0] * cosine - seat[1] * sine | |
| seat_y = seat[0] * sine + seat[1] * cosine | |
| center_x = combined_center[0] * cosine - combined_center[1] * sine | |
| return (seat_x * (preload - stiffness * seat_y) - | |
| total_mass * gravity * center_x) | |
| lower, upper = -0.8, 0.3 | |
| low_value, high_value = balance(lower), balance(upper) | |
| if low_value * high_value >= 0: | |
| raise ValueError("No stable spring equilibrium in the allowed angle range") | |
| for _ in range(60): | |
| middle = (lower + upper) / 2 | |
| if balance(middle) * low_value > 0: | |
| lower, low_value = middle, balance(middle) | |
| else: | |
| upper = middle | |
| equilibrium = (lower + upper) / 2 | |
| static_payload_y = (payload[0] * math.sin(equilibrium) + | |
| payload[1] * math.cos(equilibrium)) | |
| static_sag = -static_payload_y | |
| 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") | |
| results = {} | |
| for frequency in setup["base_frequencies_hz"]: | |
| system = ch.ChSystemNSC() | |
| system.SetGravitationalAcceleration(ch.ChVector3d(0, -gravity, 0)) | |
| ground = ch.ChBody() | |
| ground.SetFixed(True) | |
| system.Add(ground) | |
| arm = ch.ChBody() | |
| arm.SetMass(total_mass) | |
| tensor = ch.ChMatrix33d() | |
| tensor.SetMatr(inertia) | |
| arm.SetInertia(tensor) | |
| arm.SetRot(ch.QuatFromAngleAxis(equilibrium, ch.VECT_Z)) | |
| arm.SetPos(ch.ChVector3d( | |
| combined_center[0] * math.cos(equilibrium) - | |
| combined_center[1] * math.sin(equilibrium), | |
| combined_center[0] * math.sin(equilibrium) + | |
| combined_center[1] * math.cos(equilibrium), combined_center[2])) | |
| system.Add(arm) | |
| hinge = ch.ChLinkLockRevolute() | |
| hinge.Initialize(arm, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) | |
| system.Add(hinge) | |
| spring = ch.ChForce() | |
| arm.AddForce(spring) | |
| spring.SetMode(ch.ChForce.FORCE) | |
| spring.SetDir(ch.ChVector3d(0, 1, 0)) | |
| accelerations = [] | |
| base_speed = 2 * math.pi * frequency | |
| for i in range(steps): | |
| t = i * dt | |
| seat_world = arm.TransformPointLocalToParent(ch.ChVector3d( | |
| seat[0] - combined_center[0], seat[1] - combined_center[1], | |
| -combined_center[2])) | |
| angular_speed = arm.GetAngVelParent().z | |
| base_y = setup["base_amplitude_m"] * math.sin(base_speed * t) | |
| base_v = setup["base_amplitude_m"] * base_speed * math.cos(base_speed * t) | |
| force = (preload + stiffness * (base_y - seat_world.y) + | |
| setup["spring_damping_N_s_m"] * | |
| (base_v - angular_speed * seat_world.x)) | |
| spring.SetVpoint(seat_world) | |
| spring.SetMforce(force) | |
| system.DoStepDynamics(dt) | |
| if t >= setup["response_discard_s"]: | |
| payload_world = arm.TransformPointLocalToParent(ch.ChVector3d( | |
| payload[0] - combined_center[0], | |
| payload[1] - combined_center[1], -combined_center[2])) | |
| omega = arm.GetAngVelParent().z | |
| alpha = arm.GetAngAccParent().z | |
| accelerations.append(alpha * payload_world.x - | |
| omega * omega * payload_world.y) | |
| if not accelerations or not all(math.isfinite(x) for x in accelerations): | |
| raise ValueError("Nonfinite or empty isolator acceleration trace") | |
| results[str(frequency)] = math.sqrt( | |
| sum(value * value for value in accelerations) / len(accelerations)) | |
| return {"static_sag_m": static_sag, | |
| "equilibrium_angle_rad": equilibrium, | |
| "rms_payload_acceleration_m_s2_by_hz": 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, 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"] | |
| before_acc = bs["rms_payload_acceleration_m_s2_by_hz"] | |
| after_acc = gs["rms_payload_acceleration_m_s2_by_hz"] | |
| checks = { | |
| "baseline_excited": min(before_acc.values()) | |
| >= setup["minimum_baseline_rms_acceleration_m_s2"], | |
| "acceleration_reduced_all_frequencies": all( | |
| after_acc[key] <= value * | |
| (1 - setup["required_relative_rms_acceleration_reduction"]) | |
| for key, value in before_acc.items()), | |
| "static_sag_limited": 0 <= gs["static_sag_m"] | |
| <= setup["maximum_static_sag_m"], | |
| "mass_fixed": abs(ap["arm_mass_kg"] / bp["arm_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"])), | |
| "fixed_holes_intact": all( | |
| math.hypot(a[0] - b[0], a[1] - b[1]) | |
| <= setup["maximum_fixed_hole_shift_mm"] | |
| for a, b in zip(ap["fixed_hole_centers_mm"], | |
| bp["fixed_hole_centers_mm"])), | |
| "fixed_bores_clear": ap["fixed_bore_intrusion_mm3"] | |
| <= setup["maximum_fixed_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"RMS payload acceleration: {before_acc} -> {after_acc}") | |
| print(f"Gold static sag: {gs['static_sag_m']} m") | |
| print(f"Task passed: {after['comparison_to_before']['passed']}") | |
| if not after["comparison_to_before"]["passed"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |