"""Run STEP-derived rover rocker geometry over a rough course.""" 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.BRepGProp import BRepGProp from OCP.GProp import GProp_GProps 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 rover rocker solid") bores = {"pivot": [], "wheel": []} for face in shape.Faces(): if face.geomType() != "CYLINDER": continue bounds = face.BoundingBox() if abs(bounds.ymin + 10) > 1e-5 or abs(bounds.ymax - 10) > 1e-5: continue if abs(face.Area() - 2 * math.pi * 10 * 20) < 1e-3: bores["pivot"].append([face.Center().x, face.Center().z]) elif abs(face.Area() - 2 * math.pi * 8 * 20) < 1e-3: bores["wheel"].append([face.Center().x, face.Center().z]) if len(bores["pivot"]) != 1 or len(bores["wheel"]) != 2: raise ValueError("Expected one pivot bore and two wheel pickup bores") bores["wheel"].sort() props = GProp_GProps() BRepGProp.VolumeProperties_s(shape.wrapped, props) inertia = props.MatrixOfInertia() density = setup["material_density_kg_m3"] envelope = cq.Solid.makeBox(360, 20, 200, cq.Vector(-180, -10, -180)) return { "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), "volume_mm3": props.Mass(), "mass_kg": props.Mass() * density * 1e-9, "center_of_mass_m": [value / 1000 for value in 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)], "pivot_bore_mm": bores["pivot"][0], "wheel_bores_mm": bores["wheel"], "envelope_excess_mm3": max(0.0, shape.Volume() - shape.intersect(envelope).Volume()), } def dynamics(properties: dict, setup: dict) -> dict: import pychrono as ch pivot = properties["pivot_bore_mm"] pickups = [ ((bore[0] - pivot[0]) / 1000, (bore[1] - pivot[1]) / 1000) for bore in properties["wheel_bores_mm"] ] def terrain_height(x): return ( setup["first_bump_height_m"] * math.exp(-((x - setup["first_bump_center_m"]) / setup["first_bump_width_m"]) ** 2) + setup["second_bump_height_m"] * math.exp(-((x - setup["second_bump_center_m"]) / setup["second_bump_width_m"]) ** 2) ) results = {} for speed in setup["chassis_speeds_m_s"]: system = ch.ChSystemSMC() system.SetGravitationalAcceleration( ch.ChVector3d(0, 0, -setup["gravity_m_s2"])) system.SetSolver(ch.ChSolverSparseLU()) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) rocker = ch.ChBody() rocker.SetMass(properties["mass_kg"]) inertia = ch.ChMatrix33d() inertia.SetMatr(properties["inertia_tensor_kg_m2"]) rocker.SetInertia(inertia) rocker.SetPos(ch.ChVector3d(*properties["center_of_mass_m"])) system.Add(rocker) hinge = ch.ChLinkLockRevolute() hinge.Initialize(rocker, ground, ch.ChFramed( ch.ChVector3d(0, 0, 0), ch.QuatFromAngleX(-math.pi / 2))) system.Add(hinge) torque = ch.ChForce() rocker.AddForce(torque) torque.SetMode(ch.ChForce.TORQUE) torque.SetDir(ch.ChVector3d(0, 1, 0)) 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 rover time grid") peak_imbalance = 0.0 minimum_total_force = float("inf") for index in range(steps): time = index * dt chassis_x = (setup["chassis_initial_x_m"] + speed * max(0.0, time - setup["settling_duration_s"])) rotation = rocker.GetRot() angle = 2 * math.atan2(rotation.e2, rotation.e0) angular_speed = rocker.GetAngVelParent().y forces = [] moment = 0.0 for x, z in pickups: world_x = x * math.cos(angle) + z * math.sin(angle) world_z = -x * math.sin(angle) + z * math.cos(angle) vertical_speed = (-x * math.cos(angle) - z * math.sin(angle)) * angular_speed penetration = ( terrain_height(chassis_x + world_x) + setup["wheel_radius_m"] - (setup["pivot_height_m"] + world_z) ) force = max( 0.0, setup["wheel_contact_stiffness_N_m"] * penetration - setup["wheel_contact_damping_N_s_m"] * vertical_speed) forces.append(force) moment -= world_x * force torque.SetMforce(moment) system.DoStepDynamics(dt) if time >= setup["settling_duration_s"]: total = sum(forces) minimum_total_force = min(minimum_total_force, total) if total >= setup["minimum_contact_force_sum_N"]: peak_imbalance = max( peak_imbalance, abs(forces[0] - forces[1]) / total) if not all(math.isfinite(value) for value in ( peak_imbalance, minimum_total_force)): raise ValueError("Non-finite rover contact response") results[str(speed)] = { "peak_wheel_load_imbalance": peak_imbalance, "minimum_total_wheel_load_N": minimum_total_force, "wheel_pickup_arm_lengths_m": [abs(x) for x, _ in pickups], } 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["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, after = results["before"], results["after"] bp, ap = before["step_properties"], after["step_properties"] bs, gs = before["simulation_result"], after["simulation_result"] cases = [str(speed) for speed in setup["chassis_speeds_m_s"]] baseline = [bs[case]["peak_wheel_load_imbalance"] for case in cases] candidate = [gs[case]["peak_wheel_load_imbalance"] for case in cases] reductions = [1 - a / b for a, b in zip(candidate, baseline)] checks = { "wheel_load_imbalance_reduced_both_speeds": min(reductions) >= setup["required_relative_peak_imbalance_reduction"], "candidate_imbalance_limit": max(candidate) <= setup["maximum_candidate_peak_imbalance"], "both_wheels_loaded": all(gs[case]["minimum_total_wheel_load_N"] >= setup["minimum_contact_force_sum_N"] for case in cases), "wheel_pickup_range": (setup["wheel_pickup_x_min_mm"] <= ap["wheel_bores_mm"][0][0] < 0 < ap["wheel_bores_mm"][1][0] <= setup["wheel_pickup_x_max_mm"]), "pivot_fixed": max(abs(a - b) for a, b in zip( ap["pivot_bore_mm"], bp["pivot_bore_mm"])) <= setup["maximum_pivot_center_error_mm"], "wheel_height_fixed": max(abs(a[1] - b[1]) for a, b in zip( ap["wheel_bores_mm"], bp["wheel_bores_mm"])) <= setup["maximum_wheel_pickup_z_error_mm"], "mass_fixed": abs(ap["mass_kg"] / bp["mass_kg"] - 1) <= setup["maximum_relative_mass_change"], "envelope_fixed": ap["envelope_excess_mm3"] <= setup["maximum_envelope_excess_mm3"], } after["comparison_to_before"] = { "relative_peak_wheel_load_imbalance_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 wheel-load imbalance: {baseline} -> {candidate}") print(f"Task passed: {all(checks.values())}") if not all(checks.values()): raise SystemExit(1) if __name__ == "__main__": main()