File size: 8,132 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
"""Measure STEP-mesh wheel sinkage on SCM soil."""

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 wheel solid")
    hub = cq.Solid.makeCylinder(100, 10, cq.Vector(0, -5, 0),
                                cq.Vector(0, 1, 0)).cut(
        cq.Solid.makeCylinder(30, 10, cq.Vector(0, -5, 0), cq.Vector(0, 1, 0)))
    bore = cq.Solid.makeCylinder(30, 120, cq.Vector(0, -60, 0),
                                 cq.Vector(0, 1, 0))
    envelope = cq.Solid.makeBox(600, 120, 600, cq.Vector(-300, -60, -300))
    bounds = shape.BoundingBox()
    vertices, faces = shape.tessellate(setup["cad_tessellation_tolerance_mm"])
    if len(vertices) < 8 or len(faces) < 12:
        raise ValueError("Wheel tessellation is incomplete")
    return {
        "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
        "volume_mm3": shape.Volume(),
        "hub_missing_mm3": max(0.0, hub.Volume() - hub.intersect(shape).Volume()),
        "bore_overlap_mm3": bore.intersect(shape).Volume(),
        "envelope_excess_mm3": max(0.0, shape.Volume() -
                                   shape.intersect(envelope).Volume()),
        "radius_error_mm": max(abs(bounds.xmax - 300), abs(bounds.xmin + 300),
                                abs(bounds.zmax - 300), abs(bounds.zmin + 300)),
        "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
    import pychrono.vehicle as veh

    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 offset in setup["starting_x_offsets_m"]:
        system = ch.ChSystemSMC()
        system.SetCollisionSystemType(ch.ChCollisionSystem.Type_BULLET)
        system.SetGravitationalAcceleration(
            ch.ChVector3d(0, 0, -setup["gravity_m_s2"]))
        system.SetSolver(ch.ChSolverSparseLU())
        wheel = ch.ChBody()
        wheel.SetMass(setup["wheel_mass_kg"])
        wheel.SetInertiaXX(ch.ChVector3d(*setup["wheel_inertia_kg_m2"]))
        wheel.SetPos(ch.ChVector3d(offset, 0, setup["wheel_initial_height_m"]))
        system.Add(wheel)
        material = ch.ChContactMaterialSMC()
        material.SetFriction(0.8)
        material.SetRestitution(0)
        wheel.AddCollisionShape(ch.ChCollisionShapeTriangleMesh(
            material, mesh, False, False, 0.002))
        wheel.EnableCollision(True)
        terrain = veh.SCMTerrain(system, False)
        terrain.Initialize(setup["terrain_length_m"], setup["terrain_width_m"],
                           setup["terrain_grid_m"])
        terrain.SetSoilParameters(
            setup["soil_Kphi"], setup["soil_Kc"], setup["soil_n"],
            setup["soil_cohesion_Pa"], setup["soil_friction_angle_deg"],
            setup["soil_Janosi_m"], setup["soil_elastic_stiffness_Pa_m"],
            setup["soil_damping_Pa_s_m"])
        steps = round(setup["duration_s"] / setup["time_step_s"])
        if abs(steps * setup["time_step_s"] - setup["duration_s"]) > 1e-12:
            raise ValueError("Invalid simulation time grid")
        earlier_height = None
        for index in range(steps):
            system.DoStepDynamics(setup["time_step_s"])
            if index == steps - round(0.1 / setup["time_step_s"]) - 1:
                earlier_height = wheel.GetPos().z
        position = wheel.GetPos()
        sinkage = setup["wheel_outer_radius_m"] - position.z
        if not math.isfinite(sinkage) or earlier_height is None:
            raise ValueError("Non-finite wheel response")
        results[str(offset)] = {
            "sinkage_m": sinkage,
            "settling_drift_m": abs(position.z - earlier_height),
            "lateral_drift_m": math.hypot(position.x - offset, position.y),
            "modified_terrain_node_count": len(terrain.GetModifiedNodes()),
            "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"]
    bs, gs = before["simulation_result"], after["simulation_result"]
    offsets = [str(offset) for offset in setup["starting_x_offsets_m"]]
    baseline = [bs[offset]["sinkage_m"] for offset in offsets]
    candidate = [gs[offset]["sinkage_m"] for offset in offsets]
    reductions = [1 - a / b for a, b in zip(candidate, baseline)]
    checks = {
        "baseline_sinks": min(baseline) > 0.05,
        "sinkage_reduced_both_offsets": min(reductions) >=
        setup["required_relative_sinkage_reduction"],
        "wheel_settles": all(gs[offset]["settling_drift_m"] <=
                              setup["maximum_settling_drift_m"]
                              for offset in offsets),
        "wheel_stays_near_drop": all(gs[offset]["lateral_drift_m"] <=
                                      setup["maximum_lateral_drift_m"]
                                      for offset in offsets),
        "soil_contact_active": all(gs[offset]["modified_terrain_node_count"] > 0
                                    for offset in offsets),
        "volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <=
        setup["maximum_relative_volume_change"],
        "hub_fixed": ap["hub_missing_mm3"] <=
        setup["maximum_hub_missing_mm3"],
        "bore_open": ap["bore_overlap_mm3"] <=
        setup["maximum_bore_overlap_mm3"],
        "envelope_fixed": ap["envelope_excess_mm3"] <=
        setup["maximum_envelope_excess_mm3"],
        "radius_fixed": ap["radius_error_mm"] <=
        setup["maximum_radius_error_mm"],
    }
    after["comparison_to_before"] = {
        "relative_sinkage_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"Settled sinkage: {baseline} -> {candidate} m")
    print(f"Task passed: {all(checks.values())}")
    if not all(checks.values()):
        raise SystemExit(1)


if __name__ == "__main__":
    main()