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