File size: 9,863 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
"""Compare release speed for a STEP-derived catapult spring seat."""

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.BRepAdaptor import BRepAdaptor_Surface
    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("Arm volume must be positive")
    holes = []
    for face in shape.Faces():
        if face.geomType() != "CYLINDER":
            continue
        cylinder = BRepAdaptor_Surface(face.wrapped).Cylinder()
        axis = cylinder.Axis().Location()
        holes.append((cylinder.Radius(), axis.X(), axis.Y()))
    fixed = sorted([[x, y] for radius, x, y in holes
                    if abs(radius - 5) < 1e-5])
    seats = [[x, y] for radius, x, y in holes
             if abs(radius - 3) < 1e-5]
    if len(fixed) != 2 or len(seats) != 1:
        raise ValueError("Expected two 5 mm interface bores and one 3 mm spring seat")
    bounds = shape.BoundingBox()
    inertia = props.MatrixOfInertia()
    density = setup["material_density_kg_m3"]
    bores = [cq.Solid.makeCylinder(5, 10, cq.Vector(x, y, -5))
             for x, y in ((0, 0), (100, 0))]
    return {
        "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
        "volume_mm3": props.Mass(),
        "arm_mass_kg": props.Mass() * density * 1e-9,
        "arm_center_of_mass_m": [value / 1000 for value in props.CentreOfMass().Coord()],
        "arm_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],
        "fixed_hole_centers_mm": fixed,
        "spring_seat_center_mm": seats[0],
        "fixed_bore_intrusion_mm3": sum(shape.intersect(bore).Volume()
                                          for bore in bores),
    }


def dynamics(properties: dict, setup: dict) -> dict:
    import pychrono as ch

    pivot = [value / 1000 for value in properties["fixed_hole_centers_mm"][0]]
    payload = [value / 1000 for value in properties["fixed_hole_centers_mm"][1]]
    seat = [value / 1000 for value in properties["spring_seat_center_mm"]]
    payload = [payload[i] - pivot[i] for i in (0, 1)]
    seat = [seat[i] - pivot[i] for i in (0, 1)]
    arm_center = properties["arm_center_of_mass_m"]
    arm_center = [arm_center[i] - (pivot[i] if i < 2 else 0)
                  for i in range(3)]
    arm_mass = properties["arm_mass_kg"]
    payload_mass = setup["payload_mass_kg"]
    total_mass = arm_mass + payload_mass
    combined_center = [
        (arm_mass * arm_center[i] + payload_mass *
         (payload[i] if i < 2 else 0)) / total_mass
        for i in range(3)
    ]
    inertia = [row[:] for row in properties["arm_inertia_tensor_kg_m2"]]
    for mass, point in ((arm_mass, arm_center),
                        (payload_mass, [payload[0], payload[1], 0])):
        delta = [point[i] - combined_center[i] for i in range(3)]
        length_sq = sum(value * value for value in delta)
        for i in range(3):
            for j in range(3):
                inertia[i][j] += mass * ((length_sq if i == j else 0) -
                                          delta[i] * delta[j])

    angle = setup["initial_angle_rad"]
    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")
    system = ch.ChSystemNSC()
    system.SetGravitationalAcceleration(ch.ChVector3d(
        0, -setup["gravity_m_s2"], 0))
    ground = ch.ChBody()
    ground.SetFixed(True)
    system.Add(ground)
    arm = ch.ChBody()
    arm.SetMass(total_mass)
    tensor = ch.ChMatrix33d()
    tensor.SetMatr(inertia)
    arm.SetInertia(tensor)
    arm.SetRot(ch.QuatFromAngleAxis(angle, ch.VECT_Z))
    arm.SetPos(ch.ChVector3d(
        combined_center[0] * math.cos(angle) -
        combined_center[1] * math.sin(angle),
        combined_center[0] * math.sin(angle) +
        combined_center[1] * math.cos(angle), combined_center[2]))
    system.Add(arm)
    hinge = ch.ChLinkLockRevolute()
    hinge.Initialize(arm, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0)))
    system.Add(hinge)
    spring = ch.ChForce()
    arm.AddForce(spring)
    spring.SetMode(ch.ChForce.FORCE)
    spring.SetDir(ch.ChVector3d(0, 1, 0))
    damper = ch.ChForce()
    arm.AddForce(damper)
    damper.SetMode(ch.ChForce.TORQUE)
    damper.SetDir(ch.ChVector3d(0, 0, 1))
    peak_reaction = 0.0
    for i in range(steps):
        seat_world = arm.TransformPointLocalToParent(ch.ChVector3d(
            seat[0] - combined_center[0], seat[1] - combined_center[1],
            -combined_center[2]))
        spring.SetVpoint(seat_world)
        spring.SetMforce(setup["spring_preload_N"] -
                         setup["spring_stiffness_N_m"] * seat_world.y)
        damper.SetMforce(-setup["pivot_damping_N_m_s_rad"] *
                         arm.GetAngVelParent().z)
        system.DoStepDynamics(dt)
        omega = arm.GetAngVelParent().z
        angle += omega * dt
        reaction = hinge.GetReaction1().force
        peak_reaction = max(peak_reaction,
                            math.hypot(reaction.x, reaction.y))
        if not math.isfinite(angle) or not math.isfinite(peak_reaction):
            raise ValueError("Nonfinite catapult dynamics")
        if angle >= setup["release_angle_rad"]:
            return {
                "release_time_s": (i + 1) * dt,
                "release_speed_m_s": math.hypot(*payload) * abs(omega),
                "peak_pivot_reaction_N": peak_reaction,
            }
    return {"release_time_s": None, "release_speed_m_s": 0.0,
            "peak_pivot_reaction_N": peak_reaction}


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_releases": bs["release_time_s"] is not None and
        bs["release_speed_m_s"] >= setup["minimum_baseline_release_speed_m_s"],
        "release_speed_increased": gs["release_time_s"] is not None and
        gs["release_speed_m_s"] >= bs["release_speed_m_s"] *
        (1 + setup["required_relative_release_speed_gain"]),
        "pivot_reaction_limited": gs["peak_pivot_reaction_N"] <=
        setup["maximum_peak_pivot_reaction_N"],
        "mass_fixed": abs(ap["arm_mass_kg"] / bp["arm_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"])),
        "fixed_holes_intact": all(
            math.hypot(a[0] - b[0], a[1] - b[1])
            <= setup["maximum_fixed_hole_shift_mm"]
            for a, b in zip(ap["fixed_hole_centers_mm"],
                            bp["fixed_hole_centers_mm"])),
        "fixed_bores_clear": ap["fixed_bore_intrusion_mm3"]
        <= setup["maximum_fixed_bore_intrusion_mm3"],
        "spring_seat_inside_allowed_span":
        setup["minimum_spring_seat_x_mm"] <=
        ap["spring_seat_center_mm"][0] <=
        setup["maximum_spring_seat_x_mm"] and
        abs(ap["spring_seat_center_mm"][1]) <=
        setup["maximum_spring_seat_y_mm"],
    }
    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"Release speed: {bs['release_speed_m_s']} -> "
          f"{gs['release_speed_m_s']} m/s")
    print(f"Peak pivot reaction: {gs['peak_pivot_reaction_N']} N")
    print(f"Task passed: {after['comparison_to_before']['passed']}")
    if not after["comparison_to_before"]["passed"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()