Show repeated steering requests in FLM drive reviews

This commit is contained in:
firestar5683
2026-11-24 09:44:02 -06:00
parent 591c5fcf53
commit 697dcf29e0
6 changed files with 133 additions and 15 deletions
+74 -11
View File
@@ -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,
)
@@ -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():
@@ -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'
@@ -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 })) }
}
+3 -2
View File
@@ -427,9 +427,10 @@ export const FlmPage = {
<div class="gx-tuner__drive-actions"><button v-if="review.saved.length" type="button" class="gx-btn gx-btn--tonal" @click="selectView('tune')">{{ review.historical ? 'View earlier saved values' : 'View saved change' }}<i class="bi bi-arrow-right" aria-hidden="true"></i></button><button v-if="review.count" type="button" class="gx-btn gx-btn--tonal gx-tuner__review-button" data-action="view-findings" @click="selectView('tune')">{{ review.saved.length ? 'View other findings' : 'View ' + review.count + (review.count === 1 ? ' finding' : ' findings') }}<i class="bi bi-arrow-right" aria-hidden="true"></i></button></div>
</section>
<div class="gx-tuner__overview-grid"><section class="gx-card gx-tuner__section gx-tuner__response"><div class="gx-tuner__section-heading"><div><p class="gx-tuner__eyebrow">STEERING RESPONSE</p><h3>How your car followed the steering request</h3></div><span class="gx-tuner__pill">{{ trackingPlot ? 'Completed window' : offroad?.observed ? 'One recorded section · ' + recordedDuration + 's' : offroad ? 'Recorded drive' : 'Waiting for samples' }}</span></div>
<p class="gx-tuner__graph-explainer">When these lines are close, the car is following the steering request closely in this sample.</p>
<p v-if="!trackingPlot && offroad?.observed?.followedRepeatedRequest" class="gx-tuner__graph-explainer">The steering request kept swinging back and forth, and the car followed it.</p>
<p v-else class="gx-tuner__graph-explainer">When these lines are close, the car is following the steering request closely in this sample.</p>
<template v-if="trackingPlot"><PlotGraph :chart="pairedTrackingChart" title="Requested and measured steering acceleration, paired using the learner's measured delay" /><div class="gx-tuner__legend"><span class="gx-tuner__requested">What StarPilot asked for</span><span class="gx-tuner__measured">What the car did</span><small>m/s² · delay aligned</small></div><p class="gx-tuner__caption">{{ trackingPlot.totalEndpoints }} measured endpoints · {{ trackingPlot.age.toFixed(1) }}s since the last pose</p></template>
<template v-else-if="offroad?.observed"><PlotGraph :chart="recordedTrackingChart" title="Recorded requested and measured steering" start-label="Start · 0s" :end-label="'End · ' + recordedDuration + 's'" /><div class="gx-tuner__legend"><span class="gx-tuner__requested">What StarPilot asked for</span><span class="gx-tuner__measured">What the car did</span></div><p class="gx-tuner__caption">One short recorded section, not a full-drive score or a before-and-after comparison.</p><details class="gx-tuner__disclosure"><summary>About this graph</summary><p>{{ 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.</p></details></template>
<template v-else-if="offroad?.observed"><PlotGraph :chart="recordedTrackingChart" title="Recorded requested and measured steering" start-label="Start · 0s" :end-label="'End · ' + recordedDuration + 's'" /><div class="gx-tuner__legend"><span class="gx-tuner__requested">What StarPilot asked for</span><span class="gx-tuner__measured">What the car did</span></div><p class="gx-tuner__caption">One short recorded section, not a full-drive score or a before-and-after comparison.</p><details class="gx-tuner__disclosure"><summary>About this graph</summary><p>{{ 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.</p></details></template>
<div v-else-if="offroad" class="gx-tuner__empty"><i class="bi bi-activity" aria-hidden="true"></i><h4>{{ amount(offroad.samples) }} recorded steering observations</h4><p>{{ learningReason(offroad.reason) }}</p><p class="gx-tuner__caption">No recorded response series was included in this report.</p></div>
<div v-else class="gx-tuner__empty"><i class="bi bi-activity" aria-hidden="true"></i><h4>No steering recording yet</h4><p>Once the device reports steering measurements, the request and the car response will appear here.</p></div>
</section>
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "582581d52a9d85c1d9b2579daa76ad6d3c0273e408a365cced75c74ecfdf844e", "schema_version": 1}
{"protected_inventory_sha256": "00c942587cfe52c69855bdb413865a7beb5025c51c45fc9397d3cd33c9b0b06f", "schema_version": 1}