mirror of
https://github.com/sunnypilot/sunnypilot.git
synced 2026-11-23 22:53:45 +08:00
Compare commits
5 Commits
g70-2024-new
...
emt-test
| Author | SHA1 | Date | |
|---|---|---|---|
| 89995884e8 | |||
| 48b241fb6c | |||
| 11dc83736f | |||
| 2412ae892b | |||
| 75011ef0f0 |
@@ -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,9 @@ 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))
|
||||
prev_action = action
|
||||
fill_model_msg(modelv2_send, model_output, action,
|
||||
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
|
||||
|
||||
@@ -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,9 @@ 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))
|
||||
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,199 @@
|
||||
"""
|
||||
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
|
||||
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}
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
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. 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
|
||||
# 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.curb = None
|
||||
|
||||
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,
|
||||
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.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.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) 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
|
||||
Reference in New Issue
Block a user