File size: 8,899 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
"""Mirror a STEP finger and test cylindrical payload retention."""

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

    shape = cq.importers.importStep(str(step)).val()
    if shape.ShapeType() != "Solid" or len(shape.Solids()) != 1 or not shape.isValid():
        raise ValueError("Expected one valid gripper finger solid")
    mount = cq.Solid.makeBox(5, 50, 60, cq.Vector(-40, -25, -30))
    envelope = cq.Solid.makeBox(30, 50, 60, cq.Vector(-40, -25, -30))
    vertices, faces = shape.tessellate(setup["cad_tessellation_tolerance_mm"])
    if len(vertices) < 8 or len(faces) < 12:
        raise ValueError("Finger tessellation is incomplete")
    return {
        "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
        "volume_mm3": shape.Volume(),
        "mount_missing_mm3": max(0.0, mount.Volume() - mount.intersect(shape).Volume()),
        "envelope_excess_mm3": max(0.0, shape.Volume() -
                                   shape.intersect(envelope).Volume()),
        "collision_mesh": {
            "vertices": [[axis / 1000 for axis in point.toTuple()]
                         for point in vertices],
            "faces": faces,
        },
    }


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

    mesh = ch.ChTriangleMeshConnected()
    vertices = [ch.ChVector3d(*point) for point in collision_mesh["vertices"]]
    for a, b, c in collision_mesh["faces"]:
        mesh.AddTriangle(vertices[a], vertices[b], vertices[c])
    results = {}
    for frequency in setup["shake_frequencies_Hz"]:
        system = ch.ChSystemSMC()
        system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
        system.SetGravitationalAcceleration(
            ch.ChVector3d(0, 0, -setup["gravity_m_s2"]))
        system.SetSolver(ch.ChSolverSparseLU())
        material = ch.ChContactMaterialSMC()
        material.SetFriction(setup["contact_friction"])
        material.SetRestitution(0)
        material.SetYoungModulus(setup["contact_young_modulus_Pa"])
        jaws = []
        for side in (1, -1):
            jaw = ch.ChBody()
            jaw.SetFixed(True)
            jaw.SetPos(ch.ChVector3d(
                side * setup["jaw_preload_offset_m"], 0, 0))
            if side < 0:
                jaw.SetRot(ch.QuatFromAngleZ(math.pi))
            jaw.AddCollisionShape(ch.ChCollisionShapeTriangleMesh(
                material, mesh, False, False,
                setup["collision_thickness_m"]))
            jaw.EnableCollision(True)
            system.Add(jaw)
            jaws.append((jaw, side))
        payload = ch.ChBodyEasyCylinder(
            ch.ChAxis_Y, setup["payload_radius_m"],
            setup["payload_length_m"], setup["payload_density_kg_m3"],
            False, True, material)
        payload.SetPos(ch.ChVector3d(0, 0, 0))
        system.Add(payload)
        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 time grid")
        peak_jaw_force = 0.0
        maximum_vertical_error = 0.0
        maximum_horizontal_error = 0.0
        jaw_height = 0.0
        for index in range(steps):
            time = index * dt
            if time < setup["lift_duration_s"]:
                fraction = time / setup["lift_duration_s"]
                jaw_height = setup["lift_height_m"] * (
                    3 * fraction ** 2 - 2 * fraction ** 3)
                jaw_speed = (setup["lift_height_m"] /
                             setup["lift_duration_s"] *
                             (6 * fraction - 6 * fraction ** 2))
            else:
                elapsed = time - setup["lift_duration_s"]
                ramp = min(1.0, elapsed / setup["shake_ramp_duration_s"])
                amplitude = setup["shake_amplitude_m"] * ramp
                amplitude_rate = (setup["shake_amplitude_m"] /
                                  setup["shake_ramp_duration_s"]
                                  if ramp < 1 else 0.0)
                phase = 2 * math.pi * frequency * elapsed
                jaw_height = setup["lift_height_m"] + amplitude * math.sin(phase)
                jaw_speed = (amplitude_rate * math.sin(phase) +
                             amplitude * 2 * math.pi * frequency * math.cos(phase))
            for jaw, side in jaws:
                jaw.SetPos(ch.ChVector3d(
                    side * setup["jaw_preload_offset_m"], 0, jaw_height))
                jaw.SetPosDt(ch.ChVector3d(0, 0, jaw_speed))
            system.DoStepDynamics(dt)
            peak_jaw_force = max(
                peak_jaw_force,
                *(abs(jaw.GetContactForce().x) for jaw, _ in jaws))
            if time >= setup["lift_duration_s"]:
                position = payload.GetPos()
                maximum_vertical_error = max(
                    maximum_vertical_error, abs(position.z - jaw_height))
                maximum_horizontal_error = max(
                    maximum_horizontal_error,
                    math.hypot(position.x, position.y))
        position = payload.GetPos()
        if not all(math.isfinite(value) for value in (
                peak_jaw_force, maximum_vertical_error,
                maximum_horizontal_error, position.z)):
            raise ValueError("Non-finite gripper trajectory")
        results[str(frequency)] = {
            "final_payload_height_m": position.z,
            "final_jaw_height_m": jaw_height,
            "maximum_vertical_tracking_error_m": maximum_vertical_error,
            "maximum_horizontal_error_m": maximum_horizontal_error,
            "peak_jaw_normal_force_N": peak_jaw_force,
            "collision_triangle_count": mesh.GetNumTriangles(),
        }
    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)
    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["collision_mesh"], 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})
        collision_mesh = properties.pop("collision_mesh")
        results[name] = {
            "step_properties": properties,
            "simulation_result": invoke(args.physics_python, "dynamics", {
                "collision_mesh": collision_mesh, "setup": setup}),
        }
    before, after = results["before"], results["after"]
    bp, ap = before["step_properties"], after["step_properties"]
    gs = after["simulation_result"]
    cases = [str(frequency) for frequency in setup["shake_frequencies_Hz"]]
    checks = {
        "payload_retained_both_shakes": all(
            gs[case]["maximum_vertical_tracking_error_m"] <=
            setup["maximum_payload_vertical_error_m"] and
            gs[case]["maximum_horizontal_error_m"] <=
            setup["maximum_payload_horizontal_error_m"]
            for case in cases),
        "jaw_force_limited": all(
            gs[case]["peak_jaw_normal_force_N"] <=
            setup["maximum_peak_jaw_normal_force_N"] for case in cases),
        "volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <=
        setup["maximum_relative_volume_change"],
        "mount_fixed": ap["mount_missing_mm3"] <=
        setup["maximum_mount_missing_mm3"],
        "envelope_fixed": ap["envelope_excess_mm3"] <=
        setup["maximum_envelope_excess_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"Payload tracking errors: {[gs[case]['maximum_vertical_tracking_error_m'] for case in cases]} m")
    print(f"Task passed: {all(checks.values())}")
    if not all(checks.values()):
        raise SystemExit(1)


if __name__ == "__main__":
    main()