use crate::Vec2;
use super::derivative::DerivativeState;
use crate::controllers::{
Gains, InvalidConfig, check_limit, check_unit_interval, rescale_integral,
};
use crate::math::{
all_finite, assert_dt, cap_magnitude, clamp_symmetric_each, shaped_closing_speed,
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LateralControllerConfig {
pub position_p: f32,
pub velocity: Gains,
pub max_integral: f32,
pub max_accel_mps2: f32,
pub brake_mps2: f32,
pub braking_share: f32,
}
impl Default for LateralControllerConfig {
fn default() -> Self {
Self {
position_p: 0.5,
velocity: Gains {
p: 1.26,
i: 0.4,
d: 0.0,
},
max_integral: 12.5,
max_accel_mps2: 0.0,
brake_mps2: 0.0,
braking_share: DEFAULT_BRAKING_SHARE,
}
}
}
impl LateralControllerConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
check_limit("position_p", self.position_p)?;
check_limit("max_integral", self.max_integral)?;
check_limit("max_accel_mps2", self.max_accel_mps2)?;
check_limit("brake_mps2", self.brake_mps2)?;
check_unit_interval("braking_share", self.braking_share)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LateralTarget {
pub position_m: Vec2,
pub velocity_mps: Vec2,
pub max_speed_mps: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LateralEstimate {
pub position_m: Vec2,
pub velocity_mps: Vec2,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LateralController {
integrated_error: Vec2, derivative: DerivativeState<Vec2>,
shaped_velocity_mps: Option<Vec2>,
commanded_velocity_mps: Vec2,
}
impl LateralController {
pub fn control(
&mut self,
config: &LateralControllerConfig,
dt: f32,
target: LateralTarget,
estimate: LateralEstimate,
limit_mps2: Vec2,
) -> Vec2 {
assert_dt(dt);
let gains = &config.velocity;
let max_speed_mps = if target.max_speed_mps > 0.0 {
target.max_speed_mps
} else {
f32::INFINITY
};
let desired_velocity = closing_velocity(
target.position_m - estimate.position_m,
config.position_p,
braking_decel_mps2(config),
) + target.velocity_mps;
let (commanded_velocity, feedforward_mps2) = self.shape(
config.max_accel_mps2,
dt,
cap_magnitude(desired_velocity, max_speed_mps),
estimate.velocity_mps,
);
let velocity_error = commanded_velocity - estimate.velocity_mps;
if !(all_finite(&desired_velocity) && all_finite(&velocity_error)) {
self.derivative.forget();
return Vec2::zeros();
}
let error_derivative = self.derivative.step(velocity_error, dt);
self.commanded_velocity_mps = commanded_velocity;
self.integrated_error = clamp_symmetric_each(
hold_against_limit(
self.integrated_error,
dt * velocity_error,
gains.i,
limit_mps2,
),
config.max_integral,
);
feedforward_mps2
+ gains.p * velocity_error
+ gains.i * self.integrated_error
+ gains.d * error_derivative
}
fn shape(
&mut self,
max_accel_mps2: f32,
dt: f32,
demand_mps: Vec2,
measured_mps: Vec2,
) -> (Vec2, Vec2) {
let shaping = max_accel_mps2 > 0.0;
if !shaping {
self.shaped_velocity_mps = None;
return (demand_mps, Vec2::zeros());
}
if !(all_finite(&demand_mps) && all_finite(&measured_mps)) {
return (demand_mps, Vec2::zeros());
}
let from = self.shaped_velocity_mps.unwrap_or(measured_mps);
let to = from + cap_magnitude(demand_mps - from, max_accel_mps2 * dt);
self.shaped_velocity_mps = Some(to);
(to, (to - from) / dt)
}
pub(crate) fn commanded_velocity_mps(&self) -> Vec2 {
self.commanded_velocity_mps
}
#[cfg(test)]
pub(crate) fn integrated_error(&self) -> Vec2 {
self.integrated_error
}
pub(crate) fn rescale_integral(
&mut self,
old: &LateralControllerConfig,
new: &LateralControllerConfig,
) {
let (old_i, new_i) = (old.velocity.i, new.velocity.i);
self.integrated_error = self
.integrated_error
.map(|e| rescale_integral(e, old_i, new_i));
}
}
pub const DEFAULT_BRAKING_SHARE: f32 = 0.7;
fn braking_decel_mps2(config: &LateralControllerConfig) -> f32 {
if config.max_accel_mps2 > 0.0 {
config.braking_share * config.max_accel_mps2
} else if config.brake_mps2 > 0.0 {
config.brake_mps2
} else {
0.0
}
}
fn closing_velocity(error_m: Vec2, position_p: f32, decel_mps2: f32) -> Vec2 {
if decel_mps2 <= 0.0 {
return position_p * error_m;
}
let distance_m = error_m.norm();
if !(distance_m > 0.0 && distance_m.is_finite()) {
return position_p * error_m;
}
let speed_mps = shaped_closing_speed(distance_m, position_p, decel_mps2);
error_m * (speed_mps / distance_m)
}
fn hold_against_limit(integral: Vec2, step: Vec2, i: f32, limit_mps2: Vec2) -> Vec2 {
let next = integral + step;
if i * step.dot(&limit_mps2) > 0.0 {
cap_magnitude(next, integral.norm())
} else {
next
}
}
#[cfg(test)]
mod tests {
use assert2::check;
use crate::Vec2;
use super::*;
fn at(position_m: Vec2) -> LateralTarget {
LateralTarget {
position_m,
velocity_mps: Vec2::zeros(),
max_speed_mps: 0.0,
}
}
fn moving(velocity_mps: Vec2) -> LateralEstimate {
LateralEstimate {
position_m: Vec2::zeros(),
velocity_mps,
}
}
fn p_only() -> LateralControllerConfig {
LateralControllerConfig {
position_p: 0.5,
velocity: Gains {
p: 2.0,
i: 0.0,
d: 0.0,
},
..Default::default()
}
}
#[test]
fn accelerates_toward_the_target_against_velocity() {
let cases = [
(at(Vec2::zeros()), Vec2::zeros(), Vec2::zeros()),
(
at(Vec2::new(10.0, 0.0)),
Vec2::zeros(),
Vec2::new(10.0, 0.0),
), (
at(Vec2::new(0.0, -3.0)),
Vec2::zeros(),
Vec2::new(0.0, -3.0),
),
(
at(Vec2::zeros()),
Vec2::new(4.0, -2.0),
Vec2::new(-8.0, 4.0),
), (at(Vec2::new(0.0, f32::NAN)), Vec2::zeros(), Vec2::zeros()),
(
at(Vec2::new(f32::INFINITY, 0.0)),
Vec2::zeros(),
Vec2::zeros(),
), ];
for (target, velocity, expected) in cases {
let mut controller = LateralController::default();
let accel =
controller.control(&p_only(), 0.004, target, moving(velocity), Vec2::zeros());
assert!(
(accel - expected).amax() < 1e-5,
"target {target:?}, velocity {velocity:?} gave {accel:?}, expected {expected:?}"
);
}
}
#[test]
fn caps_the_desired_speed() {
let far = Vec2::new(30.0, 40.0); let cases = [
(5.0, Vec2::zeros(), Vec2::new(6.0, 8.0)), (100.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
(0.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
(-1.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
(f32::NAN, Vec2::zeros(), Vec2::new(30.0, 40.0)),
(5.0, Vec2::new(15.0, 20.0), Vec2::new(6.0, 8.0)),
];
for (max_speed_mps, velocity_mps, expected) in cases {
let target = LateralTarget {
position_m: far,
velocity_mps,
max_speed_mps,
};
let accel = LateralController::default().control(
&p_only(),
0.004,
target,
moving(Vec2::zeros()),
Vec2::zeros(),
);
assert!(
(accel - expected).amax() < 1e-4,
"max {max_speed_mps}, ff {velocity_mps:?} gave {accel:?}, expected {expected:?}"
);
}
}
#[test]
fn feedforward_flies_through_the_target() {
let target = LateralTarget {
position_m: Vec2::zeros(),
velocity_mps: Vec2::new(7.0, 0.0),
max_speed_mps: 7.0,
};
let config = p_only();
let cruising = LateralController::default().control(
&config,
0.004,
target,
moving(Vec2::new(7.0, 0.0)),
Vec2::zeros(),
);
let at_rest = LateralController::default().control(
&config,
0.004,
target,
moving(Vec2::zeros()),
Vec2::zeros(),
);
assert!(cruising == Vec2::zeros());
assert!((at_rest - Vec2::new(14.0, 0.0)).amax() < 1e-5);
}
#[test]
fn default_gains_are_the_position_pd_plus_velocity_i() {
let config = LateralControllerConfig::default();
const DT: f32 = 0.004;
let cases = [
(Vec2::new(2.0, -1.0), Vec2::zeros()),
(Vec2::zeros(), Vec2::new(1.0, 0.5)),
(Vec2::new(-3.0, 4.0), Vec2::new(0.4, -0.2)),
];
for (error, velocity) in cases {
let accel = LateralController::default().control(
&config,
DT,
at(error),
moving(velocity),
Vec2::zeros(),
);
let velocity_error = 0.5 * error - velocity;
let expected = 0.63 * error - 1.26 * velocity + 0.4 * DT * velocity_error;
assert!(
(accel - expected).amax() < 1e-5,
"error {error:?}, velocity {velocity:?} gave {accel:?}"
);
}
}
#[test]
fn default_gains_trim_a_constant_disturbance() {
const DT: f32 = 0.02;
const DRAG_MPS2: f32 = 1.5;
let config = LateralControllerConfig::default();
let mut controller = LateralController::default();
let (mut position_m, mut velocity_mps) = (Vec2::zeros(), Vec2::zeros());
let drag = Vec2::new(DRAG_MPS2, 0.0);
for _ in 0..(60.0 / DT) as usize {
let estimate = LateralEstimate {
position_m,
velocity_mps,
};
let accel = controller.control(&config, DT, at(Vec2::zeros()), estimate, Vec2::zeros());
velocity_mps += (accel + drag) * DT;
position_m += velocity_mps * DT;
}
assert!(position_m.norm() < 0.01, "settled at {position_m:?}");
}
#[test]
fn integral_is_held_against_the_limit() {
let x = Vec2::new(1.0, 0.0);
let y = Vec2::new(0.0, 1.0);
let cases = [
(x, x, 0.4, Vec2::zeros(), 2.0 * x), (x, x, 0.4, x, x), (Vec2::zeros(), x, 0.4, x, Vec2::zeros()), (x, -x, 0.4, x, Vec2::zeros()), (x, 0.5 * x, 0.4, -x, 1.5 * x), (x, y, 0.4, y, (x + y) / 2.0_f32.sqrt()), (x, x, 0.0, x, 2.0 * x), (x, x, 0.4, Vec2::new(f32::NAN, 0.0), 2.0 * x), ];
for (integral, step, i, limit, expected) in cases {
let held = hold_against_limit(integral, step, i, limit);
assert!(
(held - expected).amax() < 1e-6,
"{integral:?} + {step:?} against {limit:?} gave {held:?}, expected {expected:?}"
);
}
}
#[test]
fn non_finite_velocity_yields_no_acceleration() {
let nan = f32::NAN;
let inf = f32::INFINITY;
let velocities = [
Vec2::new(nan, 0.0),
Vec2::new(0.0, inf),
Vec2::new(-inf, nan),
];
let config = LateralControllerConfig::default();
for velocity in velocities {
let mut controller = LateralController::default();
let accel = controller.control(
&config,
0.004,
at(Vec2::new(10.0, 5.0)),
moving(velocity),
Vec2::zeros(),
);
assert!(
accel == Vec2::zeros(),
"velocity {velocity:?} gave {accel:?}"
);
}
}
#[test]
fn integral_term_is_clamped_to_max_integral() {
let config = LateralControllerConfig {
max_integral: 5.0,
..Default::default()
};
let mut controller = LateralController::default();
for _ in 0..10_000 {
controller.control(
&config,
0.01,
at(Vec2::new(100.0, -100.0)),
moving(Vec2::zeros()),
Vec2::zeros(),
);
}
assert!(controller.integrated_error == Vec2::new(5.0, -5.0));
}
#[test]
fn recovers_after_a_nan_tick() {
let config = LateralControllerConfig {
velocity: Gains {
p: 1.0,
i: 0.5,
d: 0.1,
},
..Default::default()
};
let mut controller = LateralController::default();
let at_rest = moving(Vec2::zeros());
let during = controller.control(
&config,
0.004,
at(Vec2::new(f32::NAN, 0.0)),
at_rest,
Vec2::zeros(),
);
let after = controller.control(
&config,
0.004,
at(Vec2::new(10.0, 0.0)),
at_rest,
Vec2::zeros(),
);
assert!(during == Vec2::zeros(), "NaN tick gave {during:?}");
let fresh = LateralController::default().control(
&config,
0.004,
at(Vec2::new(10.0, 0.0)),
at_rest,
Vec2::zeros(),
);
assert!(after == fresh, "valid target after NaN gave {after:?}");
}
#[test]
fn derivative_acts_on_the_velocity_error_change() {
let config = LateralControllerConfig {
position_p: 0.0,
velocity: Gains {
p: 0.0,
i: 0.0,
d: 0.5,
},
..Default::default()
};
let mut controller = LateralController::default();
let target = at(Vec2::zeros());
let first = controller.control(
&config,
0.1,
target,
moving(Vec2::new(1.0, 0.0)),
Vec2::zeros(),
);
let second = controller.control(
&config,
0.1,
target,
moving(Vec2::new(2.0, 0.0)),
Vec2::zeros(),
);
assert!(first == Vec2::zeros());
assert!((second - Vec2::new(-5.0, 0.0)).amax() < 1e-4);
}
#[test]
fn invalid_config_is_rejected_and_does_not_panic_the_tick() {
let negative_integral = LateralControllerConfig {
max_integral: -1.0,
..Default::default()
};
let nan_position_p = LateralControllerConfig {
position_p: f32::NAN,
..Default::default()
};
assert_eq!(
negative_integral.validate().map_err(|e| e.field),
Err("max_integral")
);
assert_eq!(
nan_position_p.validate().map_err(|e| e.field),
Err("position_p")
);
for max_integral in [-1.0, f32::NAN] {
let config = LateralControllerConfig {
max_integral,
..Default::default()
};
let mut controller = LateralController::default();
controller.control(
&config,
0.01,
at(Vec2::new(1.0, 1.0)),
moving(Vec2::zeros()),
Vec2::zeros(),
);
assert!(
controller.integrated_error == Vec2::zeros(),
"max_integral {max_integral}"
);
}
}
fn shaped(max_accel_mps2: f32) -> LateralControllerConfig {
LateralControllerConfig {
max_accel_mps2,
..p_only()
}
}
fn leg() -> LateralTarget {
LateralTarget {
max_speed_mps: 3.0,
..at(Vec2::new(30.0, 0.0))
}
}
#[test]
fn shaped_target_starts_at_the_measured_velocity() {
let dt = 0.1;
let turn = Vec2::new(3.0, -2.0).normalize();
let cases = [
(0.0, Vec2::zeros(), Vec2::new(6.0, 0.0)), (1.0, Vec2::zeros(), Vec2::new(1.0 + 2.0 * 0.1, 0.0)),
(1.0, Vec2::new(3.0, 0.0), Vec2::zeros()), (1.0, Vec2::new(0.0, 2.0), turn + 2.0 * 0.1 * turn),
(100.0, Vec2::zeros(), Vec2::new(30.0 + 2.0 * 3.0, 0.0)),
];
for (max_accel_mps2, velocity, expected) in cases {
let accel = LateralController::default().control(
&shaped(max_accel_mps2),
dt,
leg(),
moving(velocity),
Vec2::zeros(),
);
check!(
(accel - expected).amax() < 1e-4,
"limit {max_accel_mps2}, velocity {velocity:?}: {accel:?}, expected {expected:?}"
);
}
}
#[test]
fn shaped_target_ramps_to_the_demand() {
let (dt, config) = (0.1, shaped(1.0));
let mut controller = LateralController::default();
let mut accels = Vec::new();
for _ in 0..32 {
accels.push(controller.control(
&config,
dt,
leg(),
moving(Vec2::zeros()),
Vec2::zeros(),
));
}
let cases = [
(0, 1.0 + 2.0 * 0.1),
(14, 1.0 + 2.0 * 1.5),
(29, 1.0 + 2.0 * 3.0), (30, 2.0 * 3.0),
(31, 2.0 * 3.0),
];
for (tick, expected) in cases {
let accel = accels[tick];
check!(
(accel - Vec2::new(expected, 0.0)).amax() < 1e-3,
"tick {tick}: {accel:?}, expected {expected}"
);
}
}
#[test]
fn braking_decel_comes_from_shaping_then_brake() {
let cases = [
(0.0, 0.0, 0.7, 0.0),
(1.0, 0.0, 0.7, 0.7),
(2.0, 0.0, 0.5, 1.0), (1.0, 1.5, 0.7, 0.7), (0.0, 1.5, 0.5, 1.5), (f32::NAN, 1.5, 0.7, 1.5),
(-1.0, 1.5, 0.7, 1.5),
(0.0, f32::NAN, 0.7, 0.0),
(0.0, -1.0, 0.7, 0.0),
];
for (max_accel_mps2, brake_mps2, braking_share, expected) in cases {
let config = LateralControllerConfig {
max_accel_mps2,
brake_mps2,
braking_share,
..LateralControllerConfig::default()
};
let decel = braking_decel_mps2(&config);
check!(
(decel - expected).abs() < 1e-6,
"shaping {max_accel_mps2}, brake {brake_mps2}: {decel}, expected {expected}"
);
}
}
#[test]
fn rejects_each_field_out_of_range() {
let base = LateralControllerConfig::default;
let cases = [
(
"position_p",
LateralControllerConfig {
position_p: -1.0,
..base()
},
),
(
"max_integral",
LateralControllerConfig {
max_integral: f32::NAN,
..base()
},
),
(
"max_accel_mps2",
LateralControllerConfig {
max_accel_mps2: -1.0,
..base()
},
),
(
"brake_mps2",
LateralControllerConfig {
brake_mps2: f32::INFINITY,
..base()
},
),
(
"braking_share",
LateralControllerConfig {
braking_share: 0.0,
..base()
},
),
(
"braking_share",
LateralControllerConfig {
braking_share: 1.1,
..base()
},
),
(
"braking_share",
LateralControllerConfig {
braking_share: f32::NAN,
..base()
},
),
];
check!(base().validate().is_ok());
for (field, config) in cases {
check!(
config.validate().map_err(|e| e.field) == Err(field),
"{config:?}"
);
}
}
#[test]
fn closing_velocity_follows_the_braking_curve() {
let p = 0.5;
let cases = [
(Vec2::new(30.0, 0.0), 0.0, Vec2::new(15.0, 0.0)), (Vec2::new(2.0, 0.0), 0.7, Vec2::new(1.0, 0.0)), (Vec2::new(30.0, 0.0), 0.7, Vec2::new(6.3277, 0.0)),
(Vec2::new(0.0, -30.0), 0.7, Vec2::new(0.0, -6.3277)),
(Vec2::new(18.0, 24.0), 0.7, Vec2::new(0.6, 0.8) * 6.3277),
(Vec2::zeros(), 0.7, Vec2::zeros()),
];
for (error_m, decel_mps2, expected) in cases {
let velocity = closing_velocity(error_m, p, decel_mps2);
check!(
(velocity - expected).amax() < 1e-3,
"error {error_m:?}, decel {decel_mps2}: {velocity:?}, expected {expected:?}"
);
}
check!(
closing_velocity(Vec2::new(f32::NAN, 0.0), p, 0.7)
.x
.is_nan()
);
}
#[test]
fn closing_at_the_braking_curve_holds_its_speed() {
let closing_mps = (2.0_f32 * 0.7 * (10.0 - 1.4)).sqrt();
let accel = LateralController::default().control(
&shaped(1.0),
0.1,
at(Vec2::new(10.0, 0.0)),
moving(Vec2::new(closing_mps, 0.0)),
Vec2::zeros(),
);
check!(accel.amax() < 1e-4, "{accel:?}");
}
#[test]
fn unshaped_braking_slows_along_the_curve() {
let cases = [(1.5, 9.0, 0.0), (1.5, 12.0, -6.0), (0.0, 9.0, 12.0)];
for (brake_mps2, closing_mps, expected) in cases {
let config = LateralControllerConfig {
brake_mps2,
..p_only()
};
let accel = LateralController::default().control(
&config,
0.1,
at(Vec2::new(30.0, 0.0)),
moving(Vec2::new(closing_mps, 0.0)),
Vec2::zeros(),
);
check!(
(accel - Vec2::new(expected, 0.0)).amax() < 1e-3,
"brake {brake_mps2} at {closing_mps} m/s: {accel:?}, expected {expected}"
);
}
}
#[test]
fn invalid_brake_is_rejected_and_brakes_linearly() {
for brake_mps2 in [-1.0, f32::NAN] {
let config = LateralControllerConfig {
brake_mps2,
..p_only()
};
check!(config.validate().map_err(|e| e.field) == Err("brake_mps2"));
let accel = LateralController::default().control(
&config,
0.1,
at(Vec2::new(30.0, 0.0)),
moving(Vec2::zeros()),
Vec2::zeros(),
);
check!(
(accel - Vec2::new(30.0, 0.0)).amax() < 1e-3,
"brake {brake_mps2}: {accel:?}"
);
}
}
#[test]
fn non_finite_velocity_keeps_the_shaped_target() {
let (dt, config) = (0.1, shaped(1.0));
let mut controller = LateralController::default();
let mut run = |velocity: Vec2| {
controller.control(&config, dt, leg(), moving(velocity), Vec2::zeros())
};
run(Vec2::zeros()); check!(run(Vec2::new(f32::NAN, 0.0)) == Vec2::zeros());
let accel = run(Vec2::zeros()); check!((accel - Vec2::new(1.0 + 2.0 * 0.2, 0.0)).amax() < 1e-4);
}
#[test]
fn shaping_off_forgets_the_shaped_target() {
let dt = 0.1;
let mut controller = LateralController::default();
for _ in 0..10 {
controller.control(
&shaped(1.0),
dt,
leg(),
moving(Vec2::zeros()),
Vec2::zeros(),
);
}
controller.control(
&shaped(0.0),
dt,
leg(),
moving(Vec2::zeros()),
Vec2::zeros(),
);
let accel = controller.control(
&shaped(1.0),
dt,
leg(),
moving(Vec2::zeros()),
Vec2::zeros(),
);
check!(
(accel - Vec2::new(1.0 + 2.0 * 0.1, 0.0)).amax() < 1e-4,
"{accel:?}"
);
}
#[test]
fn invalid_accel_limit_is_rejected_and_shapes_nothing() {
for max_accel_mps2 in [-1.0, f32::NAN] {
let config = shaped(max_accel_mps2);
check!(config.validate().map_err(|e| e.field) == Err("max_accel_mps2"));
let accel = LateralController::default().control(
&config,
0.1,
leg(),
moving(Vec2::zeros()),
Vec2::zeros(),
);
check!(
(accel - Vec2::new(6.0, 0.0)).amax() < 1e-4,
"limit {max_accel_mps2}: {accel:?}"
);
}
}
#[test]
fn gain_change_between_ticks_keeps_state() {
let config = LateralControllerConfig::default();
let mut controller = LateralController::default();
controller.control(
&config,
1.0,
at(Vec2::new(0.0, 1.0)),
moving(Vec2::zeros()),
Vec2::zeros(),
);
let integral = controller.integrated_error;
let retuned = LateralControllerConfig {
position_p: 0.0,
velocity: Gains {
p: 0.0,
i: 2.0,
d: 0.0,
},
..config
};
let accel = controller.control(
&retuned,
0.01,
at(Vec2::zeros()),
moving(Vec2::zeros()),
Vec2::zeros(),
);
assert!(controller.integrated_error == integral);
approx::assert_relative_eq!(accel.y, 2.0 * integral.y, epsilon = 1e-6);
}
#[test]
#[should_panic(expected = "dt must be positive and finite")]
fn zero_dt_panics() {
LateralController::default().control(
&LateralControllerConfig::default(),
0.0,
at(Vec2::zeros()),
moving(Vec2::zeros()),
Vec2::zeros(),
);
}
}