stable_flight/controllers/lateral.rs
1use crate::Vec2;
2
3use super::derivative::DerivativeState;
4use crate::controllers::{
5 Gains, InvalidConfig, check_limit, check_unit_interval, rescale_integral,
6};
7use crate::math::{
8 all_finite, assert_dt, cap_magnitude, clamp_symmetric_each, shaped_closing_speed,
9};
10
11/// Configures the [`LateralController`]: a position loop feeding a velocity loop.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct LateralControllerConfig {
14 /// Proportional gain from position error (m) to desired velocity (m/s), in 1/s. Sets how
15 /// fast the vehicle closes on a target before the speed limit applies. Must be
16 /// non-negative and finite.
17 pub position_p: f32,
18
19 /// PID gains from velocity error (m/s) to horizontal acceleration (m/s²).
20 pub velocity: Gains,
21
22 /// Maximum absolute value of the integrated velocity error, in m, per axis.
23 /// Bounds the I term's authority at `velocity.i · max_integral` m/s².
24 pub max_integral: f32,
25
26 /// Most the velocity target changes per second, in m/s²; 0 is off. When set, the target
27 /// starts at the measured velocity and moves toward the position loop's demand at this
28 /// rate, its change fed forward as acceleration (PX4 `MPC_ACC_HOR`,
29 /// `FlightTaskAuto::activate`; ArduPilot `AC_PosControl::NE_init_controller`).
30 /// A new leg then asks for at most `atan(max_accel_mps2 / g)` of tilt at once, instead of
31 /// the tilt for its whole speed. The position loop then slows toward the target along a
32 /// braking curve: the speed that decelerating at [`braking_share`](Self::braking_share) of
33 /// this rate still stops on the target, so stopping from `v` starts about
34 /// `v² / (2 · braking_share · max_accel_mps2)` out. Must be non-negative and finite.
35 pub max_accel_mps2: f32,
36
37 /// Deceleration the position loop brakes at with shaping off, in m/s²; 0 is off. When set,
38 /// the speed toward the target follows the braking curve at this rate, instead of
39 /// `position_p · error`, which starts braking only `2 · v` meters out whatever the
40 /// vehicle's speed. Higher: brakes later, overshoots once past what the vehicle can
41 /// shed. Ignored with shaping on, which brakes at [`braking_share`](Self::braking_share) of
42 /// [`max_accel_mps2`](Self::max_accel_mps2). Must be non-negative and finite.
43 pub brake_mps2: f32,
44
45 /// Share of [`max_accel_mps2`](Self::max_accel_mps2) the braking curve slows at with
46 /// shaping on. The curve is read at the vehicle's distance, and the vehicle trails its
47 /// shaped velocity target, so it runs ahead of the curve: there the curve's speed drops
48 /// faster than its deceleration. Braking below the shaping rate leaves the rate-limited
49 /// target room to follow. Higher: arrives sooner, overshoots more. Must be in `(0, 1]`.
50 /// Defaults to [`DEFAULT_BRAKING_SHARE`].
51 pub braking_share: f32,
52}
53
54impl Default for LateralControllerConfig {
55 fn default() -> Self {
56 Self {
57 // Unsaturated, `velocity.p · (position_p · e − v)` is a flight-checked position PD
58 // for the atan tilt: P 0.63, D 1.26, ζ ≈ 0.8 (#108).
59 position_p: 0.5,
60 // I trims a steady wind; at 0.4 its closed-loop pole (≈ 0.26 /s) leaves the step
61 // response unchanged (#357).
62 velocity: Gains {
63 p: 1.26,
64 i: 0.4,
65 d: 0.0,
66 },
67 // 12.5 m at I 0.4 is ±5 m/s², the default 27° tilt cap (g · tan 27°).
68 max_integral: 12.5,
69 max_accel_mps2: 0.0,
70 brake_mps2: 0.0,
71 braking_share: DEFAULT_BRAKING_SHARE,
72 }
73 }
74}
75
76impl LateralControllerConfig {
77 /// Checks the config: `position_p`, `max_integral`, `max_accel_mps2`, and `brake_mps2`
78 /// must be non-negative and finite, and `braking_share` in `(0, 1]`.
79 ///
80 /// # Examples
81 ///
82 /// ```
83 /// use stable_flight::controllers::LateralControllerConfig;
84 ///
85 /// assert!(LateralControllerConfig::default().validate().is_ok());
86 /// let bad = LateralControllerConfig { max_integral: f32::NAN, ..Default::default() };
87 /// assert!(bad.validate().is_err());
88 /// ```
89 pub fn validate(&self) -> Result<(), InvalidConfig> {
90 check_limit("position_p", self.position_p)?;
91 check_limit("max_integral", self.max_integral)?;
92 check_limit("max_accel_mps2", self.max_accel_mps2)?;
93 check_limit("brake_mps2", self.brake_mps2)?;
94 check_unit_interval("braking_share", self.braking_share)
95 }
96}
97
98/// What the [`LateralController`] tracks: a horizontal position, a velocity fed forward
99/// toward it, and a speed limit. Horizontal components are (north, east), as in the
100/// [`VehicleState`](crate::VehicleState) frame contract.
101///
102/// # Examples
103///
104/// ```
105/// use stable_flight::Vec2;
106/// use stable_flight::controllers::LateralTarget;
107///
108/// // Fly to 20 m north at up to 5 m/s, stopping there.
109/// let target = LateralTarget {
110/// position_m: Vec2::new(20.0, 0.0),
111/// velocity_mps: Vec2::zeros(),
112/// max_speed_mps: 5.0,
113/// };
114/// ```
115#[derive(Clone, Copy, Debug, PartialEq)]
116pub struct LateralTarget {
117 /// Desired position in meters.
118 pub position_m: Vec2,
119 /// Velocity in m/s added to the position loop's demand: zero stops at the target, a
120 /// non-zero value flies through it.
121 pub velocity_mps: Vec2,
122 /// Cap on the desired speed in m/s. Zero, negative, or NaN means no cap (the guidance's
123 /// tilt limit still applies).
124 pub max_speed_mps: f32,
125}
126
127/// The vehicle's current horizontal state as the [`LateralController`] consumes it, (north,
128/// east) per the [`VehicleState`](crate::VehicleState) frame contract.
129///
130/// # Examples
131///
132/// ```
133/// use stable_flight::Vec2;
134/// use stable_flight::controllers::LateralEstimate;
135///
136/// // 4 m north, 1 m east, drifting north at 0.1 m/s.
137/// let estimate = LateralEstimate {
138/// position_m: Vec2::new(4.0, 1.0),
139/// velocity_mps: Vec2::new(0.1, 0.0),
140/// };
141/// ```
142#[derive(Clone, Copy, Debug, PartialEq)]
143pub struct LateralEstimate {
144 /// Estimated position in meters.
145 pub position_m: Vec2,
146 /// Estimated velocity in m/s.
147 pub velocity_mps: Vec2,
148}
149
150/// Horizontal position → velocity → acceleration cascade: turns a position target into a
151/// horizontal acceleration demand.
152///
153/// The position loop asks for `position_p · error + target velocity`, capped in magnitude at
154/// the target's `max_speed_mps` (direction kept), and the velocity PID turns the velocity
155/// error into acceleration. With [`max_accel_mps2`](LateralControllerConfig::max_accel_mps2)
156/// set, the position loop slows toward the target along a braking curve instead of in
157/// proportion to the distance, and the PID tracks a shaped velocity target: it starts at the
158/// measured velocity, moves toward the demand at that rate, and its change is fed forward.
159/// With shaping off, [`brake_mps2`](LateralControllerConfig::brake_mps2) sets the braking
160/// curve alone, so a fast leg starts slowing in time to stop.
161/// Turning the acceleration into tilt is the guidance's job (it depends on the airframe and its
162/// heading); [`CopterGuidance`](crate::guidance::copter::CopterGuidance) tilts by `atan(|a| /
163/// g)` toward it.
164///
165/// It holds only state (the velocity integral, derivative history, and shaped velocity
166/// target); gains and limits come from the [`LateralControllerConfig`] passed to each
167/// [`control`](Self::control) call, so they can change between ticks without resetting the
168/// state.
169#[derive(Clone, Debug, Default, PartialEq)]
170pub struct LateralController {
171 integrated_error: Vec2, // Accumulated velocity error (x, y)
172 /// Previous velocity error for the derivative term; empty on the first tick and after a gap.
173 derivative: DerivativeState<Vec2>,
174 /// The shaped velocity target, in m/s; empty until the first run with shaping on.
175 shaped_velocity_mps: Option<Vec2>,
176 /// The velocity the last finite run asked the velocity PID for, in m/s.
177 commanded_velocity_mps: Vec2,
178}
179
180impl LateralController {
181 /// Desired horizontal acceleration toward `target`.
182 ///
183 /// # Arguments
184 ///
185 /// * `config` - Gains and limits; assumed valid ([`LateralControllerConfig::validate`]).
186 /// An invalid limit does not panic: a negative or NaN `max_integral` acts as 0.
187 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
188 /// * `target` - Desired position, feedforward velocity, and speed limit.
189 /// * `estimate` - Current position and velocity.
190 /// * `limit_mps2` - The acceleration the caller last had to cap (e.g. at its tilt limit), or
191 /// zero. The integral doesn't grow in that direction, so it can't wind up against a
192 /// limit; it may still shrink or turn.
193 ///
194 /// # Returns
195 ///
196 /// Desired horizontal acceleration (x, y) in m/s², in the position frame. It is not
197 /// saturated: the caller caps the tilt it turns into. A non-finite target or estimate gives
198 /// zero (level) and leaves the integral untouched. The integral is clamped to
199 /// `max_integral` to limit windup.
200 ///
201 /// # Panics
202 ///
203 /// If `dt` is not positive and finite.
204 ///
205 /// # Examples
206 ///
207 /// ```
208 /// use stable_flight::controllers::{
209 /// LateralController, LateralControllerConfig, LateralEstimate, LateralTarget,
210 /// };
211 /// use stable_flight::Vec2;
212 ///
213 /// let config = LateralControllerConfig::default();
214 /// let mut controller = LateralController::default();
215 /// let target = LateralTarget {
216 /// position_m: Vec2::new(5.0, 2.0), // 5 m north, 2 m east
217 /// velocity_mps: Vec2::zeros(),
218 /// max_speed_mps: 3.0,
219 /// };
220 /// let estimate = LateralEstimate {
221 /// position_m: Vec2::new(4.0, 1.0),
222 /// velocity_mps: Vec2::new(0.1, 0.05),
223 /// };
224 ///
225 /// // Target is north-east: accelerate north (+x) and east (+y)
226 /// let accel_mps2 = controller.control(&config, 0.004, target, estimate, Vec2::zeros());
227 /// assert!(accel_mps2.x > 0.0 && accel_mps2.y > 0.0);
228 /// ```
229 pub fn control(
230 &mut self,
231 config: &LateralControllerConfig,
232 dt: f32,
233 target: LateralTarget,
234 estimate: LateralEstimate,
235 limit_mps2: Vec2,
236 ) -> Vec2 {
237 assert_dt(dt);
238 let gains = &config.velocity;
239
240 // `>` is false for NaN: zero, negative, and NaN limits all mean no cap.
241 let max_speed_mps = if target.max_speed_mps > 0.0 {
242 target.max_speed_mps
243 } else {
244 f32::INFINITY
245 };
246 let desired_velocity = closing_velocity(
247 target.position_m - estimate.position_m,
248 config.position_p,
249 braking_decel_mps2(config),
250 ) + target.velocity_mps;
251 let (commanded_velocity, feedforward_mps2) = self.shape(
252 config.max_accel_mps2,
253 dt,
254 cap_magnitude(desired_velocity, max_speed_mps),
255 estimate.velocity_mps,
256 );
257 let velocity_error = commanded_velocity - estimate.velocity_mps;
258
259 // A non-finite target or estimate yields no acceleration and never enters the integral
260 // or derivative history, where NaN would stick (it survives clamping). `cap_magnitude`
261 // zeroes a non-finite demand, so check its input too.
262 if !(all_finite(&desired_velocity) && all_finite(&velocity_error)) {
263 self.derivative.forget();
264 return Vec2::zeros();
265 }
266 let error_derivative = self.derivative.step(velocity_error, dt);
267 self.commanded_velocity_mps = commanded_velocity;
268
269 self.integrated_error = clamp_symmetric_each(
270 hold_against_limit(
271 self.integrated_error,
272 dt * velocity_error,
273 gains.i,
274 limit_mps2,
275 ),
276 config.max_integral,
277 );
278 feedforward_mps2
279 + gains.p * velocity_error
280 + gains.i * self.integrated_error
281 + gains.d * error_derivative
282 }
283
284 /// The velocity target to track and the acceleration to feed forward: `demand_mps` and
285 /// zero with shaping off (`max_accel_mps2` 0), which forgets the shaped target so turning
286 /// it on starts again from the measured velocity; else the shaped target moved toward the
287 /// demand by at most `max_accel_mps2 · dt`, starting from `measured_mps`, and its change
288 /// per second. A non-finite demand or measurement passes through unshaped (the caller
289 /// neutralizes it) and leaves the shaped target as it was.
290 fn shape(
291 &mut self,
292 max_accel_mps2: f32,
293 dt: f32,
294 demand_mps: Vec2,
295 measured_mps: Vec2,
296 ) -> (Vec2, Vec2) {
297 // `>` is false for NaN: an invalid limit acts as off.
298 let shaping = max_accel_mps2 > 0.0;
299 if !shaping {
300 self.shaped_velocity_mps = None;
301 return (demand_mps, Vec2::zeros());
302 }
303 if !(all_finite(&demand_mps) && all_finite(&measured_mps)) {
304 return (demand_mps, Vec2::zeros());
305 }
306 let from = self.shaped_velocity_mps.unwrap_or(measured_mps);
307 let to = from + cap_magnitude(demand_mps - from, max_accel_mps2 * dt);
308 self.shaped_velocity_mps = Some(to);
309 (to, (to - from) / dt)
310 }
311
312 /// The velocity, in m/s (north, east), the last finite [`control`](Self::control) asked the
313 /// velocity PID to track: the position loop's demand, shaped when shaping is on. Zero
314 /// before the first.
315 pub(crate) fn commanded_velocity_mps(&self) -> Vec2 {
316 self.commanded_velocity_mps
317 }
318
319 /// The accumulated error, for tests of the composites' integrator policy.
320 #[cfg(test)]
321 pub(crate) fn integrated_error(&self) -> Vec2 {
322 self.integrated_error
323 }
324
325 /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
326 /// tick's I term picks up where the last left off (`rescale_integral`).
327 pub(crate) fn rescale_integral(
328 &mut self,
329 old: &LateralControllerConfig,
330 new: &LateralControllerConfig,
331 ) {
332 let (old_i, new_i) = (old.velocity.i, new.velocity.i);
333 self.integrated_error = self
334 .integrated_error
335 .map(|e| rescale_integral(e, old_i, new_i));
336 }
337}
338
339/// Default [`LateralControllerConfig::braking_share`]: on a 260 m quadplane leg from 0.5 to
340/// 4 m/s², 0.7 overshoots at most 0.7 m, 0.9 up to 3.5 m, and 1.0 up to 6.4 m (#466).
341pub const DEFAULT_BRAKING_SHARE: f32 = 0.7;
342
343/// The deceleration the position loop's braking curve slows at, in m/s²: `braking_share` of
344/// `max_accel_mps2` with shaping on, else `brake_mps2`; 0 when neither is set, for the linear
345/// loop. An invalid value counts as unset.
346fn braking_decel_mps2(config: &LateralControllerConfig) -> f32 {
347 // `>` is false for NaN: an invalid limit acts as off.
348 if config.max_accel_mps2 > 0.0 {
349 config.braking_share * config.max_accel_mps2
350 } else if config.brake_mps2 > 0.0 {
351 config.brake_mps2
352 } else {
353 0.0
354 }
355}
356
357/// The position loop's velocity toward a target `error_m` away (north, east): `position_p ·
358/// error` with no braking deceleration (`decel_mps2` 0), else the braking curve's speed at
359/// `decel_mps2` ([`shaped_closing_speed`]), pointed at the target. A non-finite error passes
360/// through, so the caller's check sees it.
361fn closing_velocity(error_m: Vec2, position_p: f32, decel_mps2: f32) -> Vec2 {
362 if decel_mps2 <= 0.0 {
363 return position_p * error_m;
364 }
365 let distance_m = error_m.norm();
366 if !(distance_m > 0.0 && distance_m.is_finite()) {
367 return position_p * error_m;
368 }
369 let speed_mps = shaped_closing_speed(distance_m, position_p, decel_mps2);
370 error_m * (speed_mps / distance_m)
371}
372
373/// `integral + step`, except that a step whose I term pushes along `limit_mps2` may not
374/// lengthen the integral (it can still turn it): conditional integration against a capped
375/// output. A zero or non-finite `limit_mps2` never holds.
376fn hold_against_limit(integral: Vec2, step: Vec2, i: f32, limit_mps2: Vec2) -> Vec2 {
377 let next = integral + step;
378 // `>` is false for NaN, so a non-finite limit integrates freely.
379 if i * step.dot(&limit_mps2) > 0.0 {
380 cap_magnitude(next, integral.norm())
381 } else {
382 next
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use assert2::check;
389
390 use crate::Vec2;
391
392 use super::*;
393
394 /// A target at `position_m`, stopping there, with no speed cap.
395 fn at(position_m: Vec2) -> LateralTarget {
396 LateralTarget {
397 position_m,
398 velocity_mps: Vec2::zeros(),
399 max_speed_mps: 0.0,
400 }
401 }
402
403 /// The vehicle at the origin moving at `velocity_mps`.
404 fn moving(velocity_mps: Vec2) -> LateralEstimate {
405 LateralEstimate {
406 position_m: Vec2::zeros(),
407 velocity_mps,
408 }
409 }
410
411 fn p_only() -> LateralControllerConfig {
412 LateralControllerConfig {
413 position_p: 0.5,
414 velocity: Gains {
415 p: 2.0,
416 i: 0.0,
417 d: 0.0,
418 },
419 ..Default::default()
420 }
421 }
422
423 #[test]
424 fn accelerates_toward_the_target_against_velocity() {
425 // (target, velocity, expected acceleration) with the vehicle at the origin
426 let cases = [
427 (at(Vec2::zeros()), Vec2::zeros(), Vec2::zeros()),
428 (
429 at(Vec2::new(10.0, 0.0)),
430 Vec2::zeros(),
431 Vec2::new(10.0, 0.0),
432 ), // no cap
433 (
434 at(Vec2::new(0.0, -3.0)),
435 Vec2::zeros(),
436 Vec2::new(0.0, -3.0),
437 ),
438 (
439 at(Vec2::zeros()),
440 Vec2::new(4.0, -2.0),
441 Vec2::new(-8.0, 4.0),
442 ), // brakes
443 (at(Vec2::new(0.0, f32::NAN)), Vec2::zeros(), Vec2::zeros()),
444 (
445 at(Vec2::new(f32::INFINITY, 0.0)),
446 Vec2::zeros(),
447 Vec2::zeros(),
448 ), // non-finite
449 ];
450 for (target, velocity, expected) in cases {
451 let mut controller = LateralController::default();
452 let accel =
453 controller.control(&p_only(), 0.004, target, moving(velocity), Vec2::zeros());
454 assert!(
455 (accel - expected).amax() < 1e-5,
456 "target {target:?}, velocity {velocity:?} gave {accel:?}, expected {expected:?}"
457 );
458 }
459 }
460
461 /// The desired velocity is capped at `max_speed_mps`, keeping its direction; zero,
462 /// negative, and NaN limits leave it uncapped.
463 #[test]
464 fn caps_the_desired_speed() {
465 let far = Vec2::new(30.0, 40.0); // 50 m away: desired 25 m/s uncapped
466 // (max_speed_mps, velocity feedforward, expected acceleration from rest)
467 let cases = [
468 (5.0, Vec2::zeros(), Vec2::new(6.0, 8.0)), // 5 m/s toward (3, 4)/5, × P 2
469 (100.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
470 (0.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
471 (-1.0, Vec2::zeros(), Vec2::new(30.0, 40.0)),
472 (f32::NAN, Vec2::zeros(), Vec2::new(30.0, 40.0)),
473 // Feedforward adds before the cap.
474 (5.0, Vec2::new(15.0, 20.0), Vec2::new(6.0, 8.0)),
475 ];
476 for (max_speed_mps, velocity_mps, expected) in cases {
477 let target = LateralTarget {
478 position_m: far,
479 velocity_mps,
480 max_speed_mps,
481 };
482 let accel = LateralController::default().control(
483 &p_only(),
484 0.004,
485 target,
486 moving(Vec2::zeros()),
487 Vec2::zeros(),
488 );
489 assert!(
490 (accel - expected).amax() < 1e-4,
491 "max {max_speed_mps}, ff {velocity_mps:?} gave {accel:?}, expected {expected:?}"
492 );
493 }
494 }
495
496 /// On the target, the feedforward velocity is the whole demand: flying at it needs no
497 /// acceleration, and at rest the loop accelerates toward it.
498 #[test]
499 fn feedforward_flies_through_the_target() {
500 let target = LateralTarget {
501 position_m: Vec2::zeros(),
502 velocity_mps: Vec2::new(7.0, 0.0),
503 max_speed_mps: 7.0,
504 };
505 let config = p_only();
506 let cruising = LateralController::default().control(
507 &config,
508 0.004,
509 target,
510 moving(Vec2::new(7.0, 0.0)),
511 Vec2::zeros(),
512 );
513 let at_rest = LateralController::default().control(
514 &config,
515 0.004,
516 target,
517 moving(Vec2::zeros()),
518 Vec2::zeros(),
519 );
520 assert!(cruising == Vec2::zeros());
521 assert!((at_rest - Vec2::new(14.0, 0.0)).amax() < 1e-5);
522 }
523
524 /// Below the cap, the default cascade is the flight-checked position PD it replaced,
525 /// `0.63 · e − 1.26 · v`, plus the velocity I, here one tick of it.
526 #[test]
527 fn default_gains_are_the_position_pd_plus_velocity_i() {
528 let config = LateralControllerConfig::default();
529 const DT: f32 = 0.004;
530 // (position error, velocity)
531 let cases = [
532 (Vec2::new(2.0, -1.0), Vec2::zeros()),
533 (Vec2::zeros(), Vec2::new(1.0, 0.5)),
534 (Vec2::new(-3.0, 4.0), Vec2::new(0.4, -0.2)),
535 ];
536 for (error, velocity) in cases {
537 let accel = LateralController::default().control(
538 &config,
539 DT,
540 at(error),
541 moving(velocity),
542 Vec2::zeros(),
543 );
544 let velocity_error = 0.5 * error - velocity;
545 let expected = 0.63 * error - 1.26 * velocity + 0.4 * DT * velocity_error;
546 assert!(
547 (accel - expected).amax() < 1e-5,
548 "error {error:?}, velocity {velocity:?} gave {accel:?}"
549 );
550 }
551 }
552
553 /// Against a constant disturbance (a steady wind's drag), the default gains settle on the
554 /// target rather than offset from it: drag over the position-to-tilt gain without I.
555 #[test]
556 fn default_gains_trim_a_constant_disturbance() {
557 const DT: f32 = 0.02;
558 const DRAG_MPS2: f32 = 1.5;
559 let config = LateralControllerConfig::default();
560 let mut controller = LateralController::default();
561 let (mut position_m, mut velocity_mps) = (Vec2::zeros(), Vec2::zeros());
562 let drag = Vec2::new(DRAG_MPS2, 0.0);
563 for _ in 0..(60.0 / DT) as usize {
564 let estimate = LateralEstimate {
565 position_m,
566 velocity_mps,
567 };
568 let accel = controller.control(&config, DT, at(Vec2::zeros()), estimate, Vec2::zeros());
569 velocity_mps += (accel + drag) * DT;
570 position_m += velocity_mps * DT;
571 }
572 assert!(position_m.norm() < 0.01, "settled at {position_m:?}");
573 }
574
575 /// While `limit` points along the I term's push, the integral can't lengthen; it still
576 /// shrinks or turns, and a zero, opposed, or non-finite limit doesn't hold.
577 #[test]
578 fn integral_is_held_against_the_limit() {
579 let x = Vec2::new(1.0, 0.0);
580 let y = Vec2::new(0.0, 1.0);
581 // (integral, step, i, limit, expected)
582 let cases = [
583 (x, x, 0.4, Vec2::zeros(), 2.0 * x), // no limit
584 (x, x, 0.4, x, x), // held at its length
585 (Vec2::zeros(), x, 0.4, x, Vec2::zeros()), // can't start along the limit
586 (x, -x, 0.4, x, Vec2::zeros()), // shrinks
587 (x, 0.5 * x, 0.4, -x, 1.5 * x), // limit the other way
588 (x, y, 0.4, y, (x + y) / 2.0_f32.sqrt()), // turns, keeps length
589 (x, x, 0.0, x, 2.0 * x), // no I term: nothing to hold
590 (x, x, 0.4, Vec2::new(f32::NAN, 0.0), 2.0 * x), // non-finite limit
591 ];
592 for (integral, step, i, limit, expected) in cases {
593 let held = hold_against_limit(integral, step, i, limit);
594 assert!(
595 (held - expected).amax() < 1e-6,
596 "{integral:?} + {step:?} against {limit:?} gave {held:?}, expected {expected:?}"
597 );
598 }
599 }
600
601 /// A NaN or infinite velocity estimate gives no acceleration, not NaN.
602 #[test]
603 fn non_finite_velocity_yields_no_acceleration() {
604 let nan = f32::NAN;
605 let inf = f32::INFINITY;
606 let velocities = [
607 Vec2::new(nan, 0.0),
608 Vec2::new(0.0, inf),
609 Vec2::new(-inf, nan),
610 ];
611 let config = LateralControllerConfig::default();
612 for velocity in velocities {
613 let mut controller = LateralController::default();
614 let accel = controller.control(
615 &config,
616 0.004,
617 at(Vec2::new(10.0, 5.0)),
618 moving(velocity),
619 Vec2::zeros(),
620 );
621 assert!(
622 accel == Vec2::zeros(),
623 "velocity {velocity:?} gave {accel:?}"
624 );
625 }
626 }
627
628 #[test]
629 fn integral_term_is_clamped_to_max_integral() {
630 let config = LateralControllerConfig {
631 max_integral: 5.0,
632 ..Default::default()
633 };
634 let mut controller = LateralController::default();
635
636 // A large, persistent error for many ticks would wind the integral far past the limit.
637 for _ in 0..10_000 {
638 controller.control(
639 &config,
640 0.01,
641 at(Vec2::new(100.0, -100.0)),
642 moving(Vec2::zeros()),
643 Vec2::zeros(),
644 );
645 }
646
647 assert!(controller.integrated_error == Vec2::new(5.0, -5.0));
648 }
649
650 #[test]
651 fn recovers_after_a_nan_tick() {
652 let config = LateralControllerConfig {
653 velocity: Gains {
654 p: 1.0,
655 i: 0.5,
656 d: 0.1,
657 },
658 ..Default::default()
659 };
660 let mut controller = LateralController::default();
661 let at_rest = moving(Vec2::zeros());
662
663 // One tick with a NaN target must not poison later ticks.
664 let during = controller.control(
665 &config,
666 0.004,
667 at(Vec2::new(f32::NAN, 0.0)),
668 at_rest,
669 Vec2::zeros(),
670 );
671 let after = controller.control(
672 &config,
673 0.004,
674 at(Vec2::new(10.0, 0.0)),
675 at_rest,
676 Vec2::zeros(),
677 );
678
679 assert!(during == Vec2::zeros(), "NaN tick gave {during:?}");
680 let fresh = LateralController::default().control(
681 &config,
682 0.004,
683 at(Vec2::new(10.0, 0.0)),
684 at_rest,
685 Vec2::zeros(),
686 );
687 assert!(after == fresh, "valid target after NaN gave {after:?}");
688 }
689
690 /// The D term acts on the change in velocity error, with no kick on the first tick.
691 #[test]
692 fn derivative_acts_on_the_velocity_error_change() {
693 let config = LateralControllerConfig {
694 position_p: 0.0,
695 velocity: Gains {
696 p: 0.0,
697 i: 0.0,
698 d: 0.5,
699 },
700 ..Default::default()
701 };
702 let mut controller = LateralController::default();
703 let target = at(Vec2::zeros());
704 let first = controller.control(
705 &config,
706 0.1,
707 target,
708 moving(Vec2::new(1.0, 0.0)),
709 Vec2::zeros(),
710 );
711 let second = controller.control(
712 &config,
713 0.1,
714 target,
715 moving(Vec2::new(2.0, 0.0)),
716 Vec2::zeros(),
717 );
718 assert!(first == Vec2::zeros());
719 assert!((second - Vec2::new(-5.0, 0.0)).amax() < 1e-4);
720 }
721
722 /// An invalid limit fails `validate` but `control` stays panic-free: it acts as 0.
723 #[test]
724 fn invalid_config_is_rejected_and_does_not_panic_the_tick() {
725 let negative_integral = LateralControllerConfig {
726 max_integral: -1.0,
727 ..Default::default()
728 };
729 let nan_position_p = LateralControllerConfig {
730 position_p: f32::NAN,
731 ..Default::default()
732 };
733 assert_eq!(
734 negative_integral.validate().map_err(|e| e.field),
735 Err("max_integral")
736 );
737 assert_eq!(
738 nan_position_p.validate().map_err(|e| e.field),
739 Err("position_p")
740 );
741 for max_integral in [-1.0, f32::NAN] {
742 let config = LateralControllerConfig {
743 max_integral,
744 ..Default::default()
745 };
746 let mut controller = LateralController::default();
747 controller.control(
748 &config,
749 0.01,
750 at(Vec2::new(1.0, 1.0)),
751 moving(Vec2::zeros()),
752 Vec2::zeros(),
753 );
754 assert!(
755 controller.integrated_error == Vec2::zeros(),
756 "max_integral {max_integral}"
757 );
758 }
759 }
760
761 /// `p_only` with the velocity target shaped at `max_accel_mps2`.
762 fn shaped(max_accel_mps2: f32) -> LateralControllerConfig {
763 LateralControllerConfig {
764 max_accel_mps2,
765 ..p_only()
766 }
767 }
768
769 /// 30 m north at up to 3 m/s: a 3 m/s demand north.
770 fn leg() -> LateralTarget {
771 LateralTarget {
772 max_speed_mps: 3.0,
773 ..at(Vec2::new(30.0, 0.0))
774 }
775 }
776
777 /// The first run's shaped target starts at the measured velocity and moves at most
778 /// `max_accel_mps2 · dt` toward the demand, that change fed forward; 0 is off.
779 #[test]
780 fn shaped_target_starts_at_the_measured_velocity() {
781 let dt = 0.1;
782 // Sideways at 2 m/s east, toward a 3 m/s demand north: a 0.1 m/s step along (3, −2).
783 let turn = Vec2::new(3.0, -2.0).normalize();
784 // (max_accel_mps2, measured velocity, expected acceleration: feedforward + P 2 · error)
785 let cases = [
786 (0.0, Vec2::zeros(), Vec2::new(6.0, 0.0)), // off: the whole 3 m/s error
787 (1.0, Vec2::zeros(), Vec2::new(1.0 + 2.0 * 0.1, 0.0)),
788 (1.0, Vec2::new(3.0, 0.0), Vec2::zeros()), // already at the demand
789 (1.0, Vec2::new(0.0, 2.0), turn + 2.0 * 0.1 * turn),
790 // Within one step: the demand at once, its 3 m/s in 0.1 s fed forward.
791 (100.0, Vec2::zeros(), Vec2::new(30.0 + 2.0 * 3.0, 0.0)),
792 ];
793 for (max_accel_mps2, velocity, expected) in cases {
794 let accel = LateralController::default().control(
795 &shaped(max_accel_mps2),
796 dt,
797 leg(),
798 moving(velocity),
799 Vec2::zeros(),
800 );
801 check!(
802 (accel - expected).amax() < 1e-4,
803 "limit {max_accel_mps2}, velocity {velocity:?}: {accel:?}, expected {expected:?}"
804 );
805 }
806 }
807
808 /// From rest with the vehicle held still, the shaped target ramps to the demand at the
809 /// limit, then stops ramping: its feedforward ends and the PID sees the whole error.
810 #[test]
811 fn shaped_target_ramps_to_the_demand() {
812 let (dt, config) = (0.1, shaped(1.0));
813 let mut controller = LateralController::default();
814 let mut accels = Vec::new();
815 for _ in 0..32 {
816 accels.push(controller.control(
817 &config,
818 dt,
819 leg(),
820 moving(Vec2::zeros()),
821 Vec2::zeros(),
822 ));
823 }
824 // (tick, expected north acceleration: feedforward + P 2 · shaped speed)
825 let cases = [
826 (0, 1.0 + 2.0 * 0.1),
827 (14, 1.0 + 2.0 * 1.5),
828 (29, 1.0 + 2.0 * 3.0), // the last step reaches 3 m/s
829 (30, 2.0 * 3.0),
830 (31, 2.0 * 3.0),
831 ];
832 for (tick, expected) in cases {
833 let accel = accels[tick];
834 check!(
835 (accel - Vec2::new(expected, 0.0)).amax() < 1e-3,
836 "tick {tick}: {accel:?}, expected {expected}"
837 );
838 }
839 }
840
841 /// The braking curve slows at `braking_share` of the shaping limit with shaping on, whatever
842 /// `brake_mps2`; at `brake_mps2` with it off; and not at all (linear) with neither, an
843 /// invalid value acting as unset.
844 #[test]
845 fn braking_decel_comes_from_shaping_then_brake() {
846 // (max_accel_mps2, brake_mps2, braking_share, expected decel in m/s²)
847 let cases = [
848 (0.0, 0.0, 0.7, 0.0),
849 (1.0, 0.0, 0.7, 0.7),
850 (2.0, 0.0, 0.5, 1.0), // the configured share
851 (1.0, 1.5, 0.7, 0.7), // shaping wins
852 (0.0, 1.5, 0.5, 1.5), // the share is shaping's only
853 (f32::NAN, 1.5, 0.7, 1.5),
854 (-1.0, 1.5, 0.7, 1.5),
855 (0.0, f32::NAN, 0.7, 0.0),
856 (0.0, -1.0, 0.7, 0.0),
857 ];
858 for (max_accel_mps2, brake_mps2, braking_share, expected) in cases {
859 let config = LateralControllerConfig {
860 max_accel_mps2,
861 brake_mps2,
862 braking_share,
863 ..LateralControllerConfig::default()
864 };
865 let decel = braking_decel_mps2(&config);
866 check!(
867 (decel - expected).abs() < 1e-6,
868 "shaping {max_accel_mps2}, brake {brake_mps2}: {decel}, expected {expected}"
869 );
870 }
871 }
872
873 #[test]
874 fn rejects_each_field_out_of_range() {
875 let base = LateralControllerConfig::default;
876 // (case, config, the field named)
877 let cases = [
878 (
879 "position_p",
880 LateralControllerConfig {
881 position_p: -1.0,
882 ..base()
883 },
884 ),
885 (
886 "max_integral",
887 LateralControllerConfig {
888 max_integral: f32::NAN,
889 ..base()
890 },
891 ),
892 (
893 "max_accel_mps2",
894 LateralControllerConfig {
895 max_accel_mps2: -1.0,
896 ..base()
897 },
898 ),
899 (
900 "brake_mps2",
901 LateralControllerConfig {
902 brake_mps2: f32::INFINITY,
903 ..base()
904 },
905 ),
906 (
907 "braking_share",
908 LateralControllerConfig {
909 braking_share: 0.0,
910 ..base()
911 },
912 ),
913 (
914 "braking_share",
915 LateralControllerConfig {
916 braking_share: 1.1,
917 ..base()
918 },
919 ),
920 (
921 "braking_share",
922 LateralControllerConfig {
923 braking_share: f32::NAN,
924 ..base()
925 },
926 ),
927 ];
928 check!(base().validate().is_ok());
929 for (field, config) in cases {
930 check!(
931 config.validate().map_err(|e| e.field) == Err(field),
932 "{config:?}"
933 );
934 }
935 }
936
937 /// The position loop's speed toward the target follows the braking curve at its
938 /// deceleration, pointed at the target: linear within `a / p²` (2.8 m at 0.7 m/s² and P
939 /// 0.5), the square root beyond; with none, `p · error`.
940 #[test]
941 fn closing_velocity_follows_the_braking_curve() {
942 let p = 0.5;
943 // (error, decel_mps2, expected velocity)
944 let cases = [
945 (Vec2::new(30.0, 0.0), 0.0, Vec2::new(15.0, 0.0)), // none: linear
946 (Vec2::new(2.0, 0.0), 0.7, Vec2::new(1.0, 0.0)), // inside the linear part
947 // √(2 · 0.7 · (30 − 1.4)) beyond it
948 (Vec2::new(30.0, 0.0), 0.7, Vec2::new(6.3277, 0.0)),
949 (Vec2::new(0.0, -30.0), 0.7, Vec2::new(0.0, -6.3277)),
950 (Vec2::new(18.0, 24.0), 0.7, Vec2::new(0.6, 0.8) * 6.3277),
951 (Vec2::zeros(), 0.7, Vec2::zeros()),
952 ];
953 for (error_m, decel_mps2, expected) in cases {
954 let velocity = closing_velocity(error_m, p, decel_mps2);
955 check!(
956 (velocity - expected).amax() < 1e-3,
957 "error {error_m:?}, decel {decel_mps2}: {velocity:?}, expected {expected:?}"
958 );
959 }
960 check!(
961 closing_velocity(Vec2::new(f32::NAN, 0.0), p, 0.7)
962 .x
963 .is_nan()
964 );
965 }
966
967 /// 10 m out with shaping on, a vehicle closing at the braking curve's 3.47 m/s
968 /// (`√(2 · 0.7 · (10 − 1.4))`) holds that speed; the linear loop's 5 m/s would speed it up.
969 #[test]
970 fn closing_at_the_braking_curve_holds_its_speed() {
971 let closing_mps = (2.0_f32 * 0.7 * (10.0 - 1.4)).sqrt();
972 let accel = LateralController::default().control(
973 &shaped(1.0),
974 0.1,
975 at(Vec2::new(10.0, 0.0)),
976 moving(Vec2::new(closing_mps, 0.0)),
977 Vec2::zeros(),
978 );
979 check!(accel.amax() < 1e-4, "{accel:?}");
980 }
981
982 /// 30 m out with shaping off, `brake_mps2` 1.5 puts the braking curve at 9 m/s
983 /// (`√(2 · 1.5 · (30 − 3))`): a vehicle closing at it holds its speed, a faster one brakes,
984 /// and without it the linear loop's 15 m/s speeds the vehicle up (#488).
985 #[test]
986 fn unshaped_braking_slows_along_the_curve() {
987 // (brake_mps2, closing speed in m/s, expected acceleration in m/s² at velocity P 2)
988 let cases = [(1.5, 9.0, 0.0), (1.5, 12.0, -6.0), (0.0, 9.0, 12.0)];
989 for (brake_mps2, closing_mps, expected) in cases {
990 let config = LateralControllerConfig {
991 brake_mps2,
992 ..p_only()
993 };
994 let accel = LateralController::default().control(
995 &config,
996 0.1,
997 at(Vec2::new(30.0, 0.0)),
998 moving(Vec2::new(closing_mps, 0.0)),
999 Vec2::zeros(),
1000 );
1001 check!(
1002 (accel - Vec2::new(expected, 0.0)).amax() < 1e-3,
1003 "brake {brake_mps2} at {closing_mps} m/s: {accel:?}, expected {expected}"
1004 );
1005 }
1006 }
1007
1008 /// A negative or NaN braking deceleration fails validation, and in the tick brakes linearly.
1009 #[test]
1010 fn invalid_brake_is_rejected_and_brakes_linearly() {
1011 for brake_mps2 in [-1.0, f32::NAN] {
1012 let config = LateralControllerConfig {
1013 brake_mps2,
1014 ..p_only()
1015 };
1016 check!(config.validate().map_err(|e| e.field) == Err("brake_mps2"));
1017 let accel = LateralController::default().control(
1018 &config,
1019 0.1,
1020 at(Vec2::new(30.0, 0.0)),
1021 moving(Vec2::zeros()),
1022 Vec2::zeros(),
1023 );
1024 check!(
1025 (accel - Vec2::new(30.0, 0.0)).amax() < 1e-3,
1026 "brake {brake_mps2}: {accel:?}"
1027 );
1028 }
1029 }
1030
1031 /// A non-finite velocity gives no acceleration and leaves the shaped target where it was:
1032 /// the next finite tick moves on from it.
1033 #[test]
1034 fn non_finite_velocity_keeps_the_shaped_target() {
1035 let (dt, config) = (0.1, shaped(1.0));
1036 let mut controller = LateralController::default();
1037 let mut run = |velocity: Vec2| {
1038 controller.control(&config, dt, leg(), moving(velocity), Vec2::zeros())
1039 };
1040 run(Vec2::zeros()); // shaped 0.1 m/s
1041 check!(run(Vec2::new(f32::NAN, 0.0)) == Vec2::zeros());
1042 let accel = run(Vec2::zeros()); // shaped 0.2 m/s
1043 check!((accel - Vec2::new(1.0 + 2.0 * 0.2, 0.0)).amax() < 1e-4);
1044 }
1045
1046 /// Turning shaping off between runs forgets the shaped target: turned back on, it starts
1047 /// again from the measured velocity, not from where it was.
1048 #[test]
1049 fn shaping_off_forgets_the_shaped_target() {
1050 let dt = 0.1;
1051 let mut controller = LateralController::default();
1052 for _ in 0..10 {
1053 controller.control(
1054 &shaped(1.0),
1055 dt,
1056 leg(),
1057 moving(Vec2::zeros()),
1058 Vec2::zeros(),
1059 );
1060 }
1061 controller.control(
1062 &shaped(0.0),
1063 dt,
1064 leg(),
1065 moving(Vec2::zeros()),
1066 Vec2::zeros(),
1067 );
1068 let accel = controller.control(
1069 &shaped(1.0),
1070 dt,
1071 leg(),
1072 moving(Vec2::zeros()),
1073 Vec2::zeros(),
1074 );
1075 // From rest again: 0.1 m/s, not 1.1.
1076 check!(
1077 (accel - Vec2::new(1.0 + 2.0 * 0.1, 0.0)).amax() < 1e-4,
1078 "{accel:?}"
1079 );
1080 }
1081
1082 /// A negative or NaN acceleration limit fails validation, and in the tick shapes nothing.
1083 #[test]
1084 fn invalid_accel_limit_is_rejected_and_shapes_nothing() {
1085 for max_accel_mps2 in [-1.0, f32::NAN] {
1086 let config = shaped(max_accel_mps2);
1087 check!(config.validate().map_err(|e| e.field) == Err("max_accel_mps2"));
1088 let accel = LateralController::default().control(
1089 &config,
1090 0.1,
1091 leg(),
1092 moving(Vec2::zeros()),
1093 Vec2::zeros(),
1094 );
1095 check!(
1096 (accel - Vec2::new(6.0, 0.0)).amax() < 1e-4,
1097 "limit {max_accel_mps2}: {accel:?}"
1098 );
1099 }
1100 }
1101
1102 /// A gain change between ticks applies on the next tick and keeps the integral.
1103 #[test]
1104 fn gain_change_between_ticks_keeps_state() {
1105 let config = LateralControllerConfig::default();
1106 let mut controller = LateralController::default();
1107 controller.control(
1108 &config,
1109 1.0,
1110 at(Vec2::new(0.0, 1.0)),
1111 moving(Vec2::zeros()),
1112 Vec2::zeros(),
1113 );
1114 let integral = controller.integrated_error;
1115
1116 let retuned = LateralControllerConfig {
1117 position_p: 0.0,
1118 velocity: Gains {
1119 p: 0.0,
1120 i: 2.0,
1121 d: 0.0,
1122 },
1123 ..config
1124 };
1125 let accel = controller.control(
1126 &retuned,
1127 0.01,
1128 at(Vec2::zeros()),
1129 moving(Vec2::zeros()),
1130 Vec2::zeros(),
1131 );
1132
1133 assert!(controller.integrated_error == integral);
1134 approx::assert_relative_eq!(accel.y, 2.0 * integral.y, epsilon = 1e-6);
1135 }
1136
1137 #[test]
1138 #[should_panic(expected = "dt must be positive and finite")]
1139 fn zero_dt_panics() {
1140 LateralController::default().control(
1141 &LateralControllerConfig::default(),
1142 0.0,
1143 at(Vec2::zeros()),
1144 moving(Vec2::zeros()),
1145 Vec2::zeros(),
1146 );
1147 }
1148}