File size: 9,025 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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | """Solve STEP-derived steering arms and measure tire scrub in a turn."""
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 steering knuckle solid")
holes = {}
for face in shape.Faces():
if face.geomType() != "CYLINDER":
continue
bounds = face.BoundingBox()
if abs(bounds.zmin + 5) > 1e-5 or abs(bounds.zmax - 5) > 1e-5:
continue
if abs(face.Area() - 2 * math.pi * 20 * 10) < 1e-3:
holes["hub"] = [face.Center().x, face.Center().y]
elif abs(face.Area() - 2 * math.pi * 8 * 10) < 1e-3:
holes["tie"] = [face.Center().x, face.Center().y]
if set(holes) != {"hub", "tie"}:
raise ValueError("Expected one hub bore and one tie-rod bore")
envelope = cq.Solid.makeBox(250, 200, 10, cq.Vector(-200, -150, -5))
return {
"step_sha256": hashlib.sha256(step.read_bytes()).hexdigest(),
"volume_mm3": shape.Volume(),
"hub_center_mm": holes["hub"],
"tie_pickup_mm": holes["tie"],
"envelope_excess_mm3": max(0.0, shape.Volume() -
shape.intersect(envelope).Volume()),
}
def dynamics(properties: dict, setup: dict) -> dict:
import pychrono as ch
arm_x = (properties["tie_pickup_mm"][0] -
properties["hub_center_mm"][0]) / 1000
arm_y = (properties["tie_pickup_mm"][1] -
properties["hub_center_mm"][1]) / 1000
system = ch.ChSystemSMC()
system.SetGravitationalAcceleration(ch.ChVector3d(0, 0, 0))
system.SetSolver(ch.ChSolverSparseLU())
ground = ch.ChBody()
ground.SetFixed(True)
system.Add(ground)
rack = ch.ChBody()
rack.SetMass(1)
rack.SetInertiaXX(ch.ChVector3d(0.1, 0.1, 0.1))
system.Add(rack)
rack_guide = ch.ChLinkMateGeneric()
rack_guide.SetConstrainedCoords(True, False, True, True, True, True)
rack_guide.Initialize(rack, ground, ch.ChFramed(ch.ChVector3d(0, 0, 0)))
system.Add(rack_guide)
motor = ch.ChLinkMotorLinearPosition()
motor.SetGuideConstraint(ch.ChLinkMotorLinear.GuideConstraint_FREE)
motor.Initialize(rack, ground, ch.ChFramed(
ch.ChVector3d(0, 0, 0), ch.QuatFromAngleX(-math.pi / 2)))
motor.SetMotorFunction(ch.ChFunctionRamp(
0, setup["rack_travel_m"] / setup["rack_travel_duration_s"]))
system.Add(motor)
knuckles = []
for side in (1, -1):
knuckle = ch.ChBody()
knuckle.SetMass(1)
knuckle.SetInertiaXX(ch.ChVector3d(0.1, 0.1, 0.1))
knuckle.SetPos(ch.ChVector3d(
0, side * setup["front_track_m"] / 2, 0))
system.Add(knuckle)
kingpin = ch.ChLinkLockRevolute()
kingpin.Initialize(knuckle, ground, ch.ChFramed(knuckle.GetPos()))
system.Add(kingpin)
tie_rod = ch.ChLinkDistance()
tie_rod.Initialize(
knuckle, rack, True,
ch.ChVector3d(arm_x, side * arm_y, 0),
ch.ChVector3d(setup["rack_x_m"],
side * setup["rack_half_width_m"], 0))
system.Add(tie_rod)
knuckles.append(knuckle)
dt = setup["time_step_s"]
steps = round(setup["rack_travel_duration_s"] / dt)
if dt <= 0 or abs(steps * dt - setup["rack_travel_duration_s"]) > 1e-12:
raise ValueError("Invalid steering time grid")
target_steps = {
round(abs(displacement / setup["rack_travel_m"]) * steps): str(displacement)
for displacement in setup["evaluation_rack_displacements_m"]
}
results = {}
for index in range(steps):
system.DoStepDynamics(dt)
if index + 1 not in target_steps:
continue
angles = [2 * math.atan2(body.GetRot().e3, body.GetRot().e0)
for body in knuckles]
if min(angles) <= 0:
raise ValueError("Both front wheels must steer into the left turn")
turn_radius = (setup["wheelbase_m"] /
math.tan(sum(angles) / 2))
half_track = setup["front_track_m"] / 2
ideal = [
math.atan(setup["wheelbase_m"] / (turn_radius - half_track)),
math.atan(setup["wheelbase_m"] / (turn_radius + half_track)),
]
errors = [angle - target for angle, target in zip(angles, ideal)]
work = sum(
setup["tire_friction_limit"] * setup["tire_normal_load_N"] *
math.tanh(setup["lateral_slip_stiffness"] * abs(error)) *
setup["maneuver_distance_m"] * abs(math.sin(error))
for error in errors
)
if not all(math.isfinite(value) for value in (
*angles, turn_radius, *errors, work)):
raise ValueError("Non-finite steering solution")
results[target_steps[index + 1]] = {
"inner_steer_rad": angles[0],
"outer_steer_rad": angles[1],
"turning_radius_m": turn_radius,
"tire_slip_angle_errors_rad": errors,
"scrub_work_J": work,
"rack_displacement_m": rack.GetPos().y,
}
if len(results) != len(target_steps):
raise ValueError("Steering run missed a requested rack displacement")
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(value) for value in setup["evaluation_rack_displacements_m"]]
baseline = [bs[case]["scrub_work_J"] for case in cases]
candidate = [gs[case]["scrub_work_J"] for case in cases]
reductions = [1 - a / b for a, b in zip(candidate, baseline)]
checks = {
"scrub_reduced_both_turns": min(reductions) >=
setup["required_relative_scrub_work_reduction"],
"turning_radius_met": (
gs[cases[0]]["turning_radius_m"] <=
setup["maximum_turning_radius_m_at_15mm"] and
gs[cases[1]]["turning_radius_m"] <=
setup["maximum_turning_radius_m_at_20mm"]),
"rack_positions_met": all(abs(gs[case]["rack_displacement_m"] -
float(case)) < 1e-5 for case in cases),
"tie_clearance": setup["minimum_tie_pickup_y_mm"] <=
ap["tie_pickup_mm"][1] <= setup["maximum_tie_pickup_y_mm"],
"hub_fixed": max(abs(a - b) for a, b in zip(
ap["hub_center_mm"], bp["hub_center_mm"])) <=
setup["maximum_hub_center_error_mm"],
"tie_x_fixed": abs(ap["tie_pickup_mm"][0] -
bp["tie_pickup_mm"][0]) <=
setup["maximum_tie_pickup_x_error_mm"],
"volume_fixed": abs(ap["volume_mm3"] / bp["volume_mm3"] - 1) <=
setup["maximum_relative_volume_change"],
"envelope_fixed": ap["envelope_excess_mm3"] <=
setup["maximum_envelope_excess_mm3"],
}
after["comparison_to_before"] = {
"relative_scrub_work_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"Tire scrub work: {baseline} -> {candidate} J")
print(f"Task passed: {all(checks.values())}")
if not all(checks.values()):
raise SystemExit(1)
if __name__ == "__main__":
main()
|