File size: 9,803 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
"""Test holding and release torque of a CAD-derived over-center clamp."""

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("Lever 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])
    spring_pins = [[x, y] for radius, x, y in holes
                   if abs(radius - 3) < 1e-5]
    if len(fixed) != 2 or len(spring_pins) != 1:
        raise ValueError("Expected two 5 mm fixed bores and one 3 mm spring pin bore")
    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), (80, 0))]
    anchor_x, anchor_y = setup["spring_anchor_m"]
    pin_x, pin_y = (spring_pins[0][0] / 1000,
                    spring_pins[0][1] / 1000)
    overcenter_angle = (math.atan2(anchor_y, anchor_x) -
                        math.atan2(pin_y, pin_x))
    margin = math.radians(setup["closed_angle_deg"]) - overcenter_angle
    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],
        "fixed_pin_centers_mm": fixed,
        "spring_pin_center_mm": spring_pins[0],
        "overcenter_margin_rad": margin,
        "fixed_bore_intrusion_mm3": sum(shape.intersect(bore).Volume()
                                          for bore in bores),
    }


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

    center = [value / 1000 for value in properties["center_of_mass_mm"]]
    pin = [(properties["spring_pin_center_mm"][i] / 1000 - center[i])
           for i in (0, 1)]
    closed = math.radians(setup["closed_angle_deg"])
    anchor_x, anchor_y = setup["spring_anchor_m"]
    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")
    results = {}
    for release, name in ((False, "hold"), (True, "release")):
        system = ch.ChSystemNSC()
        system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
        ground = ch.ChBody()
        ground.SetFixed(True)
        system.Add(ground)
        lever = ch.ChBody()
        lever.SetMass(properties["mass_kg"])
        inertia = ch.ChMatrix33d()
        inertia.SetMatr(properties["inertia_tensor_kg_m2"])
        lever.SetInertia(inertia)
        lever.SetRot(ch.QuatFromAngleAxis(closed, ch.VECT_Z))
        lever.SetPos(ch.ChVector3d(
            center[0] * math.cos(closed) - center[1] * math.sin(closed),
            center[0] * math.sin(closed) + center[1] * math.cos(closed), center[2]))
        system.Add(lever)
        hinge = ch.ChLinkLockRevolute()
        hinge.Initialize(lever, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0)))
        system.Add(hinge)
        spring = ch.ChForce()
        lever.AddForce(spring)
        spring.SetMode(ch.ChForce.FORCE)
        spring.SetMforce(setup["spring_force_N"])
        load = ch.ChForce()
        lever.AddForce(load)
        load.SetMode(ch.ChForce.TORQUE)
        load.SetDir(ch.ChVector3d(0, 0, 1))
        stop = ch.ChForce()
        lever.AddForce(stop)
        stop.SetMode(ch.ChForce.TORQUE)
        stop.SetDir(ch.ChVector3d(0, 0, 1))
        angle = closed
        minimum_angle = closed
        maximum_reaction = 0.0
        for i in range(steps):
            pin_world = lever.TransformPointLocalToParent(ch.ChVector3d(
                pin[0], pin[1], -center[2]))
            dx, dy = pin_world.x - anchor_x, pin_world.y - anchor_y
            distance = math.hypot(dx, dy)
            if distance <= 1e-6:
                raise ValueError("Spring pin coincides with fixed spring anchor")
            spring.SetVpoint(pin_world)
            spring.SetDir(ch.ChVector3d(dx / distance, dy / distance, 0))
            pulse = (setup["release_pulse_torque_N_m"]
                     if release and i * dt < setup["release_pulse_s"] else 0)
            load.SetMforce(-setup["opening_load_torque_N_m"] - pulse)
            stop.SetMforce(-setup["stop_stiffness_N_m_rad"] *
                           max(0, angle - closed) -
                           setup["stop_damping_N_m_s_rad"] *
                           lever.GetAngVelParent().z)
            system.DoStepDynamics(dt)
            angle += lever.GetAngVelParent().z * dt
            minimum_angle = min(minimum_angle, angle)
            reaction = hinge.GetReaction1().force
            maximum_reaction = max(maximum_reaction,
                                   math.hypot(reaction.x, reaction.y))
        if not math.isfinite(angle + maximum_reaction):
            raise ValueError("Nonfinite clamp trajectory")
        results[name] = {"minimum_angle_rad": minimum_angle,
                         "end_angle_rad": angle,
                         "maximum_pivot_reaction_N": maximum_reaction}
    return results


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_opens_under_load": bs["hold"]["minimum_angle_rad"]
        <= setup["maximum_baseline_held_angle_rad"],
        "closed_position_held": gs["hold"]["minimum_angle_rad"]
        >= setup["minimum_held_angle_rad"],
        "release_travel_kept": gs["release"]["end_angle_rad"]
        <= setup["maximum_released_angle_rad"],
        "overcenter_margin": ap["overcenter_margin_rad"]
        >= setup["minimum_overcenter_margin_rad"],
        "pivot_reaction_limited": max(
            result["maximum_pivot_reaction_N"] for result in gs.values())
        <= setup["maximum_pivot_reaction_N"],
        "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"])),
        "fixed_pins_intact": all(math.hypot(a[0] - b[0], a[1] - b[1])
                                 <= setup["maximum_fixed_pin_shift_mm"]
                                 for a, b in zip(ap["fixed_pin_centers_mm"],
                                                 bp["fixed_pin_centers_mm"])),
        "fixed_bores_clear": ap["fixed_bore_intrusion_mm3"]
        <= setup["maximum_fixed_bore_intrusion_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"Minimum hold angle: {bs['hold']['minimum_angle_rad']} -> "
          f"{gs['hold']['minimum_angle_rad']} rad")
    print(f"Gold release end angle: {gs['release']['end_angle_rad']} rad")
    print(f"Task passed: {after['comparison_to_before']['passed']}")
    if not after["comparison_to_before"]["passed"]:
        raise SystemExit(1)


if __name__ == "__main__":
    main()