mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 05:03:39 +08:00
Expose controller-bound proportional gain in steering settings
This commit is contained in:
@@ -161,20 +161,19 @@ class Controls:
|
||||
self.pose_calibrator = PoseCalibrator()
|
||||
self.calibrated_pose: Pose | None = None
|
||||
|
||||
self.lateral_gain_owner = None
|
||||
self.LoC = LongControl(self.CP, startup_preferences=self.vehicle_startup_preferences)
|
||||
self.VM = VehicleModel(self.CP)
|
||||
self.LaC: LatControl
|
||||
self.LaC = create_lateral_controller(
|
||||
self.CP, self.CI, DT_CTRL, mode=self.lateral_controller_selection.mode, turn_assist=self.vehicle_startup_preferences.turn_assist
|
||||
)
|
||||
self.lateral_gain_owner = create_gain_owner(self.params, self.CP, self.LaC)
|
||||
if isinstance(self.LaC, LatControlTorque):
|
||||
# Only the actual startup owner reads configuration; replay clones stay pure.
|
||||
if manual_effects is not None and (manual_effects.profile.context[1] != str(self.LaC.controller_mode) or
|
||||
not manual_effects.compatible(self.CP, self.CI, self.LaC, self.params)):
|
||||
manual_effects, manual_status = None, 'context_changed'
|
||||
self.LaC.manual_flm_effects, self.LaC.manual_flm_status = manual_effects, manual_status
|
||||
self.lateral_gain_owner = create_gain_owner(self.params, self.CP, self.LaC)
|
||||
cloudlog.info(
|
||||
{
|
||||
"event": "torque controller selected",
|
||||
@@ -199,9 +198,17 @@ class Controls:
|
||||
from openpilot.starpilot.lateral.learning_preferences import read_preference
|
||||
|
||||
preference = read_preference(self.params, self.CP)
|
||||
route_effects, self.route_flm_status = self._configure_route_tune(manual_status)
|
||||
from openpilot.starpilot.lateral.torque_supported import GM_VEHICLES
|
||||
|
||||
custom_fixed_gain = self.lateral_gain_owner is not None and str(self.CP.carFingerprint) not in GM_VEHICLES
|
||||
if custom_fixed_gain:
|
||||
# Saved route effects and live trials require the original controller gains.
|
||||
self.route_flm_status = 'context_changed'
|
||||
else:
|
||||
_, self.route_flm_status = self._configure_route_tune(manual_status)
|
||||
self.global_learning = (
|
||||
GlobalRuntime(self.CP, self.CI, self.LaC, confirmed_live_history=load_confirmed_history(self.params)) if preference.valid and preference.enabled else None
|
||||
GlobalRuntime(self.CP, self.CI, self.LaC, confirmed_live_history=load_confirmed_history(self.params))
|
||||
if preference.valid and preference.enabled and not custom_fixed_gain else None
|
||||
)
|
||||
# Load optional capture and live-trial code before the first control command.
|
||||
# Engagement must not compile/import replay and feedback modules in the loop.
|
||||
|
||||
@@ -4,15 +4,41 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from openpilot.starpilot.lateral.torque_runtime import gm_manual_supported_cp as supported_cp
|
||||
from openpilot.starpilot.lateral.torque_supported import BOLT_VEHICLES
|
||||
from opendbc.car.interfaces import get_torque_params
|
||||
from openpilot.starpilot.car.volkswagen.model_smoothing import supported as factory_manual_golf
|
||||
|
||||
from openpilot.starpilot.lateral.torque_runtime import gm_manual_supported_cp, production_supported_cp
|
||||
from openpilot.starpilot.lateral.torque_supported import BOLT_VEHICLES, GM_VEHICLES
|
||||
from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, MAX_DOCUMENT_BYTES, GainBasis, parse_document
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
|
||||
REFRESH_NS = 1_000_000_000
|
||||
|
||||
|
||||
def gain_supported(cp) -> bool:
|
||||
if gm_manual_supported_cp(cp) or factory_manual_golf(cp):
|
||||
return True
|
||||
if str(cp.brand) in ('gm', 'ford') or not production_supported_cp(cp):
|
||||
return False
|
||||
from openpilot.starpilot.lateral.controller_selection import policy_for
|
||||
return policy_for(cp) in (None, 'generic')
|
||||
|
||||
|
||||
def pid_torque_basis(cp) -> tuple[float, float, float]:
|
||||
# Use the platform's catalog basis in the shared tuning document. PID
|
||||
# consumes only the gain; the factor/friction controls stay unavailable.
|
||||
tune = get_torque_params()[str(cp.carFingerprint)]
|
||||
return float(tune['LAT_ACCEL_FACTOR']), 0.0, float(tune['FRICTION'])
|
||||
|
||||
|
||||
def pid_gain_basis(cp) -> GainBasis:
|
||||
tune = cp.lateralTuning.pid
|
||||
return GainBasis('pid', (tuple(tune.kpBP), tuple(tune.kpV)), pid_torque_basis(cp))
|
||||
|
||||
|
||||
def gain_basis(cp, controller) -> GainBasis:
|
||||
if cp.lateralTuning.which() == "pid":
|
||||
return pid_gain_basis(cp)
|
||||
tune = cp.lateralTuning.torque
|
||||
return GainBasis(str(controller.controller_mode),
|
||||
(tuple(controller.pid._k_p[0]), tuple(controller.pid._k_p[1])),
|
||||
@@ -47,12 +73,20 @@ class GenericGainOwner:
|
||||
self._apply(value)
|
||||
|
||||
def _apply(self, value: float | None) -> None:
|
||||
table = self.basis.source_table if value is None else ((0.0,), (value,))
|
||||
table = self.basis.source_table
|
||||
if value is not None:
|
||||
if str(self.cp.carFingerprint) in GM_VEHICLES:
|
||||
table = ((0.0,), (value,))
|
||||
else:
|
||||
speeds, gains = table
|
||||
table = (speeds, tuple(gain * value / gains[-1] for gain in gains))
|
||||
if table != self.current_table:
|
||||
self.pid._k_p = [list(row) for row in table]
|
||||
self.current_table = table
|
||||
|
||||
def refresh(self, *, now_ns: int | None = None) -> None:
|
||||
if str(self.cp.carFingerprint) not in GM_VEHICLES:
|
||||
return
|
||||
now_ns = time.monotonic_ns() if now_ns is None else now_ns
|
||||
if self.last_refresh_ns is not None and 0 <= now_ns - self.last_refresh_ns < REFRESH_NS:
|
||||
return
|
||||
@@ -61,7 +95,7 @@ class GenericGainOwner:
|
||||
|
||||
|
||||
def create_gain_owner(params, cp, controller) -> GenericGainOwner | None:
|
||||
if not supported_cp(cp):
|
||||
if not gain_supported(cp):
|
||||
return None
|
||||
basis = gain_basis(cp, controller)
|
||||
value = _selected(params, cp, basis)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.volkswagen.interface import CarInterface
|
||||
from opendbc.car.volkswagen.values import CAR
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.prefix import OpenpilotPrefix
|
||||
from openpilot.selfdrive.controls.controlsd import Controls
|
||||
from openpilot.starpilot.lateral.gain_runtime import gain_supported
|
||||
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeaturePage, row_change
|
||||
|
||||
|
||||
def test_golf_parked_gain_setting_reaches_controls_at_restart(monkeypatch):
|
||||
monkeypatch.setenv("SIMULATION", "1")
|
||||
monkeypatch.setenv("REPLAY", "1")
|
||||
cp = CarInterface.get_params(CAR.VOLKSWAGEN_GOLF_MK7, {i: {0xFD: 8} if i == 1 else {} for i in range(8)}, [], True, False, False)
|
||||
with OpenpilotPrefix():
|
||||
params = Params()
|
||||
params.put("CarParams", cp.to_bytes(), block=True)
|
||||
parked = True
|
||||
owner = FeatureSettingsOwner(params, lambda group: parked or group != "parked_preferences",
|
||||
vehicle_fingerprint=lambda: str(cp.carFingerprint), vehicle_params=lambda: cp)
|
||||
|
||||
def row(key):
|
||||
state = owner.snapshot(FeaturePage.DEVELOPER_LATERAL, parked=parked, system_long=True, lateral_context=True, metric=True)
|
||||
return next(r for r in state.rows if r.key == key)
|
||||
|
||||
assert gain_supported(cp)
|
||||
baseline = Controls()
|
||||
assert baseline.lateral_gain_owner is None
|
||||
assert tuple(baseline.LaC.pid._k_p[1]) == pytest.approx((0.6,))
|
||||
enable = row_change(row("torque:gain:mode"), 1)
|
||||
assert enable is not None
|
||||
parked = False
|
||||
assert not owner.apply(enable)
|
||||
parked = True
|
||||
assert owner.apply(enable)
|
||||
request = row_change(row("torque:gain:value"), -1)
|
||||
assert request is not None
|
||||
assert not owner.apply(replace(request, value="0.30"))
|
||||
assert owner.apply(replace(request, value="0.50"))
|
||||
assert tuple(baseline.LaC.pid._k_p[1]) == pytest.approx((0.6,))
|
||||
selected = Controls()
|
||||
assert tuple(selected.LaC.pid._k_p[1]) == pytest.approx((0.5,))
|
||||
assert tuple(selected.LaC.pid._k_i[1]) == tuple(baseline.LaC.pid._k_i[1])
|
||||
assert selected.LaC.ff_factor == baseline.LaC.ff_factor
|
||||
reset = row_change(row("torque:gain:mode"), -1)
|
||||
assert reset is not None and owner.apply(reset)
|
||||
assert Controls().lateral_gain_owner is None
|
||||
assert tuple(selected.LaC.pid._k_p[1]) == pytest.approx((0.5,))
|
||||
cp.transmissionType = structs.CarParams.TransmissionType.automatic
|
||||
assert not gain_supported(cp)
|
||||
|
||||
|
||||
def test_standard_torque_gain_preserves_the_speed_schedule(monkeypatch):
|
||||
from openpilot.starpilot.lateral.gain_runtime import gain_basis
|
||||
from openpilot.starpilot.lateral.torque_settings import DOCUMENT_KEY, replace_gain, serialize_document
|
||||
import json
|
||||
|
||||
monkeypatch.setenv("SIMULATION", "1")
|
||||
monkeypatch.setenv("REPLAY", "1")
|
||||
cp = CarInterface.get_params(CAR.VOLKSWAGEN_SHARAN_MK2, {i: {0x1A0: 8} if i == 1 else {} for i in range(8)}, [], False, False, False)
|
||||
with OpenpilotPrefix():
|
||||
params = Params()
|
||||
params.put("CarParams", cp.to_bytes(), block=True)
|
||||
baseline = Controls()
|
||||
assert gain_supported(cp)
|
||||
basis = gain_basis(cp, baseline.LaC)
|
||||
speeds, gains = basis.source_table
|
||||
requested = round(0.9 * gains[-1], 8)
|
||||
document = replace_gain({}, str(cp.carFingerprint), basis, "custom", requested)
|
||||
params.put(DOCUMENT_KEY, json.loads(serialize_document(document)), block=True)
|
||||
selected = Controls()
|
||||
assert tuple(selected.LaC.pid._k_p[0]) == speeds
|
||||
assert tuple(selected.LaC.pid._k_p[1]) == pytest.approx(tuple(gain * requested / gains[-1] for gain in gains))
|
||||
assert selected.LaC.pid._k_i == baseline.LaC.pid._k_i
|
||||
@@ -192,8 +192,6 @@ def parse_document(raw: bytes) -> dict[str, PlatformProfile]:
|
||||
gain = FieldChoice()
|
||||
gain_basis = None
|
||||
if "proportionalGain" in value:
|
||||
if fingerprint not in GAIN_VEHICLES:
|
||||
raise ValueError("Unsupported gain profile")
|
||||
gain = _choice(value["proportionalGain"])
|
||||
gain_basis = parse_gain_basis(value["gainBasis"])
|
||||
low, high = gain_bounds(fingerprint, gain_basis)
|
||||
@@ -311,7 +309,7 @@ def parse_gain_basis(value: object) -> GainBasis:
|
||||
if not isinstance(value, dict) or set(value) != {"controller", "sourceTable", "torqueBasis"}:
|
||||
raise ValueError("Malformed gain basis")
|
||||
table, basis = value["sourceTable"], value["torqueBasis"]
|
||||
if (value["controller"] not in ("standard", "starpilot") or
|
||||
if (value["controller"] not in ("standard", "starpilot", "pid") or
|
||||
not isinstance(table, (list, tuple)) or len(table) != 2 or
|
||||
any(not isinstance(row, (list, tuple)) or not row for row in table) or
|
||||
len(table[0]) != len(table[1]) or len(table[0]) > 32 or
|
||||
@@ -327,15 +325,15 @@ def gain_bounds(fingerprint: str, basis: GainBasis) -> tuple[float, float]:
|
||||
# Keep the qualified five-Bolt range unchanged, including STANDARD.
|
||||
if fingerprint in BOLT_VEHICLES:
|
||||
return 0.3, 0.9
|
||||
if fingerprint not in GAIN_VEHICLES:
|
||||
if fingerprint not in PLATFORMS:
|
||||
raise ValueError("Unsupported gain profile")
|
||||
source = basis.source_table[1][-1]
|
||||
return 0.5 * source, 1.5 * source
|
||||
return (0.5 * source, 1.5 * source) if fingerprint in GAIN_VEHICLES else (round(0.8 * source, 8), round(1.1 * source, 8))
|
||||
|
||||
|
||||
def replace_gain(profiles: dict[str, PlatformProfile], fingerprint: str, basis: GainBasis,
|
||||
mode: str, value: float | None, *, review: bool = False) -> dict[str, PlatformProfile]:
|
||||
if fingerprint not in GAIN_VEHICLES or mode not in ("source", "custom"):
|
||||
if fingerprint not in PLATFORMS or mode not in ("source", "custom"):
|
||||
raise ValueError("Unsupported gain edit")
|
||||
low, high = gain_bounds(fingerprint, basis)
|
||||
if value is not None and (not _finite_number(value) or not low <= value <= high):
|
||||
|
||||
@@ -275,6 +275,12 @@ class FeatureSettingsOwner:
|
||||
return None
|
||||
try:
|
||||
from openpilot.starpilot.lateral.torque_runtime import production_supported_cp
|
||||
if group == "gain" and cp.lateralTuning.which() == "pid":
|
||||
from openpilot.starpilot.lateral.gain_runtime import gain_supported, pid_gain_basis
|
||||
if gain_supported(cp):
|
||||
basis = pid_gain_basis(cp)
|
||||
return (str(cp.carFingerprint), str(cp.brand), str(cp.steerControlType), "pid", bool(cp.dashcamOnly),
|
||||
*basis.torque_basis, str(cp.carVin) if getattr(cp, "carVin", None) else None, basis.source_table)
|
||||
if group == "torque" and production_supported_cp(cp):
|
||||
tune = cp.lateralTuning.torque
|
||||
return (str(cp.carFingerprint), str(cp.brand), str(cp.steerControlType), str(cp.lateralTuning.which()),
|
||||
@@ -1116,7 +1122,7 @@ class FeatureSettingsOwner:
|
||||
rows.append(learning_row)
|
||||
elif page == FeaturePage.DEVELOPER_LATERAL:
|
||||
title = 'Developer Parameters'
|
||||
capability = self._capability("torque")
|
||||
capability = self._capability("torque") or self._capability("gain")
|
||||
allowed = configurable and self.authority("torque") and capability is not None
|
||||
_, numeric_rows = self.torque.rows(capability, allowed, repair_allowed=parked and allowed)
|
||||
from openpilot.starpilot.ui.delay_feature import DelayFeature
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import json
|
||||
|
||||
from openpilot.starpilot.lateral.torque_runtime import gm_manual_supported_cp as supported_cp
|
||||
from openpilot.starpilot.lateral.torque_supported import BOLT_VEHICLES
|
||||
from openpilot.starpilot.lateral.gain_runtime import gain_supported, pid_gain_basis
|
||||
from openpilot.starpilot.lateral.torque_supported import BOLT_VEHICLES, GM_VEHICLES
|
||||
from openpilot.starpilot.lateral.controller_selection import DOCUMENT_KEY as SELECTION_KEY, ControllerMode, selection_from_bytes
|
||||
from openpilot.starpilot.lateral.torque_settings import (DOCUMENT_KEY, GainBasis, FieldChoice, gain_bounds, parse_document, replace_gain, serialize_document)
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeatureRow
|
||||
@@ -15,8 +15,10 @@ class GainFeature:
|
||||
|
||||
def _basis(self, capability):
|
||||
cp = self.owner.vehicle_params()
|
||||
if cp is None or not supported_cp(cp) or capability != self.owner._capability("torque"):
|
||||
if cp is None or not gain_supported(cp) or capability != (self.owner._capability("torque") or self.owner._capability("gain")):
|
||||
raise ValueError("Qualified vehicle unavailable")
|
||||
if cp.lateralTuning.which() == "pid":
|
||||
return pid_gain_basis(cp)
|
||||
if not self.owner._readable(SELECTION_KEY):
|
||||
raise ValueError("Controller selection unavailable")
|
||||
selection = selection_from_bytes(cp, self.owner._raw(SELECTION_KEY))
|
||||
@@ -44,17 +46,17 @@ class GainFeature:
|
||||
FeatureRow("torque:gain:mode", "Steering response source", "Custom", raw,
|
||||
choices=("Selected controller",), available=allowed, capability=capability, dependencies=dependencies,
|
||||
default_value="Selected controller"))
|
||||
rows = [FeatureRow("", "Manual steering response",
|
||||
"Higher values respond more strongly; lower values respond more gently. First manual activation " +
|
||||
"requires a driving-process restart; an active tuning owner refreshes changes during the drive.")]
|
||||
apply_note = ("First manual activation requires a driving-process restart."
|
||||
if capability[0] in GM_VEHICLES else "Applies at restart. Learned steering adjustments pause while custom Kp is active.")
|
||||
rows = [FeatureRow("", "Manual steering response", "Higher values respond more strongly. " + apply_note)]
|
||||
rows.append(FeatureRow("torque:gain:mode", "Steering response source",
|
||||
"Custom" if choice.mode == "custom" else "Selected controller", raw,
|
||||
choices=("Selected controller", "Custom"), available=allowed, capability=capability, dependencies=dependencies,
|
||||
default_value="Selected controller"))
|
||||
if choice.mode == "custom":
|
||||
low, high = gain_bounds(capability[0], basis)
|
||||
rows.append(FeatureRow("torque:gain:value", "Steering response", f"{choice.custom_value:.2f}", raw,
|
||||
minimum=low, maximum=high, step=0.05, available=allowed,
|
||||
rows.append(FeatureRow("torque:gain:value", "Steering response (Kp)", f"{choice.custom_value:.2f}", raw,
|
||||
minimum=low, maximum=high, step=0.05 if capability[0] in GM_VEHICLES else 0.01, available=allowed,
|
||||
default_value="Selected controller", default_key="torque:gain:mode",
|
||||
capability=capability, dependencies=dependencies))
|
||||
return tuple(rows)
|
||||
@@ -65,8 +67,9 @@ class GainFeature:
|
||||
required = {"ForceAutoTuneOff", SELECTION_KEY}
|
||||
if request.capability is not None and request.capability[0] in BOLT_VEHICLES:
|
||||
required.add("AdvancedLateralTune")
|
||||
return (owner.authority("torque") and request.vehicle_fingerprint == owner.vehicle_fingerprint() and
|
||||
request.capability is not None and request.capability == owner._capability("torque") and
|
||||
return ((request.capability is not None and request.capability[0] in GM_VEHICLES or owner.authority("parked_preferences")) and
|
||||
owner.authority("torque") and request.vehicle_fingerprint == owner.vehicle_fingerprint() and
|
||||
request.capability is not None and request.capability == (owner._capability("torque") or owner._capability("gain")) and
|
||||
required.issubset(key for key, _ in request.dependencies) and
|
||||
owner._readable(DOCUMENT_KEY) and owner._raw(DOCUMENT_KEY) == request.expected and
|
||||
all(owner._readable(key) and owner._raw(key) == value for key, value in request.dependencies))
|
||||
|
||||
@@ -163,6 +163,16 @@ class TorqueFeature:
|
||||
def rows(self, capability: tuple | None, allowed: bool, *, repair_allowed: bool | None = None) -> tuple[bool, tuple[FeatureRow, ...]]:
|
||||
repair_allowed = allowed if repair_allowed is None else repair_allowed
|
||||
raw = self._raw(DOCUMENT_KEY)
|
||||
from openpilot.starpilot.lateral.gain_runtime import gain_supported
|
||||
cp = self.owner.vehicle_params()
|
||||
gain_available = capability is not None and cp is not None and gain_supported(cp)
|
||||
if gain_available and capability is not None and capability[3] == "pid":
|
||||
from openpilot.starpilot.ui.gain_feature import GainFeature
|
||||
try:
|
||||
profiles = {} if raw is None else parse_document(raw)
|
||||
except (ValueError, UnicodeError, OverflowError):
|
||||
return False, (FeatureRow("", "Steering response", "Invalid saved tuning document"),)
|
||||
return True, GainFeature(self.owner).rows(capability, profiles, raw, repair_allowed, repair_allowed)
|
||||
bolt = capability is not None and capability[0] in BOLT_VEHICLES
|
||||
try:
|
||||
if capability is None:
|
||||
@@ -237,9 +247,10 @@ class TorqueFeature:
|
||||
if bolt:
|
||||
rows.insert(0, FeatureRow("", "Manual friction", "Compensates steering friction. First manual activation requires " +
|
||||
"a driving-process restart; an active tuning owner refreshes changes during the drive."))
|
||||
if fingerprint in GM_VEHICLES:
|
||||
if gain_available:
|
||||
from openpilot.starpilot.ui.gain_feature import GainFeature
|
||||
rows.extend(GainFeature(self.owner).rows(capability, profiles, raw, allowed, repair_allowed))
|
||||
rows.extend(GainFeature(self.owner).rows(
|
||||
capability, profiles, raw, allowed if fingerprint in GM_VEHICLES else repair_allowed, repair_allowed))
|
||||
rows.extend(self._geometry_rows(capability, profiles, raw, allowed))
|
||||
return True, tuple(rows)
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "e1107f6e0523f32c3b2e3be4174b94546b1c194a0b44628baf9a1e87cf6e1204", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "90767f419df836f5618a4859f800650b449bd325dbfe101845d84d61199b2dca", "schema_version": 1}
|
||||
|
||||
Reference in New Issue
Block a user