stable_flight/controllers/altitude.rs
1use nalgebra::UnitQuaternion;
2
3use crate::GRAVITY;
4use crate::controllers::{
5 Gains, InvalidConfig, check_limit, check_positive, check_unit_interval, rescale_integral,
6};
7use crate::math::{assert_dt, clamp_symmetric, tilt_boost};
8
9/// Default [`AltitudeControllerConfig::hover_thrust`].
10pub const DEFAULT_HOVER_THRUST: f32 = 0.5;
11
12/// Default [`AltitudeControllerConfig::integration_band_m`]: with gravity fed forward the
13/// integral just trims a `hover_thrust` mismatch, and winding it up over a long climb made the
14/// vehicle overshoot and settle slowly.
15pub const DEFAULT_INTEGRATION_BAND_M: f32 = 1.0;
16
17/// Configures the [`AltitudeController`].
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub struct AltitudeControllerConfig {
20 /// PID gains from altitude error (m) to vertical acceleration (m/s², up).
21 pub gains: Gains,
22 /// Maximum absolute value of the integrated altitude error, in m·s.
23 /// Prevents integral windup by limiting error accumulation.
24 pub max_integral: f32,
25
26 /// Linear thrust (before the stabilizer's thrust curve) that holds a level hover. The
27 /// controller feeds it forward, so the integral only trims the residual. Airframe-specific.
28 pub hover_thrust: f32,
29 /// The integral accumulates only within this many meters of the target altitude. Wider:
30 /// trims a `hover_thrust` mismatch from farther off, but winds up over a long climb or
31 /// descent and overshoots the target. Must be positive and finite. Defaults to
32 /// [`DEFAULT_INTEGRATION_BAND_M`].
33 pub integration_band_m: f32,
34}
35
36impl Default for AltitudeControllerConfig {
37 fn default() -> Self {
38 Self {
39 // A double integrator like the lateral loop: ζ ≈ 0.8. The small I trims a
40 // `hover_thrust` mismatch. Flight-checked on RealFlight's QuadCopterX (#96).
41 gains: Gains {
42 p: 1.5,
43 i: 0.2,
44 d: 2.0,
45 },
46 // With feedforward the integral only trims hover; 5 m·s at I 0.2 is ±1 m/s².
47 max_integral: 5.0,
48 hover_thrust: DEFAULT_HOVER_THRUST,
49 integration_band_m: DEFAULT_INTEGRATION_BAND_M,
50 }
51 }
52}
53
54impl AltitudeControllerConfig {
55 /// Checks the config: `max_integral` must be non-negative and finite, `hover_thrust` in
56 /// `(0, 1]`, and `integration_band_m` positive and finite.
57 ///
58 /// # Examples
59 ///
60 /// ```
61 /// use stable_flight::controllers::AltitudeControllerConfig;
62 ///
63 /// assert!(AltitudeControllerConfig::default().validate().is_ok());
64 /// let bad = AltitudeControllerConfig { hover_thrust: 1.5, ..Default::default() };
65 /// assert!(bad.validate().is_err());
66 /// ```
67 pub fn validate(&self) -> Result<(), InvalidConfig> {
68 check_limit("max_integral", self.max_integral)?;
69 check_unit_interval("hover_thrust", self.hover_thrust)?;
70 check_positive("integration_band_m", self.integration_band_m)
71 }
72}
73
74/// What the [`AltitudeController`] tracks: a target altitude and climb rate, z up as in the
75/// [`VehicleState`](crate::VehicleState) frame contract.
76///
77/// # Examples
78///
79/// ```
80/// use stable_flight::controllers::AltitudeTarget;
81///
82/// // Hold 10 m.
83/// let target = AltitudeTarget { altitude_m: 10.0, velocity_mps: 0.0 };
84/// ```
85#[derive(Clone, Copy, Debug, PartialEq)]
86pub struct AltitudeTarget {
87 /// Desired altitude in meters, up positive.
88 pub altitude_m: f32,
89 /// Desired vertical velocity in m/s, up positive; the D term damps toward it.
90 pub velocity_mps: f32,
91}
92
93/// The vehicle's current vertical state as the [`AltitudeController`] consumes it, taken from
94/// [`VehicleState`](crate::VehicleState) per its frame contract: altitude and climb rate are
95/// z up, attitude is NED world → FRD body.
96///
97/// # Examples
98///
99/// ```
100/// use stable_flight::controllers::AltitudeEstimate;
101/// use stable_flight::nalgebra::UnitQuaternion;
102///
103/// // 9.5 m, sinking slowly, level.
104/// let estimate = AltitudeEstimate {
105/// altitude_m: 9.5,
106/// velocity_mps: -0.1,
107/// attitude: UnitQuaternion::identity(),
108/// };
109/// ```
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct AltitudeEstimate {
112 /// Estimated altitude in meters, up positive.
113 pub altitude_m: f32,
114 /// Estimated vertical velocity in m/s, up positive.
115 pub velocity_mps: f32,
116 /// Estimated attitude, as [`VehicleState::attitude`](crate::VehicleState::attitude). Only the
117 /// tilt (cos roll · cos pitch) is used, for tilt compensation; yaw is ignored, an inverted
118 /// attitude gets no thrust, and a non-finite attitude counts as level.
119 pub attitude: UnitQuaternion<f32>,
120}
121
122/// Altitude PID loop with gravity feedforward: turns an altitude target into a linear thrust
123/// command.
124///
125/// It holds only state (the integral); gains and limits come from the
126/// [`AltitudeControllerConfig`] passed to each [`control`](Self::control) call, so they can
127/// change between ticks without resetting the state.
128#[derive(Clone, Debug, Default, PartialEq)]
129pub struct AltitudeController {
130 integrated_error: f32,
131}
132
133impl AltitudeController {
134 /// Controls the altitude of the vehicle by computing a normalized thrust command using a PID controller.
135 ///
136 /// The PID gives a vertical acceleration `a` (m/s², up); the thrust is
137 /// `hover_thrust · (g + a) / (g · cos tilt)`, saturated to `[0, 1]`. Zero error is hover,
138 /// and a tilted vehicle gets more thrust so its vertical component still balances gravity.
139 /// The boost stops growing past 60° (2×) and fades to zero thrust between about 84° and
140 /// 90°, so an inverted vehicle isn't driven toward the ground.
141 ///
142 /// # Arguments
143 ///
144 /// * `config` - Gains, limits, and hover thrust; assumed valid
145 /// ([`AltitudeControllerConfig::validate`]). An invalid config does not panic: a negative
146 /// or NaN `max_integral` acts as 0.
147 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
148 /// * `target` - Desired altitude and vertical velocity.
149 /// * `estimate` - Current altitude, vertical velocity, and attitude.
150 ///
151 /// # Returns
152 ///
153 /// A normalized thrust command (0.0 to 1.0).
154 ///
155 /// # Panics
156 ///
157 /// If `dt` is not positive and finite.
158 ///
159 /// # Examples
160 ///
161 /// ```
162 /// use stable_flight::controllers::{
163 /// AltitudeController, AltitudeControllerConfig, AltitudeEstimate, AltitudeTarget,
164 /// DEFAULT_HOVER_THRUST,
165 /// };
166 /// use stable_flight::nalgebra::UnitQuaternion;
167 ///
168 /// let config = AltitudeControllerConfig::default();
169 /// let mut controller = AltitudeController::default();
170 /// let dt = 0.004;
171 /// let target = AltitudeTarget { altitude_m: 10.0, velocity_mps: 0.0 };
172 /// let level = UnitQuaternion::identity();
173 ///
174 /// // On target, still, and level: the feedforward hover thrust.
175 /// let on_target = AltitudeEstimate { altitude_m: 10.0, velocity_mps: 0.0, attitude: level };
176 /// let thrust = controller.control(&config, dt, target, on_target);
177 /// assert!((thrust - DEFAULT_HOVER_THRUST).abs() < 1e-6);
178 ///
179 /// // Below target: more than hover.
180 /// let below = AltitudeEstimate { altitude_m: 9.5, velocity_mps: -0.1, attitude: level };
181 /// let thrust = controller.control(&config, dt, target, below);
182 /// assert!(thrust > DEFAULT_HOVER_THRUST && thrust <= 1.0);
183 /// ```
184 pub fn control(
185 &mut self,
186 config: &AltitudeControllerConfig,
187 dt: f32,
188 target: AltitudeTarget,
189 estimate: AltitudeEstimate,
190 ) -> f32 {
191 assert_dt(dt);
192 let gains = &config.gains;
193 let hover_thrust = config.hover_thrust;
194
195 let altitude_error = target.altitude_m - estimate.altitude_m;
196 let velocity_error = target.velocity_mps - estimate.velocity_mps;
197
198 // A non-finite error (NaN/∞ altitude or velocity) must never enter the integral, where
199 // it would stick (NaN survives clamping) and hold thrust at NaN → 0 for good. Neutral
200 // for altitude is *hover*, not zero thrust, so return the hover setpoint instead.
201 if !(altitude_error.is_finite() && velocity_error.is_finite()) {
202 return hover_thrust;
203 }
204
205 // Accumulate only near the target, but clamp every tick so a shrunk `max_integral`
206 // applies on the next tick even outside the band.
207 if altitude_error.abs() < config.integration_band_m {
208 self.integrated_error += altitude_error * dt;
209 }
210 self.integrated_error = clamp_symmetric(self.integrated_error, config.max_integral);
211
212 let acceleration =
213 gains.p * altitude_error + gains.d * velocity_error + gains.i * self.integrated_error;
214
215 // Boosted for tilt: at most 2× past 60°, none when inverted, none for a non-finite
216 // attitude (`math::tilt_boost`).
217 let linear_thrust =
218 hover_thrust * (GRAVITY + acceleration) / GRAVITY * tilt_boost(&estimate.attitude);
219 linear_thrust.clamp(0.0, 1.0)
220 }
221
222 /// The accumulated error, for tests of the composites' integrator policy.
223 #[cfg(test)]
224 pub(crate) fn integrated_error(&self) -> f32 {
225 self.integrated_error
226 }
227
228 /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
229 /// tick's I term picks up where the last left off (`rescale_integral`).
230 pub(crate) fn rescale_integral(
231 &mut self,
232 old: &AltitudeControllerConfig,
233 new: &AltitudeControllerConfig,
234 ) {
235 self.integrated_error = rescale_integral(self.integrated_error, old.gains.i, new.gains.i);
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 fn level() -> UnitQuaternion<f32> {
244 UnitQuaternion::identity()
245 }
246
247 fn target(altitude_m: f32) -> AltitudeTarget {
248 AltitudeTarget {
249 altitude_m,
250 velocity_mps: 0.0,
251 }
252 }
253
254 fn estimate(
255 altitude_m: f32,
256 velocity_mps: f32,
257 attitude: UnitQuaternion<f32>,
258 ) -> AltitudeEstimate {
259 AltitudeEstimate {
260 altitude_m,
261 velocity_mps,
262 attitude,
263 }
264 }
265
266 fn nan_attitude() -> UnitQuaternion<f32> {
267 let nan = f32::NAN;
268 UnitQuaternion::new_unchecked(nalgebra::Quaternion::new(nan, nan, nan, nan))
269 }
270
271 /// Thrust is `hover · (g + a) / (g · cos tilt)` with the PID's acceleration `a`: zero error
272 /// is hover, a bank adds thrust (yaw doesn't), the boost stops at 60° and fades to none
273 /// when inverted, and the result saturates to [0, 1].
274 #[test]
275 fn thrust_feeds_gravity_forward_and_boosts_for_tilt() {
276 let deg = f32::to_radians;
277 let attitude = |roll: f32, pitch: f32, yaw: f32| {
278 UnitQuaternion::from_euler_angles(deg(roll), deg(pitch), deg(yaw))
279 };
280 let hover = 0.4;
281 let cos = |d: f32| d.to_radians().cos();
282 // (altitude error m, climb rate m/s, attitude, expected thrust); P 1, D 0.5, no I
283 let cases = [
284 (0.0, 0.0, level(), hover),
285 (0.0, 0.0, attitude(0.0, 0.0, 120.0), hover),
286 (0.0, 0.0, attitude(30.0, 0.0, 0.0), hover / cos(30.0)),
287 (
288 0.0,
289 0.0,
290 attitude(-20.0, 20.0, 45.0),
291 hover / (cos(20.0) * cos(20.0)),
292 ),
293 (0.0, 0.0, attitude(75.0, 0.0, 0.0), hover / 0.5), // floored at 60°
294 (0.0, 0.0, attitude(170.0, 0.0, 0.0), 0.0), // inverted: no thrust
295 (1.0, 0.0, level(), hover * (GRAVITY + 1.0) / GRAVITY),
296 (-1.0, 0.0, level(), hover * (GRAVITY - 1.0) / GRAVITY),
297 (0.0, 2.0, level(), hover * (GRAVITY - 1.0) / GRAVITY), // climbing: damped
298 (100.0, 0.0, level(), 1.0), // saturates high
299 (-100.0, 0.0, level(), 0.0), // and low
300 (0.0, 0.0, nan_attitude(), hover), // non-finite: level
301 ];
302 for (error, climb, attitude, expected) in cases {
303 let config = AltitudeControllerConfig {
304 gains: Gains {
305 p: 1.0,
306 i: 0.0,
307 d: 0.5,
308 },
309 hover_thrust: hover,
310 ..Default::default()
311 };
312 let thrust = AltitudeController::default().control(
313 &config,
314 0.004,
315 target(10.0 + error),
316 estimate(10.0, climb, attitude),
317 );
318 approx::assert_relative_eq!(thrust, expected, epsilon = 1e-5);
319 }
320 }
321
322 /// The D term acts on `target - estimate` climb rate: a target climb adds thrust, tracking
323 /// it is hover.
324 #[test]
325 fn damps_toward_target_climb_rate() {
326 let hover = 0.4;
327 let config = AltitudeControllerConfig {
328 gains: Gains {
329 p: 0.0,
330 i: 0.0,
331 d: 0.5,
332 },
333 hover_thrust: hover,
334 ..Default::default()
335 };
336 // (target climb m/s, estimated climb m/s, expected thrust)
337 let cases = [
338 (2.0, 0.0, hover * (GRAVITY + 1.0) / GRAVITY),
339 (-2.0, 0.0, hover * (GRAVITY - 1.0) / GRAVITY),
340 (0.0, 2.0, hover * (GRAVITY - 1.0) / GRAVITY),
341 (2.0, 2.0, hover),
342 ];
343 for (target_climb, climb, expected) in cases {
344 let target = AltitudeTarget {
345 altitude_m: 10.0,
346 velocity_mps: target_climb,
347 };
348 let thrust = AltitudeController::default().control(
349 &config,
350 0.004,
351 target,
352 estimate(10.0, climb, level()),
353 );
354 approx::assert_relative_eq!(thrust, expected, epsilon = 1e-5);
355 }
356 }
357
358 /// The integral accumulates `error · dt` only within `integration_band_m` of the target, stops
359 /// at `max_integral`, and feeds into thrust as `I · ∫e`.
360 #[test]
361 fn integral_runs_near_target_only_and_is_clamped() {
362 let config = AltitudeControllerConfig {
363 gains: Gains {
364 p: 0.0,
365 i: 1.0,
366 d: 0.0,
367 },
368 max_integral: 2.0,
369 hover_thrust: 0.5,
370 integration_band_m: DEFAULT_INTEGRATION_BAND_M,
371 };
372 // (altitude error m, expected integral after 1000 ticks of 0.01 s)
373 let cases = [
374 (10.0, 0.0),
375 (-5.0, 0.0),
376 (0.5, 2.0),
377 (-0.5, -2.0),
378 (0.001, 0.01),
379 ];
380 for (error, expected) in cases {
381 let mut controller = AltitudeController::default();
382 for _ in 0..1_000 {
383 controller.control(
384 &config,
385 0.01,
386 target(10.0 + error),
387 estimate(10.0, 0.0, level()),
388 );
389 }
390 approx::assert_relative_eq!(controller.integrated_error, expected, epsilon = 1e-4);
391 }
392
393 let mut controller = AltitudeController {
394 integrated_error: 2.0,
395 };
396 let thrust = controller.control(&config, 0.01, target(10.0), estimate(10.0, 0.0, level()));
397 approx::assert_relative_eq!(thrust, 0.5 * (GRAVITY + 2.0) / GRAVITY, epsilon = 1e-5);
398 }
399
400 /// The band is the config's: 2 m off the target integrates within a 3 m band and not
401 /// within the default 1 m.
402 #[test]
403 fn integral_runs_within_the_configured_band() {
404 // (band m, expected integral after 100 ticks of 0.01 s at 2 m off)
405 for (integration_band_m, expected) in [(DEFAULT_INTEGRATION_BAND_M, 0.0), (3.0, 2.0)] {
406 let config = AltitudeControllerConfig {
407 integration_band_m,
408 max_integral: 10.0,
409 ..Default::default()
410 };
411 let mut controller = AltitudeController::default();
412 for _ in 0..100 {
413 controller.control(&config, 0.01, target(12.0), estimate(10.0, 0.0, level()));
414 }
415 approx::assert_relative_eq!(controller.integrated_error(), expected, epsilon = 1e-4);
416 }
417 }
418
419 #[test]
420 fn non_finite_input_holds_hover_and_does_not_poison_later_ticks() {
421 let (nan, inf) = (f32::NAN, f32::INFINITY);
422 // (target altitude, target velocity, estimated altitude, estimated velocity)
423 let cases = [
424 (20.0, 0.0, nan, 0.0),
425 (20.0, 0.0, 10.0, nan),
426 (20.0, 0.0, inf, 0.0),
427 (20.0, 0.0, nan, nan),
428 (nan, 0.0, 10.0, 0.0),
429 (20.0, nan, 10.0, 0.0),
430 (-inf, 0.0, 10.0, 0.0),
431 (20.0, inf, 10.0, 0.0),
432 ];
433 let config = AltitudeControllerConfig::default();
434 for (target_altitude, target_velocity, altitude, velocity) in cases {
435 let input = (target_altitude, target_velocity, altitude, velocity);
436 let mut controller = AltitudeController::default();
437 let bad_target = AltitudeTarget {
438 altitude_m: target_altitude,
439 velocity_mps: target_velocity,
440 };
441 let during = controller.control(
442 &config,
443 0.004,
444 bad_target,
445 estimate(altitude, velocity, level()),
446 );
447 assert!(during == DEFAULT_HOVER_THRUST, "{input:?} gave {during}");
448
449 let after =
450 controller.control(&config, 0.004, target(20.0), estimate(10.0, 0.0, level()));
451 let fresh = AltitudeController::default().control(
452 &config,
453 0.004,
454 target(20.0),
455 estimate(10.0, 0.0, level()),
456 );
457 assert!(after == fresh, "after {input:?}: {after} vs fresh {fresh}");
458 }
459 }
460
461 #[test]
462 fn validate_rejects_invalid_config() {
463 // (max_integral, hover_thrust, integration_band_m, offending field)
464 let cases = [
465 (-1.0, 0.5, 1.0, "max_integral"),
466 (5.0, 1.5, 1.0, "hover_thrust"),
467 (5.0, 0.5, 0.0, "integration_band_m"),
468 (5.0, 0.5, f32::INFINITY, "integration_band_m"),
469 ];
470 for (max_integral, hover_thrust, integration_band_m, field) in cases {
471 let config = AltitudeControllerConfig {
472 max_integral,
473 hover_thrust,
474 integration_band_m,
475 ..Default::default()
476 };
477 assert_eq!(
478 config.validate().map_err(|e| e.field),
479 Err(field),
480 "{config:?}"
481 );
482 }
483 }
484
485 /// An invalid `max_integral` fails `validate` but `control` stays panic-free: it acts as 0.
486 #[test]
487 fn invalid_max_integral_does_not_panic_the_tick() {
488 for max_integral in [-1.0, f32::NAN] {
489 let config = AltitudeControllerConfig {
490 max_integral,
491 ..Default::default()
492 };
493 let mut controller = AltitudeController::default();
494 controller.control(&config, 0.01, target(10.5), estimate(10.0, 0.0, level()));
495 assert_eq!(
496 controller.integrated_error, 0.0,
497 "max_integral {max_integral}"
498 );
499 }
500 }
501
502 /// A shrunk `max_integral` clamps the stored integral on the next tick, even when the error
503 /// is outside the integration band (where nothing accumulates).
504 #[test]
505 fn shrinking_max_integral_outside_the_band_clamps_the_integral() {
506 // (max_integral, expected integral after one tick 2 m below target)
507 for (max_integral, expected) in [(0.0, 0.0), (0.2, 0.2), (1.0, 0.5)] {
508 let mut controller = AltitudeController {
509 integrated_error: 0.5,
510 };
511 let config = AltitudeControllerConfig {
512 max_integral,
513 ..Default::default()
514 };
515 controller.control(&config, 0.01, target(12.0), estimate(10.0, 0.0, level()));
516 assert_eq!(
517 controller.integrated_error, expected,
518 "max_integral {max_integral}"
519 );
520 }
521 }
522
523 /// A gain change between ticks applies on the next tick and keeps the integral.
524 #[test]
525 fn gain_change_between_ticks_keeps_state() {
526 let config = AltitudeControllerConfig::default();
527 let mut controller = AltitudeController::default();
528 controller.control(&config, 1.0, target(10.5), estimate(10.0, 0.0, level()));
529 let integral = controller.integrated_error;
530
531 let retuned = AltitudeControllerConfig {
532 gains: Gains {
533 p: 0.0,
534 i: 0.4,
535 d: 0.0,
536 },
537 ..config
538 };
539 let thrust = controller.control(&retuned, 0.01, target(10.0), estimate(10.0, 0.0, level()));
540
541 assert_eq!(controller.integrated_error, integral);
542 let expected = config.hover_thrust * (GRAVITY + 0.4 * integral) / GRAVITY;
543 approx::assert_relative_eq!(thrust, expected, epsilon = 1e-5);
544 }
545
546 #[test]
547 #[should_panic(expected = "dt must be positive and finite")]
548 fn zero_dt_panics() {
549 AltitudeController::default().control(
550 &AltitudeControllerConfig::default(),
551 0.0,
552 target(10.0),
553 estimate(10.0, 0.0, level()),
554 );
555 }
556}