File size: 8,764 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
"""Run a STEP-contact track shoe over a rigid rock at fixed speeds."""

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 track-shoe solid")
    mount = cq.Solid.makeBox(100, 100, 10, cq.Vector(-50, -50, 20))
    envelope = cq.Solid.makeBox(300, 100, 30, cq.Vector(-150, -50, 0))
    vertices, faces = shape.tessellate(setup["cad_tessellation_tolerance_mm"])
    if len(vertices) < 8 or len(faces) < 12:
        raise ValueError("Track-shoe 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

    collision_mesh_ch = ch.ChTriangleMeshConnected()
    vertices = [ch.ChVector3d(*point) for point in collision_mesh["vertices"]]
    for a, b, c in collision_mesh["faces"]:
        collision_mesh_ch.AddTriangle(vertices[a], vertices[b], vertices[c])
    results = {}
    for speed in setup["drive_speeds_m_s"]:
        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"])
        floor = ch.ChBodyEasyBox(2, 1, 0.1, 1000, False, True, material)
        floor.SetPos(ch.ChVector3d(0, 0, -0.05))
        floor.SetFixed(True)
        system.Add(floor)
        rock = ch.ChBodyEasySphere(setup["rock_radius_m"], 1000,
                                   False, True, material)
        rock.SetPos(ch.ChVector3d(*setup["rock_center_m"]))
        rock.SetFixed(True)
        system.Add(rock)
        shoe = ch.ChBody()
        shoe.SetMass(setup["carrier_mass_kg"])
        shoe.SetInertiaXX(ch.ChVector3d(*setup["carrier_inertia_kg_m2"]))
        shoe.SetPos(ch.ChVector3d(*setup["initial_position_m"]))
        shoe.AddCollisionShape(ch.ChCollisionShapeTriangleMesh(
            material, collision_mesh_ch, False, False,
            setup["collision_thickness_m"]))
        shoe.EnableCollision(True)
        system.Add(shoe)
        guide = ch.ChLinkMateGeneric()
        guide.SetConstrainedCoords(False, True, False, True, True, True)
        guide.Initialize(shoe, floor, ch.ChFramed(shoe.GetPos()))
        system.Add(guide)
        motor = ch.ChLinkMotorLinearSpeed()
        motor.SetGuideConstraint(ch.ChLinkMotorLinear.GuideConstraint_FREE)
        motor.Initialize(shoe, floor, ch.ChFramed(
            shoe.GetPos(), ch.QuatFromAngleY(math.pi / 2)))
        motor.SetMotorFunction(ch.ChFunctionConst(speed))
        system.Add(motor)
        spring = ch.ChForce()
        shoe.AddForce(spring)
        spring.SetMode(ch.ChForce.FORCE)
        spring.SetDir(ch.ChVector3d(0, 0, 1))
        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_acceleration = 0.0
        peak_height = setup["initial_position_m"][2]
        for index in range(steps):
            position = shoe.GetPos()
            velocity = shoe.GetPosDt()
            spring.SetMforce(
                setup["carrier_mass_kg"] * setup["gravity_m_s2"] +
                setup["spring_stiffness_N_m"] *
                (setup["spring_rest_height_m"] - position.z) -
                setup["spring_damping_N_s_m"] * velocity.z)
            system.DoStepDynamics(dt)
            if index * dt >= 0.3:
                peak_acceleration = max(peak_acceleration,
                                        abs(shoe.GetPosDt2().z))
            peak_height = max(peak_height, shoe.GetPos().z)
        if not all(math.isfinite(value) for value in (
                peak_acceleration, peak_height, shoe.GetPos().x)):
            raise ValueError("Non-finite shoe trajectory")
        results[str(speed)] = {
            "peak_vertical_acceleration_m_s2": peak_acceleration,
            "rock_climb_m": peak_height - setup["initial_position_m"][2],
            "final_x_m": shoe.GetPos().x,
            "motor_speed_m_s": motor.GetMotorPosDt(),
            "collision_triangle_count": collision_mesh_ch.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"]
    bs, gs = before["simulation_result"], after["simulation_result"]
    speeds = [str(speed) for speed in setup["drive_speeds_m_s"]]
    baseline = [bs[speed]["peak_vertical_acceleration_m_s2"] for speed in speeds]
    candidate = [gs[speed]["peak_vertical_acceleration_m_s2"] for speed in speeds]
    reductions = [1 - a / b for a, b in zip(candidate, baseline)]
    checks = {
        "baseline_acceleration_measurable": min(baseline) >=
        setup["minimum_baseline_peak_acceleration_m_s2"],
        "acceleration_reduced_both_speeds": min(reductions) >=
        setup["required_relative_peak_acceleration_reduction"],
        "candidate_acceleration_below_limit": max(candidate) <=
        setup["maximum_candidate_peak_acceleration_m_s2"],
        "rock_climbed": all(gs[speed]["rock_climb_m"] >=
                            setup["minimum_rock_climb_m"] for speed in speeds),
        "motor_speeds_met": all(abs(gs[speed]["motor_speed_m_s"] - float(speed))
                                < 1e-6 for speed in speeds),
        "course_traversed": all(gs[speed]["final_x_m"] > 0.25
                                for speed in speeds),
        "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"] = {
        "relative_peak_acceleration_reductions": reductions,
        "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"Peak acceleration: {baseline} -> {candidate} m/s2")
    print(f"Task passed: {all(checks.values())}")
    if not all(checks.values()):
        raise SystemExit(1)


if __name__ == "__main__":
    main()