diff --git a/openpilot/starpilot/flm/offroad_processor.py b/openpilot/starpilot/flm/offroad_processor.py index 56ff59ce12..4b59243514 100644 --- a/openpilot/starpilot/flm/offroad_processor.py +++ b/openpilot/starpilot/flm/offroad_processor.py @@ -3,12 +3,13 @@ from dataclasses import asdict, dataclass, field, replace from bisect import bisect_left import hashlib +from statistics import fmean from openpilot.starpilot.flm.offroad_analysis import analyze, MAX_WINDOWS, cohort, _spread, MAX_COHORT_WINDOWS from openpilot.starpilot.flm.offroad_baseline_windows import baseline_windows from openpilot.starpilot.flm.canonical_surface_adapter import NAMES as AMPLITUDE_NAMES from openpilot.starpilot.flm.offroad_residual import analyze_stable_windows -from openpilot.starpilot.flm.offroad_evidence import read_point, whole_windows, eligible_points, tracking_metrics, window_demand +from openpilot.starpilot.flm.offroad_evidence import read_point, whole_windows, eligible_points, tracking_metrics, window_demand, MAX_GAP_NS from openpilot.starpilot.flm.offroad_route import ( latest_route, walk_completed_route, RouteInputCancelled, RouteReceipt, SelectedSourceReceipt, PartialRouteReceipt, route_permission, ) @@ -119,8 +120,67 @@ def _separate_qualification(report, continuous, *, proposal_windows=None, route_ ] -def _recorded_tracking(windows): - """Measured route summary and one input-ordered window, never a trial result.""" +def _repeated_request_span(windows): + """Find near-center oscillation the car followed in contiguous original windows.""" + section = [] + best = () + best_variance = 0.0 + for window in windows: + points = window.points + first = points[0] + if window.domain != 'lateral_acceleration' or any(p.speed_mps < 15 for p in points): + section.clear() + continue + if section: + last = section[-1][-1] + if (first.route, first.segment, first.context_key) != (last.route, last.segment, last.context_key) or not ( + 0 < first.mono_ns - last.mono_ns <= MAX_GAP_NS + ): + section.clear() + section.append(points) + if len(section) < 6: + continue + + span = tuple(p for part in section for p in part) + section.pop(0) + start = span[0].mono_ns + sample = _spread(span, 61) + if len(sample) != 61 or any(abs(p.mono_ns - start - i * 200_000_000) > MAX_GAP_NS for i, p in enumerate(sample)): + continue + desired = [p.desired for p in sample] + if fmean(map(abs, desired)) > .18 or max(map(abs, desired)) > .35: + continue + + # Require four alternating excursions with at least 0.6 s between them. + mean = fmean(desired) + side = last_change = changes = 0 + for i, value in enumerate(desired): + if abs(value - mean) >= .025: + current = 1 if value > mean else -1 + if current != side and (not side or i - last_change >= 3): + changes += bool(side) + side, last_change = current, i + if changes < 3: + continue + + # Compare to the original request at short, plausible response lags. + # Neither this observation nor its illustrative lag supplies tuning evidence. + actual = [p.actual for p in sample[3:]] + center = fmean(actual) + variance = fmean((a - center) ** 2 for a in actual) + if variance < .025 ** 2 or variance <= best_variance: + continue + for lag in range(4): + errors = [a - d for a, d in zip(actual, desired[3 - lag:len(desired) - lag], strict=True)] + bias = fmean(errors) + if fmean((e - bias) ** 2 for e in errors) <= .20 * variance: + best, best_variance = span, variance + break + return best + + +def _recorded_tracking(windows, raw_windows): + """Measured route summary and one observed section, never a trial result.""" import math ordered = sorted((w for rows in windows.values() for w in rows), key=lambda w: (w.points[0].segment, w.points[0].mono_ns)) @@ -128,19 +188,22 @@ def _recorded_tracking(windows): return None samples = sum(len(w.points) for w in ordered) squared_error = sum((p.desired - p.actual) ** 2 for w in ordered for p in w.points) - first = ordered[0] + raw = sorted((w for rows in raw_windows.values() for w in rows), key=lambda w: (w.points[0].route, w.points[0].segment, w.points[0].mono_ns)) + repeated = _repeated_request_span(raw) if ordered[0].domain == 'lateral_acceleration' else () + points = repeated or ordered[0].points return { 'version': 1, - 'domain': first.domain, + 'domain': points[0].domain, 'samples': samples, 'windows': len(ordered), 'error_rms': math.sqrt(squared_error / samples), - 'route': first.points[0].route, - 'segment': first.points[0].segment, - 'source_start_ns': first.points[0].mono_ns, - 'source_end_ns': first.points[-1].mono_ns, - 'points': [[p.mono_ns, p.desired, p.actual] for p in _spread(first.points, 64)], + 'route': points[0].route, + 'segment': points[0].segment, + 'source_start_ns': points[0].mono_ns, + 'source_end_ns': points[-1].mono_ns, + 'points': [[p.mono_ns, p.desired, p.actual] for p in _spread(points, 64)], 'sampling': 'input_ordered_original_endpoints_no_interpolation', + **({'observation': 'followed_repeated_steering_request'} if repeated else {}), } @@ -658,6 +721,6 @@ def _assess_inputs(route, collected, previous, *, permitted, sources=None, route counts['diagnostic_whole_windows'] = sum(map(len, raw_windows.values())) return CompletedAssessment( receipt, reports, counts, state['cp'], (), route, tuple(quality_stops), tuple(diagnostic), tuple(stable), - _recorded_tracking(proposal_windows) or _recorded_tracking(raw_windows), sources, + _recorded_tracking(proposal_windows, raw_windows) or _recorded_tracking(raw_windows, raw_windows), sources, ) diff --git a/openpilot/starpilot/flm/tests/test_observed_maneuvers.py b/openpilot/starpilot/flm/tests/test_observed_maneuvers.py index c4d0875af3..913a39325c 100644 --- a/openpilot/starpilot/flm/tests/test_observed_maneuvers.py +++ b/openpilot/starpilot/flm/tests/test_observed_maneuvers.py @@ -1,17 +1,56 @@ """Broader original observations remain separate from automatic qualification.""" from dataclasses import replace +from math import pi, sin from types import SimpleNamespace import pytest from openpilot.starpilot.flm.offroad_evidence import RouteWindow, window_identity -from openpilot.starpilot.flm.offroad_processor import CompletedAssessment, _assess_inputs +from openpilot.starpilot.flm.offroad_processor import CompletedAssessment, _assess_inputs, _recorded_tracking from openpilot.starpilot.flm.offroad_stable_bridge import StableRouteSelector from openpilot.starpilot.flm.offroad_stable_policy import FLMSample from openpilot.starpilot.flm.tests.test_offroad_backend import scope, values from openpilot.starpilot.flm.tests import test_offroad_coordinate_policy as fixtures +@pytest.mark.parametrize('case', ('followed', 'steady_curve', 'lane_change', 'uncommanded', 'gap')) +def test_report_displays_repeated_steering_request_only_with_matching_original_response(case): + # Keep a genuine 0.4 s delay between the request and measured response. + def requested(t): + if case in ('steady_curve', 'uncommanded'): + return .1 + if case == 'lane_change': + return .08 * sin(pi * t / 12) + return .075 * sin(2 * pi * t / 4.5) + + collected, _ = fixtures.TestCrossDriveEvidence.inputs(1) + base = next(iter(collected.windows.values()))[0].points[0] + windows = [] + for w in range(6): + if case == 'gap' and w == 3: + continue + points = [] + for i in range(200): + t = (200 * w + i) / 100 + actual = .08 * sin(2 * pi * t / 4.5) if case == 'uncommanded' else requested(t - .4) + points.append(replace(base, speed_mps=26., mono_ns=base.mono_ns + (200 * w + i) * 10_000_000, + desired=requested(t), actual=actual)) + points = tuple(points) + windows.append(RouteWindow(window_identity(points), points)) + + inputs = {base.context_key: windows} + result = _recorded_tracking(inputs, inputs) + assert result is not None + assert result['windows'] == len(windows) + assert result['points'][0] == [base.mono_ns, windows[0].points[0].desired, windows[0].points[0].actual] + if case == 'followed': + assert result['observation'] == 'followed_repeated_steering_request' + assert result['source_end_ns'] == windows[-1].points[-1].mono_ns + else: + assert 'observation' not in result + assert result['source_end_ns'] == windows[0].points[-1].mono_ns + + def mixed_drive(number): collected, inventory = fixtures.TestCrossDriveEvidence.inputs(number) for key, windows in collected.windows.items(): diff --git a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs index 4406beb0ed..52da753005 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs @@ -73,6 +73,20 @@ assert.equal(offroadView(completed).evidenceDrives, null, 'Older reports must no assert.equal(tunerStatus(completed, true, true).title, 'Completed drive analyzed', 'Parked status must not mask completed analysis') assert.match(tunerStatus(completed, true, true).description, /left your tune unchanged/) assert.equal(completed.current.application.applied, false) +const oscillation = structuredClone(completed) +const observedPoints = Array.from({ length: 61 }, (_, i) => [1e9 + i * 2e8, .08 * Math.sin(i / 4), .08 * Math.sin((i - 2) / 4)]) +const oscillationResponse = { + version: 1, domain: 'lateral_acceleration', samples: 1200, windows: 6, error_rms: .02, route: 'declared-drive', segment: 18, + source_start_ns: observedPoints[0][0], source_end_ns: observedPoints.at(-1)[0], points: observedPoints, + sampling: 'input_ordered_original_endpoints_no_interpolation', observation: 'followed_repeated_steering_request', +} +oscillation.current.details['Recorded steering response'] = oscillationResponse +assert(validTrainingResults(oscillation)) +assert.equal(offroadView(oscillation).observed.followedRepeatedRequest, true) +assert.equal(offroadView(oscillation).observed.points.at(-1).at, 12000) +assert.equal(offroadView(oscillation).saved, false) +delete oscillationResponse.observation +assert.equal(offroadView(oscillation).observed.followedRepeatedRequest, false) const ignitionWait = { ...report(), preference: { version: 1, valid: true, enabled: true, parked: true, vehicle: 'TOYOTA_RAV4_PRIME', controller: 'torque' } } ignitionWait.current.reason = 'waiting_for_ignition_off' diff --git a/openpilot/starpilot/galaxy/web/js/flm-training-results.js b/openpilot/starpilot/galaxy/web/js/flm-training-results.js index 21f7736a24..fe1b06d56f 100644 --- a/openpilot/starpilot/galaxy/web/js/flm-training-results.js +++ b/openpilot/starpilot/galaxy/web/js/flm-training-results.js @@ -399,6 +399,7 @@ export function recordedSteeringView(value) { value.points[0][0] !== value.source_start_ns || value.points.at(-1)[0] !== value.source_end_ns) return null return { errorRms: value.error_rms, samples: value.samples, windows: value.windows, route: value.route, segment: value.segment, units: value.domain === 'lateral_acceleration' ? 'm/s²' : 'degrees', + followedRepeatedRequest: value.domain === 'lateral_acceleration' && value.observation === 'followed_repeated_steering_request', points: value.points.map(([ns, desired, actual]) => ({ at: (ns - value.source_start_ns) / 1e6, desired, actual })) } } diff --git a/openpilot/starpilot/galaxy/web/js/flm.js b/openpilot/starpilot/galaxy/web/js/flm.js index e51ba84e30..7d45dd61ba 100644 --- a/openpilot/starpilot/galaxy/web/js/flm.js +++ b/openpilot/starpilot/galaxy/web/js/flm.js @@ -427,9 +427,10 @@ export const FlmPage = {
STEERING RESPONSE
When these lines are close, the car is following the steering request closely in this sample.
+The steering request kept swinging back and forth, and the car followed it.
+When these lines are close, the car is following the steering request closely in this sample.
{{ trackingPlot.totalEndpoints }} measured endpoints · {{ trackingPlot.age.toFixed(1) }}s since the last pose
-One short recorded section, not a full-drive score or a before-and-after comparison.
{{ offroad.observed.units }} · original source times. Drive {{ offroad.observed.route }} · segment {{ offroad.observed.segment }} · one input-ordered recorded window. No interpolation or delay alignment. Baseline statistics use {{ amount(offroad.observed.windows) }} windows.
One short recorded section, not a full-drive score or a before-and-after comparison.
{{ offroad.observed.units }} · original source times. Drive {{ offroad.observed.route }} · segment {{ offroad.observed.segment }} · original samples without interpolation or delay alignment. Baseline statistics use {{ amount(offroad.observed.windows) }} windows.
{{ learningReason(offroad.reason) }}
No recorded response series was included in this report.
Once the device reports steering measurements, the request and the car response will appear here.