diff --git a/openpilot/selfdrive/controls/controlsd.py b/openpilot/selfdrive/controls/controlsd.py index 2f88f3af04..524ca8782a 100755 --- a/openpilot/selfdrive/controls/controlsd.py +++ b/openpilot/selfdrive/controls/controlsd.py @@ -49,6 +49,7 @@ from openpilot.starpilot.lateral.lane_feedback import feedback_message from openpilot.starpilot.lateral.lane_clearance import current_delay, interface_dimensions from openpilot.starpilot.lateral.lane_change_preferences import LiveLaneChangePolicy from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate +from openpilot.starpilot.lateral.auto_lane_change import paired_clocks_ns from openpilot.starpilot.lateral.lane_runtime import LaneCenteringHost, runtime_supported as lane_runtime_supported from openpilot.starpilot.lateral.torque_runtime import TorqueHost, runtime_enabled as torque_runtime_enabled from openpilot.starpilot.feature_capabilities import lateral_supported @@ -575,6 +576,10 @@ class Controls: previous_curvature = self.desired_curvature lane_policy_now_ns = int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns() self.refresh_lane_change_policy(CS, model_v2, lane_policy_now_ns) + turn_now_ns, turn_boot_ns, turn_skew_ns = paired_clocks_ns() + intersection_turn = self.lane_change_smoother.turn_evidence.observe( + self.sm, model_v2, model_ns=int(self.sm.logMonoTime["modelV2"]), now_ns=turn_now_ns, now_boot_ns=turn_boot_ns, + valid=bool(self.sm.all_checks(["modelV2"])), enabled=assist_ready, clock_skew_ns=turn_skew_ns) factor = self.lane_change_smoother.factor( active=bool(CC.latActive and CS.canValid and not CS.canTimeout and self.sm.all_checks(['modelV2']) and self.lane_change_policy.enabled), lane_change_state=model_v2.meta.laneChangeState, @@ -583,7 +588,7 @@ class Controls: duration=self.lane_change_policy.duration_s, previous=previous_curvature, desired=new_desired_curvature, - turn_assist=assist, + turn_assist=assist, intersection_turn=intersection_turn, ) new_desired_curvature = limit_rate(CS.vEgo, previous_curvature, new_desired_curvature, factor) self.desired_curvature, curvature_limited = clip_curvature(CS.vEgo, previous_curvature, new_desired_curvature, lp.roll) diff --git a/openpilot/selfdrive/modeld/modeld.py b/openpilot/selfdrive/modeld/modeld.py index c8e926a7ae..fbb00af1ee 100644 --- a/openpilot/selfdrive/modeld/modeld.py +++ b/openpilot/selfdrive/modeld/modeld.py @@ -682,11 +682,16 @@ def main(demo=False): auto_evidence(sm, modelv2_send.modelV2, direction, runtime_lane_policy.minimum_lane_width_m, now_mono_ns=mono_now_ns, now_boot_ns=boot_now_ns, model_valid=bool(modelv2_send.valid), vehicle_capable=auto_vehicle_capable)) + signal_turn = navigation_turn.signal_model.observe( + sm, modelv2_send.modelV2, model_ns=int(modelv2_send.logMonoTime), now_ns=mono_now_ns, now_boot_ns=boot_now_ns, + valid=bool(modelv2_send.valid), enabled=bool(turn_supported and navigation_turn.steering_capable and + runtime_lane_policy.turn_signal_guidance), + clock_skew_ns=clock_skew_ns, lane_change_state=DH.lane_change_state) engaged = bool(sm['carControl'].latActive) DH.update(car_state, sm['carControl'].latActive, lane_change_prob, auto_evidence=auto_ready, engaged=auto_trigger_engaged(sm, runtime_lane_policy, openpilot_longitudinal=bool(CP.openpilotLongitudinalControl), now_mono_ns=mono_now_ns), - navigation_turn=matching_turn_signal(sm, mono_now_ns, supported=turn_supported)) + navigation_turn=signal_turn or matching_turn_signal(sm, mono_now_ns, supported=turn_supported)) modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction diff --git a/openpilot/starpilot/lateral/lane_change_smoothing.py b/openpilot/starpilot/lateral/lane_change_smoothing.py index 7a1e10382d..c7ddc08dfc 100644 --- a/openpilot/starpilot/lateral/lane_change_smoothing.py +++ b/openpilot/starpilot/lateral/lane_change_smoothing.py @@ -4,12 +4,14 @@ import math from openpilot.cereal import log from openpilot.common.realtime import DT_CTRL +from openpilot.starpilot.lateral.signal_turn import SignalTurnEvidence from openpilot.selfdrive.controls.lib.desire_helper import LANE_CHANGE_SPEED_MIN from openpilot.selfdrive.controls.lib.drive_helpers import MAX_LATERAL_JERK, MIN_SPEED class LaneChangeSmoother: def __init__(self): + self.turn_evidence = SignalTurnEvidence() self.reset() def reset(self): @@ -18,7 +20,7 @@ class LaneChangeSmoother: self.previous_factor = 1.0 self.intersection_maneuver = False - def factor(self, *, active, lane_change_state, speed, minimum_speed, duration, previous, desired, turn_assist=False): + def factor(self, *, active, lane_change_state, speed, minimum_speed, duration, previous, desired, turn_assist=False, intersection_turn=False): if (not active or not all(math.isfinite(value) for value in (speed, minimum_speed, duration, previous, desired)) or not 3.0 < duration <= 8.0): self.reset() @@ -30,8 +32,8 @@ class LaneChangeSmoother: # accelerates across the highway lane-change floor. Finish that exemption # before admitting pacing for a new maneuver. intersection = bool(turn_assist and maneuver and - (speed < LANE_CHANGE_SPEED_MIN or self.intersection_maneuver)) - if turn_assist and (speed < LANE_CHANGE_SPEED_MIN or self.intersection_maneuver): + (speed < LANE_CHANGE_SPEED_MIN or intersection_turn or self.intersection_maneuver)) + if turn_assist and (speed < LANE_CHANGE_SPEED_MIN or intersection_turn or self.intersection_maneuver): self.reset() self.intersection_maneuver = intersection return 1.0 diff --git a/openpilot/starpilot/lateral/signal_turn.py b/openpilot/starpilot/lateral/signal_turn.py new file mode 100644 index 0000000000..f9f9876391 --- /dev/null +++ b/openpilot/starpilot/lateral/signal_turn.py @@ -0,0 +1,88 @@ +"""Source-bound turn forecasts distinguish slowing intersections from lane changes.""" +import math + +from openpilot.cereal import log +from openpilot.starpilot.lateral.auto_lane_change import boottime_ns + +MAX_AGE_NS = 150_000_000 +CONFIRM_NS = 100_000_000 +MAX_SPEED_MPS = 14. + + +class SignalTurnEvidence: + def __init__(self): + self.reset() + + def reset(self): + self.key = None + self.since_ns = self.model_ns = self.eof_ns = 0 + self.ready = False + + @staticmethod + def context(sm, now_ns): + try: + car, control, device, plan = (sm[name] for name in ('carState', 'carControl', 'deviceState', 'longitudinalPlan')) + drive = device.startedMonoTime + for name, age in (('carState', 100_000_000), ('carControl', 100_000_000), + ('deviceState', 2_000_000_000), ('longitudinalPlan', MAX_AGE_NS)): + stamp, received = sm.logMonoTime[name], int(sm.recv_time[name] * 1e9) + if (not sm.valid[name] or not sm.alive[name] or not 0 < drive <= stamp <= now_ns <= stamp + age or + not drive <= received <= now_ns <= received + age): + return None + direction = -1 if car.leftBlinker and not car.rightBlinker else 1 if car.rightBlinker and not car.leftBlinker else 0 + if (not device.started or not control.latActive or not car.canValid or car.canTimeout or car.standstill or + car.steerFaultTemporary or car.steerFaultPermanent or str(car.gearShifter) != 'drive' or not direction or + car.leftBlindspot and direction == -1 or car.rightBlindspot and direction == 1 or + not math.isfinite(car.vEgo) or not .1 < car.vEgo < MAX_SPEED_MPS or + not math.isfinite(car.aEgo) or car.aEgo > -.5 or plan.shouldStop or + not drive <= plan.modelMonoTime <= sm.logMonoTime['longitudinalPlan']): + return None + return int(drive), direction + except (AttributeError, KeyError, TypeError, ValueError, OverflowError): + return None + + def current(self, sm, now_ns, *, now_boot_ns=None): + boot = boottime_ns() if now_boot_ns is None else now_boot_ns + return bool(self.ready and self.key == self.context(sm, now_ns) and + 0 < self.model_ns <= now_ns <= self.model_ns + MAX_AGE_NS and + 0 < self.eof_ns <= boot <= self.eof_ns + MAX_AGE_NS) + + def observe(self, sm, model, *, model_ns, now_ns, now_boot_ns, valid, enabled, clock_skew_ns=0, lane_change_state=None): + key = self.context(sm, now_ns) if enabled else None + try: + if (key is None or not valid or not 0 <= clock_skew_ns <= 1_000_000 or + not 0 < model_ns <= now_ns <= model_ns + MAX_AGE_NS or + not 0 < model.timestampEof <= now_boot_ns <= model.timestampEof + MAX_AGE_NS or model.action.shouldStop): + self.reset() + return False + prediction = tuple(model.meta.desirePrediction) + if len(prediction) != 32 or not all(math.isfinite(x) and 0 <= x <= 1 for x in prediction): + self.reset() + return False + direction = int(log.Desire.turnLeft if key[1] == -1 else log.Desire.turnRight) + opposite = int(log.Desire.turnRight if key[1] == -1 else log.Desire.turnLeft) + for offset in range(0, 32, 8): + if abs(sum(prediction[offset:offset + 8]) - 1.) > .01: + self.reset() + return False + # Forecasts, rather than desireState, avoid reusing an injected desire as evidence. + if any(prediction[offset + direction] < .6 or prediction[offset + opposite] > .2 or + prediction[offset + int(log.Desire.laneChangeLeft)] + prediction[offset + int(log.Desire.laneChangeRight)] > .2 + for offset in (0, 8, 16)): + self.reset() + return False + state = model.meta.laneChangeState if lane_change_state is None else lane_change_state + ongoing = state in (log.LaneChangeState.laneChangeStarting, log.LaneChangeState.laneChangeFinishing) + if ongoing and not self.ready: + self.reset() + return False + if key != self.key or model_ns < self.model_ns or model_ns > self.model_ns + MAX_AGE_NS: + self.reset() + self.key, self.since_ns = key, model_ns + if model_ns > self.model_ns: + self.model_ns, self.eof_ns = model_ns, int(model.timestampEof) + self.ready = model_ns - self.since_ns >= CONFIRM_NS + return self.current(sm, now_ns, now_boot_ns=now_boot_ns) + except (AttributeError, KeyError, TypeError, ValueError, OverflowError): + self.reset() + return False diff --git a/openpilot/starpilot/lateral/tests/fixtures/signal_turn_forecasts.json b/openpilot/starpilot/lateral/tests/fixtures/signal_turn_forecasts.json new file mode 100644 index 0000000000..0c9c358917 --- /dev/null +++ b/openpilot/starpilot/lateral/tests/fixtures/signal_turn_forecasts.json @@ -0,0 +1,394 @@ +{ + "left_forecast": [ + { + "dt_ns": 0, + "prediction": [ + 0.2517191171646118, + 0.6845842599868774, + 0.053305305540561676, + 0.002806614385917783, + 0.00031921351910568774, + 0.004733010195195675, + 0.002532290294766426, + 2.2304607227852102e-07, + 0.200195774435997, + 0.740424394607544, + 0.04771728813648224, + 0.004698011092841625, + 0.000659082317724824, + 0.004054173827171326, + 0.002251056022942066, + 1.7229841375865362e-07, + 0.21075284481048584, + 0.727595329284668, + 0.04768043011426926, + 0.006346132140606642, + 0.000841981265693903, + 0.004430876113474369, + 0.00235229404643178, + 1.566101843764045e-07, + 0.24916012585163116, + 0.6858150959014893, + 0.04980456829071045, + 0.0064636776223778725, + 0.0013114067260175943, + 0.00496078422293067, + 0.0024842247366905212, + 1.1507084707318427e-07 + ], + "speed": 12.559648513793945, + "acceleration": -2.9386351108551025 + }, + { + "dt_ns": 49337563, + "prediction": [ + 0.14192910492420197, + 0.8345760703086853, + 0.012921926565468311, + 0.0020893672481179237, + 0.00012106307985959575, + 0.007204725872725248, + 0.0011574962409213185, + 1.3289020728279866e-07, + 0.10489256680011749, + 0.8730593919754028, + 0.011380820535123348, + 0.0034567248076200485, + 0.0002993766393046826, + 0.005941532552242279, + 0.0009694910841062665, + 1.0449315368532552e-07, + 0.11046990752220154, + 0.8648601174354553, + 0.012043105438351631, + 0.004923455882817507, + 0.0003493419208098203, + 0.006332709453999996, + 0.0010212056804448366, + 9.235603215529409e-08, + 0.13670232892036438, + 0.8366432785987854, + 0.013408210128545761, + 0.004600076470524073, + 0.0005573534872382879, + 0.006972160190343857, + 0.0011165407486259937, + 7.191877671175462e-08 + ], + "speed": 12.418076515197754, + "acceleration": -2.8973944187164307 + }, + { + "dt_ns": 98056941, + "prediction": [ + 0.22506320476531982, + 0.624922513961792, + 0.1412457972764969, + 0.0018387612653896213, + 0.0005084274453110993, + 0.00417677965015173, + 0.002244270406663418, + 2.8155454856459983e-07, + 0.19552582502365112, + 0.6683225035667419, + 0.1266232132911682, + 0.002645330736413598, + 0.0009941289899870753, + 0.0037794087547808886, + 0.002109369495883584, + 2.2924909615085198e-07, + 0.21779009699821472, + 0.6493634581565857, + 0.12183461338281631, + 0.0033556248527020216, + 0.0011536605888977647, + 0.0042364755645394325, + 0.002265849383547902, + 1.9479674051581242e-07, + 0.265501469373703, + 0.6022194027900696, + 0.11968119442462921, + 0.0036460047122091055, + 0.0017883672844618559, + 0.004770516883581877, + 0.002392821479588747, + 1.5143668008477107e-07 + ], + "speed": 12.271668434143066, + "acceleration": -2.9126951694488525 + }, + { + "dt_ns": 149563855, + "prediction": [ + 0.1507800966501236, + 0.7993219494819641, + 0.04284306988120079, + 0.0015983586199581623, + 0.0001650308258831501, + 0.003593946574255824, + 0.0016974747413769364, + 1.6430692539870506e-07, + 0.12262430787086487, + 0.8308331966400146, + 0.03855994716286659, + 0.0028526177629828453, + 0.0003249606234021485, + 0.0032589181791990995, + 0.0015459390124306083, + 1.3776917739960481e-07, + 0.136449933052063, + 0.8127506971359253, + 0.04077418893575668, + 0.00404142402112484, + 0.0003945830394513905, + 0.003867587074637413, + 0.0017214391846209764, + 1.242146367985697e-07, + 0.1664714515209198, + 0.7787107229232788, + 0.04360231012105942, + 0.0041067758575081825, + 0.0006542212795466185, + 0.004580454435199499, + 0.0018739830702543259, + 1.0146449369585753e-07 + ], + "speed": 12.13661003112793, + "acceleration": -2.827855110168457 + } + ], + "right_forecast": [ + { + "dt_ns": 0, + "prediction": [ + 0.14399610459804535, + 0.0018468290800228715, + 0.7772950530052185, + 3.228439891245216e-05, + 0.003104032250121236, + 0.01965775340795517, + 0.054067619144916534, + 4.116242848795082e-07, + 0.1445188969373703, + 0.002679640892893076, + 0.747387707233429, + 6.28245688858442e-05, + 0.006948428228497505, + 0.027039706707000732, + 0.07136227190494537, + 5.040000132794376e-07, + 0.1507185399532318, + 0.0033021981362253428, + 0.7212076187133789, + 0.00012578669702634215, + 0.007537933997809887, + 0.03121154196560383, + 0.08589591830968857, + 4.287647072942491e-07, + 0.15581217408180237, + 0.0035524459090083838, + 0.7173025608062744, + 0.00014762976206839085, + 0.008999636396765709, + 0.030394520610570908, + 0.08379078656435013, + 3.103942844973062e-07 + ], + "speed": 12.956438064575195, + "acceleration": -0.7823941111564636 + }, + { + "dt_ns": 52033960, + "prediction": [ + 0.11420727521181107, + 0.0018102733884006739, + 0.8329049348831177, + 2.416104507574346e-05, + 0.0036391171161085367, + 0.010978790931403637, + 0.03643515333533287, + 3.7097188965162786e-07, + 0.1149366945028305, + 0.0026387323159724474, + 0.8103874921798706, + 5.637149661197327e-05, + 0.008177746087312698, + 0.015237663872539997, + 0.048564717173576355, + 4.94087998959003e-07, + 0.125924751162529, + 0.0034008307848125696, + 0.7813695073127747, + 0.00010704118176363409, + 0.009179690852761269, + 0.018776224926114082, + 0.06124156713485718, + 4.1454109123151284e-07, + 0.1353694498538971, + 0.003868239000439644, + 0.769148588180542, + 0.00014240991731639951, + 0.010028498247265816, + 0.01931806094944477, + 0.06212446093559265, + 3.131616779228352e-07 + ], + "speed": 12.910385131835938, + "acceleration": -0.8441282510757446 + }, + { + "dt_ns": 100946175, + "prediction": [ + 0.11112934350967407, + 0.0013723386218771338, + 0.8208386898040771, + 1.6238824173342437e-05, + 0.0032898709177970886, + 0.014979529194533825, + 0.04837360978126526, + 3.7009277775723604e-07, + 0.11168589442968369, + 0.0019447735976427794, + 0.7942485809326172, + 3.904109325958416e-05, + 0.007009292021393776, + 0.02034684829413891, + 0.0647251307964325, + 4.871073997492203e-07, + 0.12048284709453583, + 0.0024434071965515614, + 0.7662124633789062, + 7.175466453190893e-05, + 0.00736248167231679, + 0.02380603365600109, + 0.07962056249380112, + 3.9672136153967585e-07, + 0.13052070140838623, + 0.0029067406430840492, + 0.7552695870399475, + 9.76076116785407e-05, + 0.008114641532301903, + 0.023957140743732452, + 0.07913327217102051, + 3.051759449590463e-07 + ], + "speed": 12.864348411560059, + "acceleration": -0.8763702511787415 + }, + { + "dt_ns": 151511553, + "prediction": [ + 0.12022392451763153, + 0.004121023695915937, + 0.8344688415527344, + 2.739852607192006e-05, + 0.0027433147188276052, + 0.015108815394341946, + 0.023306356742978096, + 3.907180143869482e-07, + 0.12051219493150711, + 0.005465234164148569, + 0.8205814361572266, + 5.401772796176374e-05, + 0.004709949251264334, + 0.01833469048142433, + 0.030342020094394684, + 4.69789711132762e-07, + 0.1385597437620163, + 0.006833148188889027, + 0.7895673513412476, + 9.95996524579823e-05, + 0.004804557655006647, + 0.021185999736189842, + 0.03894925117492676, + 3.9097221815609373e-07, + 0.1569688767194748, + 0.008147699758410454, + 0.7675970792770386, + 0.00014080028631724417, + 0.005245060659945011, + 0.021282393485307693, + 0.04061771556735039, + 3.044337120172713e-07 + ], + "speed": 12.825695991516113, + "acceleration": -0.8314024209976196 + } + ], + "lane_change_negatives": [ + { + "direction": -1, + "prediction": [ + 0.6595547199249268, + 0.005394125357270241, + 0.05791579559445381, + 0.26746809482574463, + 0.002742513082921505, + 0.0008440061355940998, + 0.006080400664359331, + 3.295378974144114e-07, + 0.5508841872215271, + 0.005007042083889246, + 0.0711447224020958, + 0.3643110692501068, + 0.0013703256845474243, + 0.000749188766349107, + 0.006533204112201929, + 2.798424532102217e-07, + 0.5737854838371277, + 0.00696712639182806, + 0.09581083059310913, + 0.3126314878463745, + 0.0024703044909983873, + 0.000964868871960789, + 0.007369672879576683, + 2.843283652964601e-07, + 0.707490861415863, + 0.010692724958062172, + 0.11685094237327576, + 0.1499822437763214, + 0.004471973981708288, + 0.0013867865782231092, + 0.009124205447733402, + 2.8463884405027784e-07 + ] + }, + { + "direction": 1, + "prediction": [ + 0.5278466939926147, + 0.0006761957192793489, + 0.006499207112938166, + 0.0002219110756414011, + 0.46117615699768066, + 0.0004377840959932655, + 0.0031419238075613976, + 1.225279646632771e-07, + 0.3955632448196411, + 0.0007739472785033286, + 0.006069717928767204, + 0.0007188228191807866, + 0.5937000513076782, + 0.00043661557720042765, + 0.0027374711353331804, + 1.1076579653490626e-07, + 0.35594555735588074, + 0.0010346401249989867, + 0.006801532581448555, + 0.0012882715091109276, + 0.6317903399467468, + 0.0004743319295812398, + 0.0026651264633983374, + 1.0893887036900196e-07, + 0.6258675456047058, + 0.002370727015659213, + 0.014617660082876682, + 0.0032970458269119263, + 0.3476628363132477, + 0.0008900907705537975, + 0.005293908063322306, + 1.6385111223371496e-07 + ] + } + ] +} diff --git a/openpilot/starpilot/lateral/tests/test_signal_turn.py b/openpilot/starpilot/lateral/tests/test_signal_turn.py new file mode 100644 index 0000000000..db319371f7 --- /dev/null +++ b/openpilot/starpilot/lateral/tests/test_signal_turn.py @@ -0,0 +1,202 @@ +"""Forecast-qualified turns preserve lane changes, source guards and native limits.""" +from types import SimpleNamespace as NS +from unittest.mock import patch + +import pytest + +from opendbc.car import structs +from openpilot.cereal import log +from openpilot.common.params import Params +from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper +from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature +from openpilot.starpilot.lateral.lane_change_preferences import KEY, LaneChangePolicy, to_value +from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate +from openpilot.starpilot.lateral.signal_turn import SignalTurnEvidence +from openpilot.starpilot.navigation.intent import TurnIntent + +BASE, DRIVE, OFFSET = 10_000_000_000, 9_000_000_000, 2_000_000_000 + + +def forecast(desire, probability=.75): + row = [0.] * 8 + row[0], row[int(desire)] = 1. - probability, probability + return row * 4 + + +def frame(tick, direction=-1): + now = BASE + tick * 50_000_000 + class SM(dict): + pass + model = log.ModelDataV2.new_message(timestampEof=now + OFFSET) + model.meta.desirePrediction = forecast(log.Desire.turnLeft if direction == -1 else log.Desire.turnRight) + car = structs.CarState.new_message(vEgo=12., aEgo=-1., canValid=True, gearShifter='drive', + leftBlinker=direction == -1, rightBlinker=direction == 1) + sm = SM(carState=car, carControl=NS(latActive=True), deviceState=NS(started=True, startedMonoTime=DRIVE), + longitudinalPlan=NS(shouldStop=False, modelMonoTime=now), modelV2=model) + sm.valid, sm.alive = dict.fromkeys(sm, True), dict.fromkeys(sm, True) + sm.logMonoTime, sm.recv_time = dict.fromkeys(sm, now), dict.fromkeys(sm, now / 1e9) + return sm, now, model + + +def observe(owner, tick, direction=-1, change=None, **kwargs): + sm, now, model = frame(tick, direction) + if change is not None: + change(sm, model) + args = {'model_ns': sm.logMonoTime['modelV2'], 'now_ns': now, 'now_boot_ns': now + OFFSET, 'valid': True, 'enabled': True} + return owner.observe(sm, model, **(args | kwargs)), sm, now + + +@pytest.mark.parametrize('direction', [-1, 1]) +def test_confirmed_forecast_admits_earlier_hint_and_cancels_pending_lane_change(tmp_path, direction): + params = Params(str(tmp_path)) + params.put(KEY, to_value(LaneChangePolicy()), block=True) + cp = structs.CarParams.new_message(carFingerprint='real', brand='hyundai', steerControlType='torque') + cp.safetyConfigs = [structs.CarParams.SafetyConfig.new_message(safetyModel='hyundaiCanfd')] + intent, helper = TurnIntent(params, cp), DesireHelper() + for tick in range(5): + sm, now, model = frame(tick, direction) + with patch('openpilot.starpilot.lateral.signal_turn.boottime_ns', return_value=now + OFFSET): + selected = intent.select(sm, now, helper.desire, supported=True, model_stop=False) + ready = intent.signal_model.observe(sm, model, model_ns=now, now_ns=now, now_boot_ns=now + OFFSET, + valid=True, enabled=True, lane_change_state=helper.lane_change_state) + helper.update(sm['carState'], True, 1., navigation_turn=ready) + if tick == 0: + assert helper.lane_change_state == log.LaneChangeState.preLaneChange + if tick < 3: + assert selected == log.Desire.none + else: + assert selected == (log.Desire.turnLeft if direction == -1 else log.Desire.turnRight) + assert helper.lane_change_state == log.LaneChangeState.off + sm['carState'].steeringPressed = True + with patch('openpilot.starpilot.lateral.signal_turn.boottime_ns', return_value=now + OFFSET): + assert intent.select(sm, now, helper.desire, supported=True, model_stop=False) == log.Desire.none + helper.update(sm['carState'], True, 1., navigation_turn=ready) + assert helper.lane_change_state == log.LaneChangeState.off + + +@pytest.mark.parametrize('direction', [-1, 1]) +def test_ordinary_lane_changes_and_existing_maneuvers_are_not_reclassified(direction): + evidence, helper = SignalTurnEvidence(), DesireHelper() + for tick in range(5): + def lane(sm, model, tick=tick): + model.meta.desirePrediction = forecast(log.Desire.laneChangeLeft if direction == -1 else log.Desire.laneChangeRight) + model.meta.desireState = forecast(log.Desire.turnLeft if direction == -1 else log.Desire.turnRight)[:8] + sm['carState'].steeringPressed = tick > 0 + sm['carState'].steeringTorque = 1. if direction == -1 else -1. + ready, sm, _ = observe(evidence, tick, direction, lane) + assert not ready + helper.update(sm['carState'], True, 1., navigation_turn=ready) + assert helper.desire == (log.Desire.laneChangeLeft if direction == -1 else log.Desire.laneChangeRight) + for tick in range(5, 10): + assert not observe(evidence, tick, direction, + lambda sm, model: setattr(model.meta, 'laneChangeState', log.LaneChangeState.laneChangeStarting))[0] + + +@pytest.mark.parametrize('field,value', [('standstill', True), ('canValid', False), ('canTimeout', True), + ('steerFaultTemporary', True), ('steerFaultPermanent', True), ('gearShifter', 'reverse'), ('rightBlinker', True), + ('leftBlindspot', True), ('vEgo', 14.), ('vEgo', float('nan')), ('aEgo', 0.), ('aEgo', float('inf'))]) +def test_vehicle_guards_withdraw_confirmation(field, value): + owner = SignalTurnEvidence() + for tick in range(3): + ready, _, _ = observe(owner, tick) + assert ready + assert not observe(owner, 3, change=lambda sm, model: setattr(sm['carState'], field, value))[0] + + +@pytest.mark.parametrize('service', ['carState', 'carControl', 'deviceState', 'longitudinalPlan']) +@pytest.mark.parametrize('failure', ['stale', 'future', 'dead', 'invalid', 'receipt']) +def test_source_guards(service, failure): + def change(sm, model): + if failure == 'stale': + sm.logMonoTime[service] = DRIVE - 2_000_000_000 + if failure == 'future': + sm.logMonoTime[service] += 1 + if failure == 'dead': + sm.alive[service] = False + if failure == 'invalid': + sm.valid[service] = False + if failure == 'receipt': + sm.recv_time[service] = (DRIVE - 2_000_000_000) / 1e9 + owner = SignalTurnEvidence() + for tick in range(3): + observe(owner, tick) + assert not observe(owner, 3, change=change)[0] + + +def test_invalid_forecasts_stops_disabling_and_suspend_refuse_turn(): + changes = [lambda sm, m: setattr(m.action, 'shouldStop', True), + lambda sm, m: setattr(sm['longitudinalPlan'], 'shouldStop', True), + lambda sm, m: setattr(sm['carControl'], 'latActive', False), + lambda sm, m: setattr(sm['deviceState'], 'started', False), + lambda sm, m: setattr(m, 'timestampEof', 1), + lambda sm, m: setattr(m.meta, 'desirePrediction', [0.] * 32), + lambda sm, m: setattr(m.meta, 'desirePrediction', [float('nan')] * 32), + lambda sm, m: setattr(m.meta, 'desirePrediction', forecast(log.Desire.turnRight)), + lambda sm, m: setattr(m.meta, 'desirePrediction', forecast(log.Desire.turnLeft)[:8])] + for change in changes: + owner = SignalTurnEvidence() + for tick in range(3): + observe(owner, tick) + assert not observe(owner, 3, change=change)[0] + owner = SignalTurnEvidence() + for tick in range(3): + ready, sm, now = observe(owner, tick) + assert ready + assert not owner.current(sm, now, now_boot_ns=now + OFFSET + 1_000_000_000) + assert not observe(owner, 3, clock_skew_ns=1_000_001)[0] + assert not observe(owner, 4, enabled=False)[0] + assert not observe(owner, 5, valid=False)[0] + + +def test_repeated_frames_cannot_confirm(): + owner = SignalTurnEvidence() + for tick in range(3): + assert not observe(owner, tick, change=lambda sm, model: sm.logMonoTime.__setitem__('modelV2', BASE))[0] + + +def test_forecast_exemption_retains_native_curvature_and_jerk_guard(): + smoother, previous = LaneChangeSmoother(), 0. + for tick in range(200): + state = log.LaneChangeState.laneChangeStarting if tick < 150 else log.LaneChangeState.off + desired = .04 if tick < 100 else -.01 + factor = smoother.factor(active=True, lane_change_state=state, speed=11., minimum_speed=0., duration=5.777777777777778, + previous=previous, desired=desired, turn_assist=True, intersection_turn=tick == 0) + assert factor == 1. + output, _ = clip_curvature(11., previous, limit_rate(11., previous, desired, factor), 0.) + assert output == clip_curvature(11., previous, desired, 0.)[0] + previous = output + + +def test_recorded_turn_forecasts_and_lane_change_heads_remain_distinct(): + import json + from pathlib import Path + recorded = json.loads((Path(__file__).parent / 'fixtures/signal_turn_forecasts.json').read_text()) + for name, direction in (('left_forecast', -1), ('right_forecast', 1)): + owner = SignalTurnEvidence() + ready = False + for row in recorded[name]: + sm, _, model = frame(0, direction) + now = BASE + row['dt_ns'] + sm.logMonoTime = dict.fromkeys(sm, now) + sm.recv_time = dict.fromkeys(sm, now / 1e9) + sm['carState'].vEgo, sm['carState'].aEgo = row['speed'], row['acceleration'] + sm['longitudinalPlan'].modelMonoTime = now + model.timestampEof = now + OFFSET + model.meta.desirePrediction = row['prediction'] + ready = owner.observe(sm, model, model_ns=now, now_ns=now, now_boot_ns=now + OFFSET, valid=True, enabled=True) + assert ready + for row in recorded['lane_change_negatives']: + owner = SignalTurnEvidence() + for tick in range(6): + # Put the recorded lane-change forecast inside every other turn gate. + ready, _, _ = observe(owner, tick, row['direction'], + lambda sm, model, prediction=row['prediction']: setattr(model.meta, 'desirePrediction', prediction)) + assert not ready + + +def test_forecast_never_replaces_opposite_near_curvature(): + smoother = LaneChangeSmoother() + factor = smoother.factor(active=True, lane_change_state=log.LaneChangeState.preLaneChange, speed=9., minimum_speed=0., + duration=5.777777777777778, previous=0., desired=.0015, turn_assist=True, intersection_turn=True) + output, _ = clip_curvature(9., 0., limit_rate(9., 0., .0015, factor), 0.) + assert output >= 0. diff --git a/openpilot/starpilot/navigation/intent.py b/openpilot/starpilot/navigation/intent.py index 69be712a79..108b324e25 100644 --- a/openpilot/starpilot/navigation/intent.py +++ b/openpilot/starpilot/navigation/intent.py @@ -6,6 +6,7 @@ from openpilot.cereal import log from openpilot.common.constants import CV from openpilot.starpilot.navigation.wire import navigation_state +from openpilot.starpilot.lateral.signal_turn import SignalTurnEvidence SERVICE = 'starpilotNavigation' MAX_AGE_NS = 2_500_000_000 @@ -106,6 +107,7 @@ class TurnIntent: from openpilot.starpilot.lateral.lane_change_preferences import LiveLaneChangePolicy self.guidance = LiveLaneChangePolicy(params) if params is not None else None self.steering_capable = steering_capable(cp) + self.signal_model = SignalTurnEvidence() self.signal_stop_hold = False self.signal_stop_completed = False self.key = None @@ -148,7 +150,8 @@ class TurnIntent: if (not supported or not self.steering_capable or not policy.turn_signal_guidance or current_desire != log.Desire.none or not cc.latActive or not cs.canValid or cs.canTimeout or str(cs.gearShifter) != 'drive' or - not math.isfinite(cs.vEgo) or cs.vEgo >= 20 * CV.MPH_TO_MS or + not math.isfinite(cs.vEgo) or (cs.vEgo >= 20 * CV.MPH_TO_MS and + (cs.steeringPressed or not self.signal_model.current(sm, now_ns))) or not device.started): return current_desire for service, age in (('carState', 100_000_000), ('carControl', 100_000_000), diff --git a/prebuilt.json b/prebuilt.json index 262c1a0afb..f70f583fbd 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "a4f076343ab5f49bbd73eb83ae4a6508bb49a880d706a643293ae792572ed465", "schema_version": 1} +{"protected_inventory_sha256": "e13fe2ebb785fa01370adb6d81ff150b18a45a22d50c19abb160687748699ac5", "schema_version": 1}