File size: 7,373 Bytes
99510bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""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()