Compare commits

...

6 Commits

4 changed files with 579 additions and 5 deletions
+12 -3
View File
@@ -3,7 +3,7 @@ from collections.abc import Callable
import base64
import ctypes
import gc
from functools import cached_property
from functools import cached_property, partial
import os
os.environ['GMMU'] = '0' # for chestnut fast loading, noop for qcom
os.environ.setdefault('AM_POWER_LIMIT', '100')
@@ -43,6 +43,7 @@ from openpilot.selfdrive.modeld.constants import ModelConstants, Plan
from openpilot.selfdrive.modeld.helpers import MODELS_DIR, chestnut_present, chestnut_compiled, modeld_pkl_path, load_oob, wait_for_chestnut
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
from openpilot.sunnypilot.modeld_v2.turn_planner import TurnPlanner
from openpilot.sunnypilot.selfdrive.controls.lib.relc import RoadEdgeLaneChangeController
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
@@ -54,7 +55,8 @@ BIG_MODEL_TIMEOUT = 60
def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action,
lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action:
lat_action_t: float, long_action_t: float, v_ego: float,
turn_shaper: Callable[[float, float], tuple[float, float]] | None = None) -> log.ModelDataV2.Action:
if 'action' not in model_output:
plan = model_output['plan'][0]
desired_accel = get_accel_from_plan(plan[:,Plan.VELOCITY][:,0],
@@ -69,6 +71,8 @@ def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.
else:
desired_accel = model_output['action'][0,1]
desired_curvature = model_output['action'][0,0] / (max(1.0, v_ego))**2
if turn_shaper is not None:
desired_curvature, desired_accel = turn_shaper(desired_curvature, desired_accel)
stop = should_stop(v_ego, desired_accel)
desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, LONG_SMOOTH_SECONDS)
if v_ego > MIN_LAT_CONTROL_SPEED:
@@ -340,6 +344,7 @@ def main(demo=False):
DH = DesireHelper()
RELC = RoadEdgeLaneChangeController()
turn_planner = TurnPlanner(CP.wheelbase)
while True:
# Keep receiving frames until we are at least 1 frame ahead of previous extra frame
@@ -448,7 +453,11 @@ def main(demo=False):
if not sm['carControl'].latActive:
prev_action.desiredCurvature = sm['controlsState'].curvature
action = get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
action = get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego,
partial(turn_planner.update, model_output, v_ego, sm['controlsState'].curvature,
sm['carControl'].latActive, is_rhd,
left_blindspot=sm['carState'].leftBlindspot,
right_blindspot=sm['carState'].rightBlindspot))
prev_action = action
fill_model_msg(modelv2_send, model_output, action,
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
+11 -2
View File
@@ -41,6 +41,7 @@ from openpilot.selfdrive.modeld.modeld import ChestnutGpuState
from openpilot.sunnypilot.modeld_v2.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState, get_curvature_from_output
from openpilot.sunnypilot.modeld_v2.parse_model_outputs import Parser
from openpilot.sunnypilot.modeld_v2.blendful import Blendful
from openpilot.sunnypilot.modeld_v2.turn_planner import TurnPlanner
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan
from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants
from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper
@@ -231,7 +232,8 @@ class ModelState(ModelStateBase):
def get_action_from_model(self, model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action,
lat_action_t: float, long_action_t: float, v_ego: float,
blendful: Callable[[float], float] | None = None) -> log.ModelDataV2.Action:
blendful: Callable[[float], float] | None = None,
turn_shaper: Callable[[float, float], tuple[float, float]] | None = None) -> log.ModelDataV2.Action:
if 'action' not in model_output:
plan = model_output['plan'][0]
desired_accel = get_accel_from_plan(plan[:, Plan.VELOCITY][:, 0], plan[:, Plan.ACCELERATION][:, 0], self.constants.T_IDXS,
@@ -245,6 +247,8 @@ class ModelState(ModelStateBase):
desired_curvature = model_output['action'][0, 0] / (max(2.5, v_ego))**2
if blendful is not None:
desired_curvature += blendful(desired_curvature)
if turn_shaper is not None:
desired_curvature, desired_accel = turn_shaper(desired_curvature, desired_accel)
stop = v_ego < 0.3 and desired_accel < 0.1
desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, self.LONG_SMOOTH_SECONDS)
@@ -373,6 +377,7 @@ def main(demo=False):
RELC = RoadEdgeLaneChangeController()
blendful = Blendful()
blendful_enabled = False
turn_planner = TurnPlanner(CP.wheelbase)
while True:
# Keep receiving frames until we are at least 1 frame ahead of previous extra frame
@@ -492,7 +497,11 @@ def main(demo=False):
prev_action.desiredCurvature = sm['controlsState'].curvature
blendful_active = desire == log.Desire.none and DH.lane_change_state == log.LaneChangeState.off
action = model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego,
partial(blendful.update, model_output, v_ego, blendful_active, enabled=blendful_enabled))
partial(blendful.update, model_output, v_ego, blendful_active, enabled=blendful_enabled),
partial(turn_planner.update, model_output, v_ego, sm['controlsState'].curvature,
sm['carControl'].latActive, is_rhd,
left_blindspot=sm['carState'].leftBlindspot,
right_blindspot=sm['carState'].rightBlindspot))
prev_action = action
fill_model_msg(drivingdata_send, modelv2_send, model_output, action,
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
@@ -0,0 +1,271 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import functools
import math
import numpy as np
from openpilot.common.realtime import DT_MDL
from openpilot.common.test import OpenpilotTestCase
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan
from openpilot.sunnypilot.modeld_v2.turn_planner import TurnPlanner
X = np.array(ModelConstants.X_IDXS, dtype=np.float32)
def make_plan(curv: float, speed: float = 4.0) -> dict[str, np.ndarray]:
t = np.array(ModelConstants.T_IDXS, dtype=np.float32)
s = speed * t
plan = np.zeros((1, len(t), ModelConstants.PLAN_WIDTH), dtype=np.float32)
if abs(curv) < 1e-6:
plan[0, :, Plan.POSITION][:, 0] = s
else:
r = 1.0 / curv
th = s * curv
plan[0, :, Plan.POSITION][:, 0] = r * np.sin(th)
plan[0, :, Plan.POSITION][:, 1] = r * (1.0 - np.cos(th))
plan[0, :, Plan.T_FROM_CURRENT_EULER][:, 2] = th
return {'plan': plan}
def with_curb(plan_dict: dict[str, np.ndarray], e0: float = 2.4, flare_5m: float = 0.1, std: float = 0.4) -> dict[str, np.ndarray]:
edges = np.zeros((1, 2, len(X), 2), dtype=np.float32)
edges[0, 0, :, 0] = -5.0
edges[0, 1, :, 0] = e0 + (flare_5m / 25.0) * (X ** 2)
stds = np.full((1, 2, len(X), 2), std, dtype=np.float32)
return {**plan_dict, 'road_edges': edges, 'road_edges_stds': stds}
def with_lanes_and_edges(plan_dict: dict[str, np.ndarray], re_l: float = -5.0, re_r: float = 5.4,
ll1: float = -1.8, ll2: float = 1.9, p1: float = 0.8, p2: float = 0.8,
std_l: float = 0.5, std_r: float = 0.5, plan_y_end: float | None = None) -> dict[str, np.ndarray]:
out = {**plan_dict}
if plan_y_end is not None:
plan = plan_dict['plan'].copy()
x = plan[0, :, Plan.POSITION][:, 0]
plan[0, :, Plan.POSITION][:, 1] = plan_y_end * np.clip(x / 12.0, 0.0, 1.0)
out['plan'] = plan
edges = np.zeros((1, 2, len(X), 2), dtype=np.float32)
edges[0, 0, :, 0] = re_l
edges[0, 1, :, 0] = re_r
stds = np.zeros((1, 2, len(X), 2), dtype=np.float32)
stds[0, 0, :, 0] = std_l
stds[0, 1, :, 0] = std_r
lanes = np.zeros((1, 4, len(X), 2), dtype=np.float32)
lanes[0, 0, :, 0] = ll1 - 3.6
lanes[0, 1, :, 0] = ll1
lanes[0, 2, :, 0] = ll2
lanes[0, 3, :, 0] = ll2 + 3.6
probs = np.zeros((1, 8), dtype=np.float32)
probs[0, 3] = p1
probs[0, 5] = p2
out.update({'road_edges': edges, 'road_edges_stds': stds, 'lane_lines': lanes, 'lane_lines_prob': probs})
return out
class TestTurnPlanner(OpenpilotTestCase):
def test_untouched_highway_and_gentle_curves(self):
tp = TurnPlanner(wheelbase=2.89)
for i in range(60):
k = 0.01 * math.sin(i * 0.1)
out_k, out_a = tp.update(make_plan(k, 25.0), 25.0, k, True, False, k, 0.2)
assert out_k == k and out_a == 0.2
for i in range(60):
k = 0.025 * min(1.0, i / 20.0)
out_k, out_a = tp.update(make_plan(k, 6.0), 6.0, k, True, False, k, 0.2)
assert out_k == k and out_a == 0.2
def test_sign_preservation_and_magnitude_bounds(self):
tp = TurnPlanner(wheelbase=2.89)
ks = [-0.015] * 15 + [0.016, 0.05, 0.11, 0.14, 0.17, 0.18, 0.14, 0.08, 0.02, -0.01]
plan_r = make_plan(0.15, 3.0)
for k in ks:
out_k, _ = tp.update(plan_r, 3.0, k * 0.7, True, False, k, 0.0)
assert abs(out_k) <= abs(k) * 1.35 + 1e-9
if k > 0:
assert out_k >= 0.0
elif k < 0:
assert out_k <= 0.0
def test_zero_lag_on_turn_exit_unwinding(self):
tp = TurnPlanner(wheelbase=2.89)
plan_tight = make_plan(0.14, 4.0)
for i in range(25):
k = 0.14 * (i / 25.0)
tp.update(plan_tight, 4.0, k * 0.8, True, False, k)
for _ in range(15):
tp.update(plan_tight, 4.0, 0.14, True, False, 0.14)
for i in range(1, 20):
k = max(0.0, 0.14 * (1.0 - i / 15.0))
out_k, _ = tp.update(make_plan(k, 4.0), 4.0, k + 0.01, True, False, k)
assert abs(out_k - k) < 1e-3
def test_standstill_launch_and_mid_turn_pause(self):
tp = TurnPlanner(wheelbase=2.89)
for _ in range(10):
tp.update(make_plan(0.12, 0.0), 0.0, 0.0, True, False, 0.002)
outs = [tp.update(make_plan(0.12, 2.5), 2.5, 0.004 * i, True, False, 0.006 * i)[0] for i in range(1, 20)]
assert outs[10] < 0.006 * 11 - 0.01
tp.turn_psi = math.radians(30.0)
tp.update(make_plan(0.08, 0.0), 0.0, 0.05, True, False, 0.05)
assert tp.turn_psi >= math.radians(29.0)
resumed, _ = tp.update(make_plan(0.08, 2.0), 2.0, 0.05, True, False, 0.06)
assert resumed >= 0.05 - 1e-6
def test_odometry_curb_memory_and_rear_tire_clearance(self):
tp = TurnPlanner(wheelbase=2.89)
# 1) Live straight curb beside car holds early turn-in down
mo_curb = with_curb(make_plan(0.08, 5.0), e0=2.0, flare_5m=0.05, std=0.4)
out_live, _ = tp.update(mo_curb, 5.0, 0.0, True, False, 0.05)
assert tp.curb is not None and tp.curb[3] is True
assert out_live < 0.015
# 2) Curb exits cropped FOV (std=2.0): odometry remembers frozen corner and keeps protecting rear tire
mo_blind = with_curb(make_plan(0.14, 5.0), e0=4.0, flare_5m=1.5, std=2.0)
out_frozen, _ = tp.update(mo_blind, 5.0, 0.02, True, False, 0.14)
assert tp.curb is not None and tp.curb[3] is False
assert out_frozen < 0.14
# 3) Advance ~4.5 m so rear axle clears the remembered corner -> curb memory releases!
for _ in range(25):
tp.update(mo_blind, 5.0, 0.08, True, False, 0.12)
assert tp.curb is None
# 4) Normal curved road (curb curves with the road at k=0.03) passes untouched
tp2 = TurnPlanner(wheelbase=2.89)
mo_curve = with_curb(make_plan(0.03, 6.7), e0=2.4, flare_5m=0.375, std=0.4)
out_curve, _ = tp2.update(mo_curve, 6.7, 0.03, True, False, 0.03)
assert abs(out_curve - 0.03) < 1e-6
def test_apex_1s_path_boost_and_exit_unwind(self):
tp = TurnPlanner(wheelbase=2.89)
for _ in range(35):
tp.update(make_plan(0.14, 4.0), 4.0, 0.12, True, False, 0.10)
apex_out, _ = tp.update(make_plan(0.14, 4.0), 4.0, 0.12, True, False, 0.10)
assert apex_out > 0.115
for _ in range(20):
tp.update(make_plan(0.14, 4.0), 4.0, 0.12, True, False, 0.14)
exit_out, _ = tp.update(make_plan(0.10, 4.0), 4.0, 0.15, True, False, 0.20)
assert exit_out < 0.15
def test_rolling_turn_pre_slowing(self):
tp = TurnPlanner(wheelbase=2.89)
# Approaching a tight R=8 m corner (k=0.125) at 14 mph (6.3 m/s) -> pre-slows smoothly
_, a_slow = tp.update(make_plan(0.125, 6.3), 6.3, 0.0, True, False, 0.02, model_accel=0.2)
assert a_slow < -0.5
# Already slow at 7 mph (3.1 m/s) -> does not brake
_, a_ok = tp.update(make_plan(0.125, 3.1), 3.1, 0.0, True, False, 0.02, model_accel=0.2)
assert a_ok == 0.2
def test_closed_loop_90deg_stop_and_rolling_turns(self):
L, W_half, x_cam, lane_w, curb_r = 2.89, 0.96, 1.50, 3.60, 2.5
y_curb = lane_w / 2.0
x_dest = curb_r + lane_w / 2.0
x_yellow = x_dest + lane_w / 2.0
pts = [(x, 0.0) for x in np.linspace(-25, x_dest - 2.0, 250)]
pts += [(x_dest - 2.0 + 2.0 * math.cos(th), 2.0 + 2.0 * math.sin(th)) for th in np.linspace(-math.pi / 2, 0, 50)]
pts += [(x_dest, y) for y in np.linspace(2.0, 25.0, 250)]
ref = np.array(pts)
def run(v_init: float, use_planner: bool) -> tuple[float, float]:
X_p, Y_p, psi, k_act, k_ctl = -18.0, 0.0, 0.0, 0.0, 0.0
v = v_init
tp = TurnPlanner(wheelbase=L, dt=DT_MDL) if use_planner else None
min_clr, max_ovr = 99.0, -99.0
for _ in range(500):
xc, yc = X_p + x_cam * math.cos(psi), Y_p + x_cam * math.sin(psi)
i_near = int(np.argmin(np.hypot(ref[:, 0] - xc, ref[:, 1] - yc)))
i_tgt = i_near
while i_tgt < len(ref) - 1 and np.hypot(ref[i_tgt, 0] - xc, ref[i_tgt, 1] - yc) < 6.5:
i_tgt += 1
dx, dy = ref[i_tgt, 0] - xc, ref[i_tgt, 1] - yc
lx = dx * math.cos(psi) + dy * math.sin(psi)
ly = -dx * math.sin(psi) + dy * math.cos(psi)
k_mod = float(np.clip(2.0 * ly / max(lx**2 + ly**2, 1.0), -0.19, 0.19))
plan = make_plan(0.14 if (max(0.0, x_dest - xc) < 16.0 and psi < math.radians(75)) else 0.0, max(v, 1.0))
k_des, a_des = tp.update(plan, v, k_act, True, False, k_mod, 0.0) if tp else (k_mod, 0.0)
v = max(2.5, v + a_des * DT_MDL)
max_rate = 5.0 / max(v, 1.0) ** 2
k_ctl = float(np.clip(k_des, k_ctl - max_rate * DT_MDL, k_ctl + max_rate * DT_MDL))
k_ctl = float(np.clip(k_ctl, -min(0.2, 3.0 / max(v, 1.0) ** 2), min(0.2, 3.0 / max(v, 1.0) ** 2)))
k_act += (k_ctl - k_act) * (DT_MDL / (0.22 + DT_MDL))
ds = v * DT_MDL
psi += k_act * ds
X_p += ds * math.cos(psi)
Y_p += ds * math.sin(psi)
x_ir, y_ir = X_p - W_half * math.sin(psi), Y_p + W_half * math.cos(psi)
x_of, y_of = X_p + L * math.cos(psi) + W_half * math.sin(psi), Y_p + L * math.sin(psi) - W_half * math.cos(psi)
if x_ir <= 0.0:
clr = y_curb - y_ir
elif y_ir >= y_curb + curb_r:
clr = x_ir - curb_r
else:
clr = math.hypot(x_ir, y_ir - (y_curb + curb_r)) - curb_r
min_clr = min(min_clr, clr)
if y_of > 2.0:
max_ovr = max(max_ovr, x_of - x_yellow)
if Y_p > 15.0:
break
return min_clr, max_ovr
# Low-speed turn clears curb with margin and stays in lane
base_clr, _ = run(3.5, False)
plan_clr, plan_ovr = run(3.5, True)
assert base_clr < -0.5 and plan_clr > 0.20 and plan_ovr < 0.0
# Rolling 11 mph turn: baseline blows wide into oncoming lane; TurnPlanner pre-slows, clears curb, stays in lane
_, roll_base_ovr = run(4.9, False)
roll_plan_clr, roll_plan_ovr = run(4.9, True)
assert roll_base_ovr > 0.5 and roll_plan_clr > 0.15 and roll_plan_ovr < 0.0
def test_nearest_lane_exit_lock(self):
def finish_turn(sign: float, is_rhd: bool = False) -> TurnPlanner:
tp = TurnPlanner(wheelbase=2.89)
for _ in range(30):
tp.update(make_plan(0.12 * sign, 5.0), 5.0, 0.10 * sign, True, is_rhd, 0.10 * sign)
assert tp.exit_timer > 0.0 and tp.exit_sign == sign
return tp
# 1) Right turn exiting into lane 2 (full 3.5 m lane to right of ll2) -> pulls right into lane 1
tp_r = finish_turn(+1.0)
mo_lane2 = with_lanes_and_edges(make_plan(0.0, 6.0), re_r=5.4, ll2=1.9, p2=0.7)
out_r, _ = tp_r.update(mo_lane2, 6.0, 0.0, True, False, 0.0)
assert out_r > 0.008
# 2) Right turn beside 2.1 m bike lane/shoulder -> zero pull (never pulls into shoulder/bike lane)
tp_bike = finish_turn(+1.0)
mo_bike = with_lanes_and_edges(make_plan(0.0, 6.0), re_r=4.0, ll2=1.9, p2=0.9)
out_bike, _ = tp_bike.update(mo_bike, 6.0, 0.0, True, False, 0.0)
assert out_bike == 0.0
# 3) Right blindspot occupied -> suppressed
tp_bs = finish_turn(+1.0)
fn_bs = functools.partial(tp_bs.update, mo_lane2, 6.0, 0.0, True, False,
left_blindspot=False, right_blindspot=True)
out_bs, _ = fn_bs(0.0, 0.0)
assert out_bs == 0.0
# 4) Left turn drifting right of ll1 -> pulls left back to ll1 + 1.8 m, never crosses ll1 into oncoming
tp_l = finish_turn(-1.0)
mo_l_drift = with_lanes_and_edges(make_plan(0.0, 6.0), ll1=-1.5, p1=0.7, plan_y_end=+1.2)
out_l_drift, _ = tp_l.update(mo_l_drift, 6.0, 0.0, True, False, 0.0)
assert out_l_drift < -0.008
tp_l_ok = finish_turn(-1.0)
mo_l_ok = with_lanes_and_edges(make_plan(0.0, 6.0), ll1=-1.5, p1=0.7, plan_y_end=0.0)
out_l_ok, _ = tp_l_ok.update(mo_l_ok, 6.0, 0.0, True, False, 0.0)
assert out_l_ok == 0.0
# 5) RHD symmetry: left turn is curb-side -> pulls left when full lane exists to the left
tp_rhd = finish_turn(-1.0, is_rhd=True)
mo_rhd = with_lanes_and_edges(make_plan(0.0, 6.0), re_l=-5.4, ll1=-1.9, p1=0.7)
out_rhd, _ = tp_rhd.update(mo_rhd, 6.0, 0.0, True, True, 0.0)
assert out_rhd < -0.008
@@ -0,0 +1,285 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
from collections import deque
import numpy as np
from openpilot.common.realtime import DT_MDL
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan
T_IDXS = np.array(ModelConstants.T_IDXS, dtype=np.float32)
X_IDXS = np.array(ModelConstants.X_IDXS, dtype=np.float32)
# Physical geometry constants
SHIFT_WB_RATIO = 0.55 # windshield-camera-to-rear-axle fraction of wheelbase
REAR_KEEPOUT = 1.35 # m: half car width (~1.0 m) + curb safety margin (~0.35 m)
TURN_LAT_ACCEL = 1.8 # m/s^2: comfortable lat accel target for rolling-turn pre-slowing
LANE_HALF_W = 1.8 # m: standard half lane width for nearest-lane exit targeting
MIN_EXTRA_LANE_W = 2.7 # m: distinguishes a real adjacent lane from a shoulder/bike lane
EXIT_LAT_ACCEL_MAX = 0.8 # m/s^2: gentle cap for nearest-lane exit pull
def _plan_stats(model_output: dict[str, np.ndarray]) -> tuple[float, float, float]:
"""Return (peak_curv_18m, avg_curv_1s, yaw_18m) from model_output['plan']."""
plan_arr = model_output.get('plan')
if plan_arr is None or plan_arr.ndim < 3 or plan_arr.shape[1] < 3:
return 0.0, 0.0, 0.0
plan = plan_arr[0]
pos = plan[:, Plan.POSITION]
yaws = plan[:, Plan.T_FROM_CURRENT_EULER][:, 2]
s = np.concatenate(([0.0], np.cumsum(np.hypot(np.diff(pos[:, 0]), np.diff(pos[:, 1])))))
peak_k = 0.0
for i in range(len(yaws) - 2):
if s[i] < 1.0:
continue
if s[i] > 18.0:
break
seg_ds = s[i + 2] - s[i]
if seg_ds >= 0.8:
k = float((yaws[i + 2] - yaws[i]) / seg_ds)
if abs(k) > abs(peak_k):
peak_k = k
peak_k = float(np.clip(peak_k, -0.25, 0.25))
path_k_1s = 0.0
if len(yaws) == len(T_IDXS):
s1 = float(np.interp(1.0, T_IDXS, s))
if s1 >= 0.8:
path_k_1s = float(np.clip(np.interp(1.0, T_IDXS, yaws) / s1, -0.25, 0.25))
yaw_18m = float(np.interp(18.0, s, yaws)) if s[-1] >= 1.0 else 0.0
return peak_k, path_k_1s, yaw_18m
class TurnPlanner:
"""
Geometry-first turn planner for tight low-speed turns:
1. 2D odometry curb memory + exact rear-tire clearance circle (even after curb exits FOV).
2. Wheelbase viewpoint shift from windshield camera back toward rear axle (zero exit lag).
3. 1-second path blend through apex & exit (prevents wide apexes and exit hang-ups).
4. Nearest-lane exit lock (finishes turns in the lane closest to the turn direction).
5. Rolling-turn pre-slowing so rolling turns get stop-bar steering headroom.
"""
def __init__(self, wheelbase: float = 2.7, dt: float = DT_MDL):
self.wb = float(np.clip(wheelbase, 2.0, 4.0))
self.dt = dt
self.s = 0.0
self.buf_s: deque[float] = deque()
self.buf_k: deque[float] = deque()
self.turn_sign = 0.0
self.turn_psi = 0.0
self.exit_sign = 0.0
self.exit_timer = 0.0
# Remembered curb corner in rear-axle frame: (cx, cy, sign, live, k_live)
self.curb: tuple[float, float, float, bool, float] | None = None
def reset(self) -> None:
self.s = 0.0
self.buf_s.clear()
self.buf_k.clear()
self.turn_sign = 0.0
self.turn_psi = 0.0
self.exit_sign = 0.0
self.exit_timer = 0.0
self.curb = None
def _nearest_lane_dk(self, model_output: dict[str, np.ndarray], sign: float, is_rhd: bool,
v_ego: float, blindspot: bool) -> float:
"""Gentle curvature pull to finish a turn in the lane closest to the turn direction."""
if blindspot or sign == 0.0:
return 0.0
plan_arr = model_output.get('plan')
edges = model_output.get('road_edges')
edge_stds = model_output.get('road_edges_stds')
lanes = model_output.get('lane_lines')
lane_probs = model_output.get('lane_lines_prob')
if any(x is None for x in (plan_arr, edges, edge_stds, lanes, lane_probs)):
return 0.0
if edges.ndim < 4 or edge_stds.ndim < 4 or lanes.ndim < 4 or edges.shape[1] < 2 or lanes.shape[1] < 4:
return 0.0
pos = plan_arr[0, :, Plan.POSITION]
dx = np.diff(pos[:, 0])
stop_i = int(np.argmax(dx <= 0.0)) + 1 if np.any(dx <= 0.0) else len(pos)
if stop_i < 2 or float(pos[stop_i - 1, 0]) < 8.0:
return 0.0
x_look = min(12.0, float(pos[stop_i - 1, 0]))
plan_y = float(np.interp(x_look, pos[:stop_i, 0], pos[:stop_i, 1]))
probs = lane_probs[0, 1::2]
if len(probs) < 4:
return 0.0
max_dk = EXIT_LAT_ACCEL_MAX / max(v_ego, 3.0) ** 2
curb_side = (sign < 0.0) if is_rhd else (sign > 0.0)
if curb_side:
re_idx, ll_idx = (1, 2) if sign > 0.0 else (0, 1)
if float(edge_stds[0, re_idx, 0, 0]) >= 1.2:
return 0.0
re_x = float(np.interp(x_look, X_IDXS, edges[0, re_idx, :, 0])) * sign
ll_x = float(np.interp(x_look, X_IDXS, lanes[0, ll_idx, :, 0])) * sign
# Only pull if a full driving lane exists between us and the curb (never into a bike lane/shoulder)
if float(probs[ll_idx]) > 0.25:
if (re_x - ll_x) < MIN_EXTRA_LANE_W:
return 0.0
elif (re_x - plan_y * sign) < (LANE_HALF_W + MIN_EXTRA_LANE_W):
return 0.0
target_y = (re_x - LANE_HALF_W) * sign
else:
# Non-curb-side turn (e.g. left turn in LHD): anchor to inside lane line, NEVER crossing it
ll_idx = 1 if sign < 0.0 else 2
if float(probs[ll_idx]) < 0.25:
return 0.0
ll_x = float(np.interp(x_look, X_IDXS, lanes[0, ll_idx, :, 0])) * sign
target_y = (ll_x - LANE_HALF_W) * sign
err = (target_y - plan_y) * sign
if err <= 0.35:
return 0.0
return float(np.clip(2.0 * err / (x_look * x_look), 0.0, max_dk)) * sign
def _update_curb(self, model_output: dict[str, np.ndarray], ds: float, dpsi: float) -> None:
# Propagate remembered curb corner through ego motion (exact 2D rigid transform)
if self.curb is not None:
cx, cy, csign, _, _ = self.curb
dx, dy = cx - ds, cy
c, sn = math.cos(dpsi), math.sin(dpsi)
cx, cy = dx * c + dy * sn, -dx * sn + dy * c
if cx < -0.3 or cy * csign < -0.5 or (self.turn_sign != 0.0 and csign != self.turn_sign):
self.curb = None
else:
self.curb = (cx, cy, csign, False, 0.0)
edges = model_output.get('road_edges')
stds = model_output.get('road_edges_stds')
if self.turn_sign == 0.0 or edges is None or stds is None or edges.ndim < 4 or edges.shape[1] < 2:
return
idx = 1 if self.turn_sign > 0.0 else 0
edge_y = edges[0, idx, :, 0]
if len(edge_y) != len(X_IDXS) or float(stds[0, idx, 0, 0]) >= 0.80:
return
e0 = float(edge_y[0]) * self.turn_sign
flare = float(np.interp(5.0, X_IDXS, edge_y)) * self.turn_sign - e0
if 0.5 < e0 < 3.0 and flare < 0.65:
k_live = max(0.0, 2.0 * flare / 25.0) + 0.005
self.curb = (SHIFT_WB_RATIO * self.wb + 2.0, e0 * self.turn_sign, self.turn_sign, True, k_live)
def update(self, model_output: dict[str, np.ndarray], v_ego: float, actual_curv: float,
active: bool, is_rhd: bool, model_curv: float, model_accel: float = 0.0,
left_blindspot: bool = False, right_blindspot: bool = False,
enabled: bool = True) -> tuple[float, float]:
if not enabled or not active:
self.reset()
return model_curv, model_accel
if v_ego < 0.3:
if abs(actual_curv) < 0.02:
self.turn_psi = 0.0
self.turn_sign = 0.0
self.exit_sign = 0.0
self.exit_timer = 0.0
self.curb = None
self.buf_s = deque([self.s])
self.buf_k = deque([float(actual_curv)])
return model_curv, model_accel
ds = v_ego * self.dt
self.s += ds
self.buf_s.append(self.s)
self.buf_k.append(float(model_curv))
while len(self.buf_s) > 2 and (self.s - self.buf_s[0]) > 4.5:
self.buf_s.popleft()
self.buf_k.popleft()
speed_w = float(np.interp(v_ego, [7.5, 10.5], [1.0, 0.0]))
if speed_w <= 0.0:
self.turn_psi = 0.0
self.turn_sign = 0.0
self.exit_sign = 0.0
self.exit_timer = 0.0
self.curb = None
return model_curv, model_accel
plan_peak, path_k_1s, yaw_18m = _plan_stats(model_output)
curv_w = float(np.interp(max(abs(model_curv), abs(plan_peak)), [0.04, 0.09], [0.0, 1.0]))
ref_k = model_curv if abs(model_curv) > 0.015 else plan_peak
if abs(ref_k) > 0.035:
new_sign = 1.0 if ref_k > 0.0 else -1.0
if new_sign != self.turn_sign:
self.turn_sign = new_sign
self.turn_psi = 0.0
self.turn_psi = max(0.0, self.turn_psi + actual_curv * self.turn_sign * ds)
else:
self.turn_psi = max(0.0, self.turn_psi - 0.5 * self.dt)
if self.turn_psi < 0.02:
self.turn_sign = 0.0
self._update_curb(model_output, ds, actual_curv * ds)
out_k = model_curv
out_a = model_accel
psi_deg = math.degrees(self.turn_psi)
# 1) Entry protection: odometry curb memory (live curb wall + frozen rear-tire circle)
curb_limited = False
if self.curb is not None and out_k * self.curb[2] > 0.0 and psi_deg < 25.0:
cx, cy, csign, live, k_live = self.curb
if live:
k_lim = k_live
elif cx > 0.0:
cy_s = cy * csign
k_lim = max(0.0, 2.0 * (cy_s - REAR_KEEPOUT) / max(cx * cx + cy_s * cy_s - REAR_KEEPOUT ** 2, 0.25))
else:
k_lim = 1.0
if abs(out_k) > k_lim:
out_k = math.copysign(k_lim, out_k)
curb_limited = True
# 2) Entry protection: wheelbase viewpoint shift (works even with no visible curb; zero exit lag)
entry_w = float(np.interp(psi_deg, [8.0, 22.0], [1.0, 0.0]))
shift_spd = float(np.interp(v_ego, [3.5, 6.0, 8.5], [1.0, 0.35, 0.0]))
side_w = 1.0 if ((ref_k < 0.0) if is_rhd else (ref_k > 0.0)) else 0.70
shift = min(SHIFT_WB_RATIO * self.wb * shift_spd * curv_w * entry_w * side_w, v_ego * 0.45)
if shift >= 0.05 and len(self.buf_s) >= 2:
k_del = float(np.interp(self.s - shift, self.buf_s, self.buf_k))
k_sh = float(np.clip(k_del, 0.0, model_curv)) if model_curv >= 0.0 else float(np.clip(k_del, model_curv, 0.0))
if abs(k_sh) < abs(out_k):
out_k = k_sh
# 3) Apex & exit: blend with model's 1-second path curvature once past corner entry
apex_w = 0.65 * speed_w * curv_w * float(np.interp(psi_deg, [10.0, 25.0], [0.0, 1.0]))
if apex_w > 0.01 and out_k * path_k_1s > 0.0 and not curb_limited:
if abs(path_k_1s) > abs(out_k) or psi_deg > 60.0:
cap = abs(model_curv) * 1.35
out_k = (1.0 - apex_w) * out_k + apex_w * float(np.clip(path_k_1s, -cap, cap))
# 4) Nearest-lane exit lock: finish turns in the lane closest to the turn (active psi>=35 deg + 1.5s fade)
if psi_deg >= 35.0 and self.turn_sign != 0.0:
self.exit_sign = self.turn_sign
self.exit_timer = 1.5
elif self.exit_timer > 0.0:
self.exit_timer = max(0.0, self.exit_timer - self.dt)
if self.exit_timer <= 0.0:
self.exit_sign = 0.0
if self.exit_timer > 0.0 and not curb_limited:
bs = right_blindspot if self.exit_sign > 0.0 else left_blindspot
exit_w = min(1.0, self.exit_timer / 0.5) * speed_w
out_k += exit_w * self._nearest_lane_dk(model_output, self.exit_sign, is_rhd, v_ego, bs)
# 5) Rolling-turn pre-slowing: slow to comfortable turn speed before sharp corners
if abs(plan_peak) > 0.06 and abs(yaw_18m) > math.radians(35.0):
v_turn = math.sqrt(TURN_LAT_ACCEL / abs(plan_peak))
if v_ego > v_turn:
out_a = min(out_a, float(np.clip((v_turn - v_ego) * 0.8, -1.8, 0.0)))
return out_k, out_a