"""Measure both STEP blocks and test tipping under the same sideways load.""" 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, density: float) -> 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(): raise ValueError(f"Expected one valid solid: {step}") props = GProp_GProps() BRepGProp.VolumeProperties_s(shape.wrapped, props) box = shape.BoundingBox() inertia = props.MatrixOfInertia() return { "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), "volume_mm3": props.Mass(), "mass_kg": props.Mass() * density * 1e-9, "width_mm": box.xlen, "height_mm": box.ylen, "depth_mm": box.zlen, "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) ], } def dynamics(p: dict, setup: dict) -> dict: import pychrono as ch if max(abs(v) for v in p["center_of_mass_mm"]) > 1e-6: raise ValueError("Block must be centered on the origin") width = p["width_mm"] / 1000 height = p["height_mm"] / 1000 system = ch.ChSystemNSC() system.SetGravitationalAcceleration(ch.ChVector3d(0, -setup["gravity_m_s2"], 0)) floor = ch.ChBody() floor.SetFixed(True) system.Add(floor) block = ch.ChBody() block.SetMass(p["mass_kg"]) inertia = ch.ChMatrix33d() inertia.SetMatr(p["inertia_tensor_kg_m2"]) block.SetInertia(inertia) block.SetPos(ch.ChVector3d(-width / 2, height / 2, 0)) system.Add(block) # The right bottom edge is the pivot. The one-sided limit represents the # floor preventing rotation into it, while allowing clockwise tipping. hinge = ch.ChLinkLockRevolute() hinge.Initialize(block, floor, ch.ChFramed(ch.ChVector3d(0, 0, 0))) limit = hinge.LimitRz() limit.SetActive(True) limit.SetMin(-math.pi) limit.SetMax(0) system.Add(hinge) # Apply a world-horizontal force at the top of the measured STEP block. force = ch.ChForce() block.AddForce(force) force.SetMode(ch.ChForce.FORCE) force.SetAlign(ch.ChForce.WORLD_DIR) force.SetDir(ch.ChVector3d(1, 0, 0)) force.SetVrelpoint(ch.ChVector3d(0, height / 2, 0)) force.SetMforce(setup["sideways_force_at_top_N"]) 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("Duration must contain whole time steps") greatest = 0.0 tip_time = None for i in range(1, steps + 1): system.DoStepDynamics(dt) q = block.GetRot() angle = -math.degrees(2 * math.atan2(q.e3, q.e0)) if not math.isfinite(angle): raise ValueError("Nonfinite tipping angle") greatest = max(greatest, angle) if angle >= setup["tip_angle_deg"]: tip_time = i * dt break return { "tipped_within_window": tip_time is not None, "time_to_tip_s": tip_time, "maximum_tip_angle_deg": greatest, "steps_run": i, } 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}") 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) print(json.dumps( measure(Path(payload["step"]), payload["density"]) if args.phase == "measure" else dynamics(payload["properties"], payload["setup"]) )) return setup_path = ROOT / "setup.json" setup = json.loads(setup_path.read_text()) hashes = { "setup_sha256": hashlib.sha256(setup_path.read_bytes()).hexdigest(), "simulation_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "engine": setup["engine"], "engine_version": setup["engine_version"], } results = {} for name in ("before", "after"): step = ROOT / f"{name}.step" p = invoke(args.cad_python, "measure", { "step": str(step), "density": setup["material_density_kg_m3"], }) results[name] = { "step": step.name, "setup": "setup.json", "simulation": "simulate.py", "step_properties": p, "simulation_result": invoke(args.physics_python, "dynamics", { "properties": p, "setup": setup, }), "provenance": hashes, } b, a = results["before"], results["after"] bp, ap = b["step_properties"], a["step_properties"] checks = { "before_tips": b["simulation_result"]["tipped_within_window"], "after_resists_tip": not a["simulation_result"]["tipped_within_window"], "mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) <= setup["maximum_relative_mass_change"], } a["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"Tipped within {setup['duration_s']} s: " f"{b['simulation_result']['tipped_within_window']} -> " f"{a['simulation_result']['tipped_within_window']}" ) print(f"Task passed: {a['comparison_to_before']['passed']}") if not a["comparison_to_before"]["passed"]: raise SystemExit(1) if __name__ == "__main__": main()