"""Extract STEP friction radius and simulate a braked wheel and chassis.""" 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 brake rotor solid") disc = cq.Solid.makeCylinder(150, 8, cq.Vector(0, -4, 0), cq.Vector(0, 1, 0)) bore = cq.Solid.makeCylinder(20, 10, cq.Vector(0, -4, 0), cq.Vector(0, 1, 0)) base = disc.cut(bore) envelope = cq.Solid.makeCylinder(150, 10, cq.Vector(0, -4, 0), cq.Vector(0, 1, 0)) vertices, triangles = shape.tessellate(setup["cad_tessellation_tolerance_mm"]) area = 0.0 radial_moment = 0.0 count = 0 for a, b, c in triangles: p, q, r = [vertices[index].toTuple() for index in (a, b, c)] if not all(abs(point[1] - setup["friction_face_y_mm"]) < 1e-5 for point in (p, q, r)): continue ax, az = q[0] - p[0], q[2] - p[2] bx, bz = r[0] - p[0], r[2] - p[2] triangle_area = abs(ax * bz - az * bx) / 2 radius = math.hypot((p[0] + q[0] + r[0]) / 3, (p[2] + q[2] + r[2]) / 3) area += triangle_area radial_moment += triangle_area * radius count += 1 if area <= 0 or count < 3: raise ValueError("No measurable raised pad-contact face") props = GProp_GProps() BRepGProp.VolumeProperties_s(shape.wrapped, props) inertia_yy = props.MatrixOfInertia().Value(2, 2) return { "step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(), "volume_mm3": shape.Volume(), "base_missing_mm3": max(0.0, base.Volume() - base.intersect(shape).Volume()), "bore_overlap_mm3": bore.intersect(shape).Volume(), "envelope_excess_mm3": max(0.0, shape.Volume() - shape.intersect(envelope).Volume()), "contact_area_mm2": area, "effective_friction_radius_m": radial_moment / area / 1000, "friction_face_triangle_count": count, "rotor_inertia_kg_m2": inertia_yy * 7800 * 1e-15, } def dynamics(properties: dict, setup: dict) -> dict: import pychrono as ch brake_torque = (setup["pad_friction"] * setup["clamp_force_N"] * properties["effective_friction_radius_m"]) results = {} for initial_speed in setup["initial_speeds_m_s"]: system = ch.ChSystemSMC() system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0)) system.SetSolver(ch.ChSolverSparseLU()) ground = ch.ChBody() ground.SetFixed(True) system.Add(ground) chassis = ch.ChBody() chassis.SetMass(setup["car_mass_kg"]) chassis.SetInertiaXX(ch.ChVector3d(50, 50, 50)) chassis.SetPosDt(ch.ChVector3d(initial_speed, 0, 0)) system.Add(chassis) wheel = ch.ChBody() wheel.SetMass(setup["wheel_mass_kg"]) spin_inertia = (setup["wheel_spin_inertia_kg_m2"] + properties["rotor_inertia_kg_m2"]) wheel.SetInertiaXX(ch.ChVector3d(spin_inertia, spin_inertia, spin_inertia)) wheel.SetPosDt(ch.ChVector3d(initial_speed, 0, 0)) wheel.SetAngVelParent(ch.ChVector3d( 0, initial_speed / setup["wheel_radius_m"], 0)) system.Add(wheel) guide = ch.ChLinkMateGeneric() guide.SetConstrainedCoords(False, True, True, True, True, True) guide.Initialize(chassis, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0))) system.Add(guide) spindle = ch.ChLinkLockRevolute() spindle.Initialize(wheel, chassis, ch.ChFramed( ch.ChVector3d(0, 0, 0), ch.QuatFromAngleX(-math.pi / 2))) system.Add(spindle) tire_force = ch.ChForce() chassis.AddForce(tire_force) tire_force.SetMode(ch.ChForce.FORCE) tire_force.SetDir(ch.ChVector3d(-1, 0, 0)) wheel_torque = ch.ChForce() wheel.AddForce(wheel_torque) wheel_torque.SetMode(ch.ChForce.TORQUE) wheel_torque.SetDir(ch.ChVector3d(0, 1, 0)) dt = setup["time_step_s"] steps = round(setup["maximum_duration_s"] / dt) if dt <= 0 or abs(steps * dt - setup["maximum_duration_s"]) > 1e-12: raise ValueError("Invalid simulation time grid") maximum_slip = 0.0 stopped = False for index in range(steps): speed = chassis.GetPosDt().x angular_speed = wheel.GetAngVelParent().y slip = ((speed - setup["wheel_radius_m"] * angular_speed) / max(speed, setup["stop_speed_m_s"])) force = (setup["tire_peak_force_N"] * math.tanh(setup["tire_slip_stiffness"] * slip)) tire_force.SetMforce(force) wheel_torque.SetMforce(setup["wheel_radius_m"] * force - brake_torque) system.DoStepDynamics(dt) if speed > 2: maximum_slip = max(maximum_slip, abs(slip)) if chassis.GetPosDt().x <= setup["stop_speed_m_s"]: stopped = True break results[str(initial_speed)] = { "stopping_distance_m": chassis.GetPos().x if stopped else None, "stopping_time_s": system.GetChTime() if stopped else None, "maximum_tire_slip_above_2m_s": maximum_slip, "brake_torque_N_m": brake_torque, "rotor_inertia_kg_m2": properties["rotor_inertia_kg_m2"], } 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"] speeds = [str(speed) for speed in setup["initial_speeds_m_s"]] baseline = [bs[speed]["stopping_distance_m"] for speed in speeds] candidate = [gs[speed]["stopping_distance_m"] for speed in speeds] if any(value is None for value in baseline + candidate): raise ValueError("Wheel did not stop before the time limit") reductions = [1 - a / b for a, b in zip(candidate, baseline)] checks = { "stopping_distance_reduced_both_speeds": min(reductions) >= setup["required_relative_stopping_distance_reduction"], "candidate_distance_limit": candidate[-1] <= setup["maximum_candidate_stopping_distance_m_at_10m_s"], "tire_slip_limited": all(gs[speed]["maximum_tire_slip_above_2m_s"] <= setup["maximum_tire_slip"] for speed in speeds), "volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <= setup["maximum_relative_volume_change"], "base_fixed": ap["base_missing_mm3"] <= setup["maximum_base_missing_mm3"], "bore_open": ap["bore_overlap_mm3"] <= setup["maximum_bore_overlap_mm3"], "contact_area_fixed": abs(ap["contact_area_mm2"] / bp["contact_area_mm2"] - 1) <= setup["maximum_contact_area_relative_change"], "envelope_fixed": ap["envelope_excess_mm3"] <= setup["maximum_envelope_excess_mm3"], } after["comparison_to_before"] = { "relative_stopping_distance_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"Stopping distance: {baseline} -> {candidate} m") print(f"Task passed: {all(checks.values())}") if not all(checks.values()): raise SystemExit(1) if __name__ == "__main__": main()