"""Measure STEP-mesh wheel drawbar pull at fixed commanded slip.""" 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, 80, cq.Vector(0, -40, 0), cq.Vector(0, 1, 0)) envelope = cq.Solid.makeBox(600, 80, 600, cq.Vector(-300, -40, -300)) 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": abs(max(math.hypot(point.x, point.z) for point in vertices) - 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()) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) 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"]) dt = setup["time_step_s"] settle_steps = round(setup["settling_duration_s"] / dt) drive_steps = round(setup["drive_duration_s"] / dt) sample_start = round(setup["measure_after_drive_s"] / dt) if (abs(settle_steps * dt - setup["settling_duration_s"]) > 1e-12 or abs(drive_steps * dt - setup["drive_duration_s"]) > 1e-12 or abs(sample_start * dt - setup["measure_after_drive_s"]) > 1e-12): raise ValueError("Invalid simulation time grid") for _ in range(settle_steps): system.DoStepDynamics(dt) linear = ch.ChLinkMotorLinearSpeed() linear.SetGuideConstraint(ch.ChLinkMotorLinear.GuideConstraint_FREE) linear.Initialize(wheel, ground, ch.ChFramed( wheel.GetPos(), ch.QuatFromAngleY(math.pi / 2))) linear.SetMotorFunction(ch.ChFunctionConst(setup["forward_speed_m_s"])) system.Add(linear) angular_speed = (setup["forward_speed_m_s"] / (setup["wheel_outer_radius_m"] * (1 - setup["commanded_longitudinal_slip"]))) rotary = ch.ChLinkMotorRotationSpeed() rotary.SetSpindleConstraint(ch.ChLinkMotorRotation.SpindleConstraint_FREE) rotary.Initialize(wheel, ground, ch.ChFramed( wheel.GetPos(), ch.QuatFromAngleX(-math.pi / 2))) rotary.SetMotorFunction(ch.ChFunctionConst(angular_speed)) system.Add(rotary) forces = [] for index in range(drive_steps): system.DoStepDynamics(dt) if index >= sample_start: forces.append(-linear.GetMotorForce()) mean_force = sum(forces) / len(forces) if not math.isfinite(mean_force): raise ValueError("Non-finite drawbar reaction") results[str(offset)] = { "mean_drawbar_pull_N": mean_force, "final_center_height_m": wheel.GetPos().z, "motor_forward_speed_m_s": linear.GetMotorPosDt(), "motor_angular_speed_rad_s": rotary.GetMotorAngleDt(), "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]["mean_drawbar_pull_N"] for offset in offsets] candidate = [gs[offset]["mean_drawbar_pull_N"] for offset in offsets] gains = [a - b for a, b in zip(candidate, baseline)] expected_angular_speed = (setup["forward_speed_m_s"] / (setup["wheel_outer_radius_m"] * (1 - setup["commanded_longitudinal_slip"]))) checks = { "drawbar_gain_both_offsets": min(gains) >= setup["minimum_drawbar_gain_N"], "positive_candidate_drawbar_pull": min(candidate) >= setup["minimum_candidate_drawbar_pull_N"], "commanded_speeds_met": all( abs(gs[offset]["motor_forward_speed_m_s"] - setup["forward_speed_m_s"]) < 1e-4 and abs(gs[offset]["motor_angular_speed_rad_s"] - expected_angular_speed) < 1e-4 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"] = { "drawbar_gains_N": gains, "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"Mean drawbar pull: {baseline} -> {candidate} N") print(f"Task passed: {all(checks.values())}") if not all(checks.values()): raise SystemExit(1) if __name__ == "__main__": main()