"""Score a three-ball batch through a STEP-derived gravity chute.""" 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 not shape.isValid() or len(shape.Solids()) != 1: raise ValueError(f"Expected one valid solid: {step}") bounds = shape.BoundingBox() envelope = cq.Solid.makeBox(300, 150, 60, cq.Vector(-150, -150, -30)) floor = cq.Solid.makeBox(300, 10, 60, cq.Vector(-150, -150, -30)) mounts = [cq.Solid.makeBox(10, 150, 60, cq.Vector(x, -150, -30)) for x in (-150, 140)] vertices, faces = shape.tessellate(1.0) if not vertices or not faces: raise ValueError("STEP tessellation has no triangles") return { "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), "volume_mm3": shape.Volume(), "mass_kg": shape.Volume() * setup["material_density_kg_m3"] * 1e-9, "bounds_mm": [bounds.xmin, bounds.xmax, bounds.ymin, bounds.ymax, bounds.zmin, bounds.zmax], "external_added_mm3": shape.cut(envelope).Volume(), "floor_missing_mm3": floor.cut(shape).Volume(), "mount_missing_mm3": sum(mount.cut(shape).Volume() for mount in mounts), "collision_vertices_m": [[v.x / 1000, v.y / 1000, v.z / 1000] for v in vertices], "collision_triangles": faces, } def dynamics(properties: dict, setup: dict) -> dict: import pychrono as ch ch.ChCollisionModel.SetDefaultSuggestedEnvelope(1e-5) ch.ChCollisionModel.SetDefaultSuggestedMargin(1e-5) system = ch.ChSystemNSC() system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET) system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 0)) material = ch.ChContactMaterialNSC() material.SetFriction(setup["contact_friction"]) material.SetRestitution(setup["contact_restitution"]) mesh = ch.ChTriangleMeshConnected() vertices = properties["collision_vertices_m"] for a, b, c in properties["collision_triangles"]: mesh.AddTriangle(ch.ChVector3d(*vertices[a]), ch.ChVector3d(*vertices[b]), ch.ChVector3d(*vertices[c])) chute = ch.ChBody() chute.SetFixed(True) chute.AddCollisionShape(ch.ChCollisionShapeTriangleMesh( material, mesh, True, False, 0)) chute.EnableCollision(True) system.Add(chute) balls = [] for x, y in setup["release_positions_m"]: ball = ch.ChBodyEasySphere(setup["ball_radius_m"], setup["ball_density_kg_m3"], False, True, material) ball.SetPos(ch.ChVector3d(x, y, 0)) system.Add(ball) planar = ch.ChLinkMateGeneric() planar.SetConstrainedCoords(False, False, True, False, False, False) planar.Initialize(ball, chute, ch.ChFramed(ch.ChVector3d(x, y, 0))) system.Add(planar) balls.append(ball) 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") passage_times = [None] * len(balls) nearby_ball_steps = 0 for i in range(steps): system.DoStepDynamics(dt) positions = [ball.GetPos() for ball in balls] if not all(math.isfinite(pos.x + pos.y) for pos in positions): raise ValueError("Nonfinite ball trajectory") for j, pos in enumerate(positions): if pos.y <= setup["collection_y_m"] and passage_times[j] is None: passage_times[j] = (i + 1) * dt if any(math.hypot(a.x - b.x, a.y - b.y) <= 2 * setup["ball_radius_m"] + 0.001 for n, a in enumerate(positions) for b in positions[n + 1:]): nearby_ball_steps += 1 if all(value is not None for value in passage_times): break return { "passage_times_s": passage_times, "passed_count": sum(value is not None for value in passage_times), "nearby_ball_steps": nearby_ball_steps, "final_positions_m": [[pos.x, pos.y] for pos in positions], } 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"] checks = { "baseline_jams": bs["passed_count"] == 0, "whole_batch_passes": all(value is not None and value <= setup["maximum_passage_time_s"] for value in gs["passage_times_s"]), "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"])), "outer_envelope_kept": ap["external_added_mm3"] <= setup["maximum_external_added_mm3"], "bottom_floor_intact": ap["floor_missing_mm3"] <= setup["maximum_floor_missing_mm3"], "side_mounts_intact": ap["mount_missing_mm3"] <= setup["maximum_mount_missing_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"Balls passing chute: {bs['passed_count']} -> {gs['passed_count']}") print(f"Task passed: {after['comparison_to_before']['passed']}") if not after["comparison_to_before"]["passed"]: raise SystemExit(1) if __name__ == "__main__": main()