"""Measure radial load at two bearings from a STEP-derived rotor.""" 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("Rotor volume must be positive") density = setup["material_density_kg_m3"] inertia = props.MatrixOfInertia() bounds = shape.BoundingBox() radius = setup["shaft_radius_mm"] half_thickness = setup["half_thickness_mm"] bore = cq.Solid.makeCylinder(radius, 2 * half_thickness, cq.Vector(0, 0, -half_thickness)) hub = cq.Solid.makeCylinder(setup["hub_radius_mm"], 2 * half_thickness, cq.Vector(0, 0, -half_thickness)).cut(bore) 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], "bore_intrusion_mm3": shape.intersect(bore).Volume(), "hub_interface_missing_mm3": hub.cut(shape).Volume(), } def dynamics(properties: dict, setup: dict) -> dict: import pychrono as ch cx, cy, cz = (value / 1000 for value in properties["center_of_mass_mm"]) speed = setup["angular_speed_rad_s"] system = ch.ChSystemNSC() system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) rotor = ch.ChBody() rotor.SetMass(properties["mass_kg"]) inertia = ch.ChMatrix33d() inertia.SetMatr(properties["inertia_tensor_kg_m2"]) rotor.SetInertia(inertia) rotor.SetPos(ch.ChVector3d(cx, cy, cz)) rotor.SetLinVel(ch.ChVector3d(-speed * cy, speed * cx, 0)) rotor.SetAngVelParent(ch.ChVector3d(0, 0, speed)) system.Add(rotor) lower = ch.ChLinkLockSpherical() lower.Initialize(rotor, ground, ch.ChFramed(ch.ChVector3d(0, 0, setup["bearing_z_mm"][0] / 1000))) system.Add(lower) upper = ch.ChLinkLockPointLine() upper.Initialize(rotor, ground, ch.ChFramed(ch.ChVector3d(0, 0, setup["bearing_z_mm"][1] / 1000))) system.Add(upper) dt = setup["time_step_s"] steps = round(setup["duration_s"] / dt) settle = round(setup["settling_s"] / dt) if dt <= 0 or steps <= settle or abs(steps * dt - setup["duration_s"]) > 1e-12: raise ValueError("Invalid simulation duration or time step") sums = [0.0, 0.0] count = 0 speeds = [] for i in range(steps): system.DoStepDynamics(dt) if i < settle: continue for j, bearing in enumerate((lower, upper)): force = bearing.GetReaction1().force radial_squared = force.x * force.x + force.y * force.y if not math.isfinite(radial_squared): raise ValueError("Nonfinite bearing reaction") sums[j] += radial_squared speeds.append(rotor.GetAngVelParent().z) count += 1 return { "bearing_rms_radial_load_N": [math.sqrt(value / count) for value in sums], "mean_angular_speed_rad_s": sum(speeds) / count, "maximum_relative_speed_drift": max(abs(value / speed - 1) for value in speeds), "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": invoke(args.physics_python, "dynamics", { "properties": properties, "setup": setup, }), } before = results["before"] after = results["after"] bp = before["step_properties"] ap = after["step_properties"] br = before["simulation_result"]["bearing_rms_radial_load_N"] ar = after["simulation_result"]["bearing_rms_radial_load_N"] target = setup["required_relative_bearing_load_reduction"] envelope = [-setup["outer_radius_mm"], setup["outer_radius_mm"], -setup["outer_radius_mm"], setup["outer_radius_mm"], -setup["half_thickness_mm"], setup["half_thickness_mm"]] checks = { "baseline_load_measurable": min(br) > 0.001, "both_bearing_loads_reduced": all(a <= (1 - target) * b for a, b in zip(ar, br)), "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"], envelope)), "shaft_bore_clear": ap["bore_intrusion_mm3"] <= setup["maximum_bore_intrusion_mm3"], "shaft_interface_intact": ap["hub_interface_missing_mm3"] <= setup["maximum_interface_missing_mm3"], "speed_held": all(result["simulation_result"]["maximum_relative_speed_drift"] <= setup["maximum_relative_speed_drift"] for result in (before, after)), } after["comparison_to_before"] = { "relative_bearing_load_reduction": [1 - a / b for a, b in zip(ar, br)], "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"Bearing RMS radial loads: {br} -> {ar} N") print(f"Task passed: {after['comparison_to_before']['passed']}") if not after["comparison_to_before"]["passed"]: raise SystemExit(1) if __name__ == "__main__": main()