Download tasks/045/simulate.py from OrlaLabs/PhyCAD-Bench: direct link, hf CLI and curl.
- Browser
- Download file 8.9 kB
-
https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/045/simulate.py
- Command line
-
hf download hf://datasets/OrlaLabs/PhyCAD-Bench/tasks/045/simulate.py
-
curl -L -o simulate.py https://huggingface.co/datasets/OrlaLabs/PhyCAD-Bench/resolve/main/tasks/045/simulate.py
8.9 kB
| """Mirror a STEP finger and test cylindrical payload retention.""" | |
| 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 | |
| shape = cq.importers.importStep(str(step)).val() | |
| if shape.ShapeType() != "Solid" or len(shape.Solids()) != 1 or not shape.isValid(): | |
| raise ValueError("Expected one valid gripper finger solid") | |
| mount = cq.Solid.makeBox(5, 50, 60, cq.Vector(-40, -25, -30)) | |
| envelope = cq.Solid.makeBox(30, 50, 60, cq.Vector(-40, -25, -30)) | |
| vertices, faces = shape.tessellate(setup["cad_tessellation_tolerance_mm"]) | |
| if len(vertices) < 8 or len(faces) < 12: | |
| raise ValueError("Finger tessellation is incomplete") | |
| return { | |
| "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), | |
| "volume_mm3": shape.Volume(), | |
| "mount_missing_mm3": max(0.0, mount.Volume() - mount.intersect(shape).Volume()), | |
| "envelope_excess_mm3": max(0.0, shape.Volume() - | |
| shape.intersect(envelope).Volume()), | |
| "collision_mesh": { | |
| "vertices": [[axis / 1000 for axis in point.toTuple()] | |
| for point in vertices], | |
| "faces": faces, | |
| }, | |
| } | |
| def dynamics(collision_mesh: dict, setup: dict) -> dict: | |
| import pychrono as ch | |
| mesh = ch.ChTriangleMeshConnected() | |
| vertices = [ch.ChVector3d(*point) for point in collision_mesh["vertices"]] | |
| for a, b, c in collision_mesh["faces"]: | |
| mesh.AddTriangle(vertices[a], vertices[b], vertices[c]) | |
| results = {} | |
| for frequency in setup["shake_frequencies_Hz"]: | |
| system = ch.ChSystemSMC() | |
| system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET) | |
| system.SetGravitationalAcceleration( | |
| ch.ChVector3d(0, 0, -setup["gravity_m_s2"])) | |
| system.SetSolver(ch.ChSolverSparseLU()) | |
| material = ch.ChContactMaterialSMC() | |
| material.SetFriction(setup["contact_friction"]) | |
| material.SetRestitution(0) | |
| material.SetYoungModulus(setup["contact_young_modulus_Pa"]) | |
| jaws = [] | |
| for side in (1, -1): | |
| jaw = ch.ChBody() | |
| jaw.SetFixed(True) | |
| jaw.SetPos(ch.ChVector3d( | |
| side * setup["jaw_preload_offset_m"], 0, 0)) | |
| if side < 0: | |
| jaw.SetRot(ch.QuatFromAngleZ(math.pi)) | |
| jaw.AddCollisionShape(ch.ChCollisionShapeTriangleMesh( | |
| material, mesh, False, False, | |
| setup["collision_thickness_m"])) | |
| jaw.EnableCollision(True) | |
| system.Add(jaw) | |
| jaws.append((jaw, side)) | |
| payload = ch.ChBodyEasyCylinder( | |
| ch.ChAxis_Y, setup["payload_radius_m"], | |
| setup["payload_length_m"], setup["payload_density_kg_m3"], | |
| False, True, material) | |
| payload.SetPos(ch.ChVector3d(0, 0, 0)) | |
| system.Add(payload) | |
| 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 time grid") | |
| peak_jaw_force = 0.0 | |
| maximum_vertical_error = 0.0 | |
| maximum_horizontal_error = 0.0 | |
| jaw_height = 0.0 | |
| for index in range(steps): | |
| time = index * dt | |
| if time < setup["lift_duration_s"]: | |
| fraction = time / setup["lift_duration_s"] | |
| jaw_height = setup["lift_height_m"] * ( | |
| 3 * fraction ** 2 - 2 * fraction ** 3) | |
| jaw_speed = (setup["lift_height_m"] / | |
| setup["lift_duration_s"] * | |
| (6 * fraction - 6 * fraction ** 2)) | |
| else: | |
| elapsed = time - setup["lift_duration_s"] | |
| ramp = min(1.0, elapsed / setup["shake_ramp_duration_s"]) | |
| amplitude = setup["shake_amplitude_m"] * ramp | |
| amplitude_rate = (setup["shake_amplitude_m"] / | |
| setup["shake_ramp_duration_s"] | |
| if ramp < 1 else 0.0) | |
| phase = 2 * math.pi * frequency * elapsed | |
| jaw_height = setup["lift_height_m"] + amplitude * math.sin(phase) | |
| jaw_speed = (amplitude_rate * math.sin(phase) + | |
| amplitude * 2 * math.pi * frequency * math.cos(phase)) | |
| for jaw, side in jaws: | |
| jaw.SetPos(ch.ChVector3d( | |
| side * setup["jaw_preload_offset_m"], 0, jaw_height)) | |
| jaw.SetPosDt(ch.ChVector3d(0, 0, jaw_speed)) | |
| system.DoStepDynamics(dt) | |
| peak_jaw_force = max( | |
| peak_jaw_force, | |
| *(abs(jaw.GetContactForce().x) for jaw, _ in jaws)) | |
| if time >= setup["lift_duration_s"]: | |
| position = payload.GetPos() | |
| maximum_vertical_error = max( | |
| maximum_vertical_error, abs(position.z - jaw_height)) | |
| maximum_horizontal_error = max( | |
| maximum_horizontal_error, | |
| math.hypot(position.x, position.y)) | |
| position = payload.GetPos() | |
| if not all(math.isfinite(value) for value in ( | |
| peak_jaw_force, maximum_vertical_error, | |
| maximum_horizontal_error, position.z)): | |
| raise ValueError("Non-finite gripper trajectory") | |
| results[str(frequency)] = { | |
| "final_payload_height_m": position.z, | |
| "final_jaw_height_m": jaw_height, | |
| "maximum_vertical_tracking_error_m": maximum_vertical_error, | |
| "maximum_horizontal_error_m": maximum_horizontal_error, | |
| "peak_jaw_normal_force_N": peak_jaw_force, | |
| "collision_triangle_count": mesh.GetNumTriangles(), | |
| } | |
| 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["collision_mesh"], 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}) | |
| collision_mesh = properties.pop("collision_mesh") | |
| results[name] = { | |
| "step_properties": properties, | |
| "simulation_result": invoke(args.physics_python, "dynamics", { | |
| "collision_mesh": collision_mesh, "setup": setup}), | |
| } | |
| before, after = results["before"], results["after"] | |
| bp, ap = before["step_properties"], after["step_properties"] | |
| gs = after["simulation_result"] | |
| cases = [str(frequency) for frequency in setup["shake_frequencies_Hz"]] | |
| checks = { | |
| "payload_retained_both_shakes": all( | |
| gs[case]["maximum_vertical_tracking_error_m"] <= | |
| setup["maximum_payload_vertical_error_m"] and | |
| gs[case]["maximum_horizontal_error_m"] <= | |
| setup["maximum_payload_horizontal_error_m"] | |
| for case in cases), | |
| "jaw_force_limited": all( | |
| gs[case]["peak_jaw_normal_force_N"] <= | |
| setup["maximum_peak_jaw_normal_force_N"] for case in cases), | |
| "volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <= | |
| setup["maximum_relative_volume_change"], | |
| "mount_fixed": ap["mount_missing_mm3"] <= | |
| setup["maximum_mount_missing_mm3"], | |
| "envelope_fixed": ap["envelope_excess_mm3"] <= | |
| setup["maximum_envelope_excess_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"Payload tracking errors: {[gs[case]['maximum_vertical_tracking_error_m'] for case in cases]} m") | |
| print(f"Task passed: {all(checks.values())}") | |
| if not all(checks.values()): | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |