Skip to main content

stable_flight/controllers/
altitude.rs

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