diff --git a/openpilot/starpilot/conditional_mode/launch_geometry.py b/openpilot/starpilot/conditional_mode/launch_geometry.py new file mode 100644 index 0000000000..d90ac08361 --- /dev/null +++ b/openpilot/starpilot/conditional_mode/launch_geometry.py @@ -0,0 +1,44 @@ +"""Release-only candidate; never used to acquire a stop or validate road geometry.""" + +import math +from openpilot.selfdrive.modeld.constants import ModelConstants + + +def qualified_launch_horizon(model, car, lead_present): + if ( + car.standstill is not True + or car.vEgoRaw != 0.0 + or not -0.01 <= car.vEgo <= 0.01 + or car.gasPressed + or car.brakePressed + or lead_present + or model.action.shouldStop is not False + or not math.isfinite(model.action.desiredAcceleration) + or not 0.3 <= model.action.desiredAcceleration <= 10.0 + ): + return None + x, v, t = tuple(model.position.x), tuple(model.velocity.x), tuple(model.position.t) + vt = tuple(model.velocity.t) + if ( + len(t) != len(ModelConstants.T_IDXS) + or len(vt) != len(t) + or any(not math.isfinite(a) or abs(a - b) > 1e-5 for grid in (t, vt) for a, b in zip(grid, ModelConstants.T_IDXS, strict=True)) + ): + return None + if len(x) != 33 or len(v) != 33 or len(t) != 33 or not all(math.isfinite(a) for a in (*x, *v, *t)): + return None + if abs(x[0]) > 1e-6 or t[0] != 0 or any(b <= a for a, b in zip(t, t[1:], strict=False)): + return None + # A bounded launch-prediction prefix, not a general backtracking allowance. + debt = 0.0 + for i, (a, b) in enumerate(zip(x, x[1:], strict=False)): + if b < a: + debt += a - b + if t[i + 1] > 0.75 or max(abs(a), abs(b)) > 0.05 or debt > 0.05: + return None + if min(x) < -0.05 or max(x) > 500 or min(v) < -0.15 or max(v) > 100 or x[-1] < 54: + return None + tail = [a for a, stamp in zip(v, t, strict=True) if stamp >= 2.0] + if not tail or min(tail) < 0.3 or tail[-1] < 5 or any(b < a for a, b in zip(tail, tail[1:], strict=False)): + return None + return x[-1] diff --git a/openpilot/starpilot/conditional_mode/projection.py b/openpilot/starpilot/conditional_mode/projection.py index ba09b1ce9c..be44e78947 100644 --- a/openpilot/starpilot/conditional_mode/projection.py +++ b/openpilot/starpilot/conditional_mode/projection.py @@ -623,6 +623,19 @@ class SceneProjector: launch_horizon = stop_horizon if stop_horizon is not None else ( _standstill_clear_horizon(model) if model_transport_current else None) stationary_launch_clear = _stationary_launch_clear(model, car, lead, launch_horizon) + # Qualify a stationary launch release and keep it valid after clearing; never acquire a stop or + # qualify spatial/lead geometry from this bounded launch prefix. + if (not stationary_launch_clear and model_transport_current and car_valid and + control is not None and selfdrive is not None and control.enabled and control.longActive and selfdrive.enabled and + lead is not None and radar is not None): + from openpilot.starpilot.conditional_mode.launch_geometry import qualified_launch_horizon + try: + launch = qualified_launch_horizon(model, car, any(item.present for item in (radar.leadOne, radar.leadTwo))) + except (AttributeError, TypeError, ValueError, OverflowError): + launch = None + if launch is not None: + launch_horizon, stationary_launch_clear = launch, True + if stationary_launch_clear: # Continue a proven stationary launch after its stop commitment clears. # This bounded geometry cannot acquire a stop or qualify curve/lead data. diff --git a/openpilot/starpilot/conditional_mode/tests/test_launch_geometry.py b/openpilot/starpilot/conditional_mode/tests/test_launch_geometry.py new file mode 100644 index 0000000000..3c6fd06f9b --- /dev/null +++ b/openpilot/starpilot/conditional_mode/tests/test_launch_geometry.py @@ -0,0 +1,122 @@ +"""Recorded20Hz stationary launch: release-only prefix, unchanged red-hold guards.""" + +import gzip +import json +from pathlib import Path +from openpilot.starpilot.longitudinal.tests.test_cem_green_release import CemGreenCallerTests + + +class RecordedLaunchTests(CemGreenCallerTests): + def setUp(self): + super().setUp() + from unittest.mock import patch + from openpilot.cereal import messaging + from openpilot.selfdrive.modeld.constants import ModelConstants + from openpilot.starpilot.longitudinal.tests import test_cem_green_release as green + + original = green.serialized_scene + + def timed_scene(**kwargs): + payloads = original(**kwargs) + event = messaging.new_message('modelV2') + event.modelV2 = payloads['modelV2'] + event.modelV2.position.t = list(ModelConstants.T_IDXS) + event.modelV2.velocity.t = list(ModelConstants.T_IDXS) + payloads['modelV2'] = messaging.log_from_bytes(event.to_bytes()).modelV2 + if getattr(self, 'second_lead', False): + radar = messaging.new_message('radarState') + radar.radarState = payloads['radarState'] + radar.radarState.leadTwo.present = True + radar.radarState.leadTwo.dRel = 5.0 + payloads['radarState'] = messaging.log_from_bytes(radar.to_bytes()).radarState + return payloads + + self.enterContext(patch.object(green, 'serialized_scene', timed_scene)) + + def test_recorded_20hz_launch(self): + self.prime() + samples = json.loads(gzip.decompress((Path(__file__).parent / 'testdata/route160_stationary_launch.json.gz').read_bytes())) + release = None + for frame in samples: + _, _, held, plan = self.cycle(stopped=True, position=frame['x'], velocity=frame['v'], should_stop=frame['stop'], desired_accel=frame['accel']) + if frame['stop']: + self.assertTrue(held and plan.shouldStop) + if not held and release is None: + release = frame['t'] + if release is not None: + self.assertFalse(held or plan.shouldStop) + self.assertGreater(plan.aTarget, 0.0) + self.assertIsNotNone(release) + self.assertLess(release, 5953.0) + + def test_candidate_frame_rejects_red_lead_and_lost_authority(self): + samples = json.loads(gzip.decompress((Path(__file__).parent / 'testdata/route160_stationary_launch.json.gz').read_bytes())) + frame = next(f for f in samples if f['accel'] > 0.35 and min(f['x']) < -0.02) + for change in ( + {'should_stop': True}, + {'lead': True}, + {'aol': True}, + {'stale': 'carControl'}, + {'stale': 'selfdriveState'}, + {'repeat_model': True}, + {'lead_two': True}, + ): + self.owner.mode.projector.stop_detector.reset() + self.prime() + self.second_lead = change.get('lead_two', False) + for _ in range(18): + kwargs = {'stopped': True, 'position': frame['x'], 'velocity': frame['v'], 'should_stop': False, 'desired_accel': frame['accel']} + kwargs.update({k: v for k, v in change.items() if k != 'lead_two'}) + self.cycle(**kwargs) + if change.get('repeat_model'): + self.tick -= 1 # Keep source time fixed, not a newly stamped old-shaped frame. + self.second_lead = False + if change.get('aol'): + # Existing disengagement behavior clears the detector; a subsequent + # red stop must still acquire and hold after re-enabling. + self.prime() + else: + self.assertTrue(self.owner.mode.projector.stop_detector.committed, change) + + def test_candidate_clear_dwell_restarts_after_real_stop(self): + self.prime() + samples = json.loads(gzip.decompress((Path(__file__).parent / 'testdata/route160_stationary_launch.json.gz').read_bytes())) + frame = next(f for f in samples if f['accel'] > 0.35 and min(f['x']) < -0.02) + for stop in [False] * 6 + [True] + [False] * 6: + _, _, held, plan = self.cycle(stopped=True, position=frame['x'], velocity=frame['v'], should_stop=stop, desired_accel=frame['accel']) + self.assertTrue(held and plan.shouldStop) + self.assertLessEqual(plan.aTarget, 0.0) + + +def test_candidate_numeric_time_and_lead_guards(): + from copy import deepcopy + from types import SimpleNamespace as N + from openpilot.selfdrive.modeld.constants import ModelConstants + from openpilot.starpilot.conditional_mode.launch_geometry import qualified_launch_horizon + + samples = json.loads(gzip.decompress((Path(__file__).parent / 'testdata/route160_stationary_launch.json.gz').read_bytes())) + f = next(f for f in samples if f['accel'] > 0.35 and min(f['x']) < -0.02) + model = N( + position=N(x=f['x'], t=list(ModelConstants.T_IDXS)), + velocity=N(x=f['v'], t=list(ModelConstants.T_IDXS)), + action=N(shouldStop=False, desiredAcceleration=f['accel']), + ) + car = N(standstill=True, vEgoRaw=0.0, vEgo=0.0, gasPressed=False, brakePressed=False) + assert qualified_launch_horizon(model, car, False) > 54 + changes = [ + lambda m: setattr(m.velocity, 't', [0.0] * 33), + lambda m: m.position.t.__setitem__(-1, 1000.0), + lambda m: setattr(m.action, 'desiredAcceleration', 1000.0), + lambda m: m.position.x.__setitem__(20, 0.0), + lambda m: m.velocity.x.__setitem__(25, 0.0), + lambda m: setattr(m.action, 'shouldStop', True), + ] + for change in changes: + m = deepcopy(model) + change(m) + assert qualified_launch_horizon(m, car, False) is None + assert qualified_launch_horizon(model, car, True) is None + for name, value in [('standstill', False), ('vEgoRaw', 0.01), ('vEgo', 0.1), ('gasPressed', True), ('brakePressed', True)]: + c = deepcopy(car) + setattr(c, name, value) + assert qualified_launch_horizon(model, c, False) is None diff --git a/openpilot/starpilot/conditional_mode/tests/testdata/route160_stationary_launch.json.gz b/openpilot/starpilot/conditional_mode/tests/testdata/route160_stationary_launch.json.gz new file mode 100644 index 0000000000..db13668e5a Binary files /dev/null and b/openpilot/starpilot/conditional_mode/tests/testdata/route160_stationary_launch.json.gz differ