Skip to main content

stable_flight/controllers/
body_rate.rs

1use crate::Vec3;
2
3use super::derivative::DerivativeState;
4use super::{Gains, InvalidConfig, check_limit, rescale_integral};
5use crate::math::{assert_dt, clamp_symmetric};
6
7/// Default proportional gain, in normalized moment per rad/s of rate error.
8const DEFAULT_P: f32 = 0.15;
9/// Default derivative gain, in normalized moment per rad/s².
10const DEFAULT_D: f32 = 0.003;
11/// Default yaw proportional gain. Yaw authority comes only from differential prop drag, so
12/// yaw needs more gain than roll and pitch.
13const DEFAULT_YAW_P: f32 = 0.3;
14/// Default yaw integral gain, in normalized moment per rad of accumulated error.
15const DEFAULT_YAW_I: f32 = 0.1;
16/// Default integral limit, in rad (accumulated rate error).
17const DEFAULT_MAX_INTEGRAL: f32 = 1.0;
18
19/// Configures the [BodyRateController] with PID gains and operational limits.
20///
21/// Gains map rate error (rad/s) straight to a normalized moment in `[-1, 1]`: `p` is moment per
22/// rad/s, `i` per rad of accumulated error, and `d` per rad/s².
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct BodyRateControllerConfig {
25    /// PID gains for the roll and pitch rates.
26    pub gains: Gains,
27
28    /// PID gains for the yaw rate.
29    pub yaw_gains: Gains,
30
31    /// Maximum absolute value of the integrated rate error, in rad, per axis.
32    /// Prevents integral windup by limiting error accumulation.
33    pub max_integral: f32,
34}
35
36impl Default for BodyRateControllerConfig {
37    fn default() -> Self {
38        Self {
39            gains: Gains {
40                p: DEFAULT_P,
41                i: 0.0,
42                d: DEFAULT_D,
43            },
44            yaw_gains: Gains {
45                p: DEFAULT_YAW_P,
46                i: DEFAULT_YAW_I,
47                d: 0.0,
48            },
49            max_integral: DEFAULT_MAX_INTEGRAL,
50        }
51    }
52}
53
54impl BodyRateControllerConfig {
55    /// Checks the config: `max_integral` must be non-negative and finite.
56    ///
57    /// # Examples
58    ///
59    /// ```
60    /// use stable_flight::controllers::BodyRateControllerConfig;
61    ///
62    /// assert!(BodyRateControllerConfig::default().validate().is_ok());
63    /// let bad = BodyRateControllerConfig { max_integral: -1.0, ..Default::default() };
64    /// assert!(bad.validate().is_err());
65    /// ```
66    pub fn validate(&self) -> Result<(), InvalidConfig> {
67        check_limit("max_integral", self.max_integral)
68    }
69
70    /// Gains per axis: roll and pitch use `gains`, yaw uses `yaw_gains`.
71    fn axis_gains(&self) -> [Gains; 3] {
72        [self.gains, self.gains, self.yaw_gains]
73    }
74}
75
76/// A PID-based controller for managing angular rates (roll, pitch, yaw) of a vehicle.
77///
78/// This controller uses a PID algorithm to compute corrective moments based on desired and estimated
79/// angular rates. It is designed as the innermost control loop, directly affecting motor commands.
80///
81/// It holds only state (integral and derivative history); gains and limits come from the
82/// [`BodyRateControllerConfig`] passed to each [`control`](Self::control) call, so they can
83/// change between ticks without resetting the state.
84///
85/// # Units
86/// - Time (`dt`) is in seconds.
87/// - Desired and estimated rates are expected in rad/s.
88/// - Output moments are `P·e + I·∫e + D·ė`, saturated to `[-1, 1]` per axis; the mixer scales
89///   them to motor commands.
90#[derive(Clone, Debug, Default, PartialEq)]
91pub struct BodyRateController {
92    /// Roll, pitch, and yaw, each with its own PID state.
93    axes: [RateAxis; 3],
94}
95
96/// One axis of the rate loop: its integral and derivative history.
97#[derive(Clone, Copy, Debug, Default, PartialEq)]
98struct RateAxis {
99    /// Integrated rate error, in rad.
100    integrated_error: f32,
101
102    /// Previous error for the derivative term; empty on the first tick and after a gap.
103    derivative: DerivativeState<f32>,
104}
105
106impl RateAxis {
107    /// `P·e + I·∫e + D·ė` for one axis, saturated to `[-1, 1]`. A non-finite `error_radps`
108    /// gives 0 and stays out of the integral and derivative state.
109    fn step(&mut self, gains: Gains, max_integral: f32, dt: f32, error_radps: f32) -> f32 {
110        if !error_radps.is_finite() {
111            self.derivative.forget();
112            return 0.0;
113        }
114
115        let error_derivative = self.derivative.step(error_radps, dt);
116        self.integrated_error =
117            clamp_symmetric(self.integrated_error + dt * error_radps, max_integral);
118
119        let moment =
120            gains.p * error_radps + gains.i * self.integrated_error + gains.d * error_derivative;
121        clamp_symmetric(moment, 1.0)
122    }
123}
124
125impl BodyRateController {
126    /// Controls the angular velocity (body rates) of the vehicle using a PID controller.
127    ///
128    /// Computes the error between desired and estimated rates (both rad/s) and applies PID
129    /// control to it, per axis: `config.gains` for roll and pitch, `config.yaw_gains` for yaw.
130    ///
131    /// # Arguments
132    ///
133    /// * `config` - Gains and limits; assumed valid ([`BodyRateControllerConfig::validate`]).
134    ///   An invalid limit does not panic: a negative or NaN `max_integral` acts as 0.
135    /// * `dt` - Time step since the last update in seconds (must be positive and finite).
136    /// * `desired_rates_radps` - Desired angular rates (roll, pitch, yaw) in rad/s.
137    /// * `estimated_rates_radps` - Current measured angular rates (roll, pitch, yaw) in rad/s.
138    ///
139    /// # Returns
140    ///
141    /// Moments (roll, pitch, yaw), each saturated to `[-1, 1]`.
142    ///
143    /// # Panics
144    ///
145    /// If `dt` is not positive and finite.
146    ///
147    /// A non-finite component in `desired_rates_radps` or `estimated_rates_radps` gives a zero
148    /// moment on that axis alone and leaves that axis's state untouched, so a bad gyro axis
149    /// doesn't take damping off the others (the input policy in `architecture.md`).
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use stable_flight::controllers::{BodyRateController, BodyRateControllerConfig};
155    /// use stable_flight::Vec3;
156    ///
157    /// let config = BodyRateControllerConfig::default();
158    /// let mut controller = BodyRateController::default();
159    /// let dt = 0.004; // seconds; 250 Hz control loop
160    /// let desired_rates_radps = Vec3::new(0.1, 0.0, 0.05); // roll, pitch, yaw rates (rad/s)
161    /// let estimated_rates_radps = Vec3::zeros();
162    ///
163    /// let moments = controller.control(&config, dt, desired_rates_radps, estimated_rates_radps);
164    /// assert!(moments.x > 0.0 && moments.z > 0.0);
165    /// assert!(moments.iter().all(|m| (-1.0..=1.0).contains(m)));
166    /// ```
167    pub fn control(
168        &mut self,
169        config: &BodyRateControllerConfig,
170        dt: f32,
171        desired_rates_radps: Vec3,
172        estimated_rates_radps: Vec3,
173    ) -> Vec3 {
174        assert_dt(dt);
175        let error = desired_rates_radps - estimated_rates_radps;
176        let gains = config.axis_gains();
177        Vec3::from_fn(|axis, _| {
178            self.axes[axis].step(gains[axis], config.max_integral, dt, error[axis])
179        })
180    }
181
182    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
183    /// tick's I term picks up where the last left off (`rescale_integral`).
184    pub(crate) fn rescale_integral(
185        &mut self,
186        old: &BodyRateControllerConfig,
187        new: &BodyRateControllerConfig,
188    ) {
189        let gains = old.axis_gains().into_iter().zip(new.axis_gains());
190        for (axis, (old, new)) in self.axes.iter_mut().zip(gains) {
191            axis.integrated_error = rescale_integral(axis.integrated_error, old.i, new.i);
192        }
193    }
194
195    /// The integrated rate error per axis, in rad.
196    #[cfg(test)]
197    fn integrated_error(&self) -> Vec3 {
198        Vec3::from_fn(|axis, _| self.axes[axis].integrated_error)
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use approx::assert_abs_diff_eq;
206    use assert2::assert;
207
208    const DT: f32 = 0.004;
209
210    /// The same gains on every axis.
211    fn config(p: f32, i: f32, d: f32) -> BodyRateControllerConfig {
212        BodyRateControllerConfig {
213            gains: Gains { p, i, d },
214            yaw_gains: Gains { p, i, d },
215            max_integral: 1.0,
216        }
217    }
218
219    /// One tick from a fresh controller is `P·e + I·e·dt` (no derivative history yet; see
220    /// `first_tick_has_no_derivative_kick`), saturated to `[-1, 1]` per axis.
221    #[test]
222    fn first_tick_output_is_saturated_p_plus_i() {
223        // (p, i, desired, estimated, expected)
224        let cases = [
225            (0.15, 0.0, Vec3::zeros(), Vec3::zeros(), Vec3::zeros()),
226            (
227                0.15,
228                0.0,
229                Vec3::new(1.0, 0.0, 0.0),
230                Vec3::zeros(),
231                Vec3::new(0.15, 0.0, 0.0),
232            ),
233            (
234                0.15,
235                0.0,
236                Vec3::new(0.0, 2.0, -2.0),
237                Vec3::zeros(),
238                Vec3::new(0.0, 0.3, -0.3),
239            ),
240            (
241                0.15,
242                0.0,
243                Vec3::new(1.0, 1.0, 1.0),
244                Vec3::new(1.0, 2.0, 0.0),
245                Vec3::new(0.0, -0.15, 0.15),
246            ),
247            (
248                0.15,
249                0.0,
250                Vec3::new(10.0, -10.0, 0.0),
251                Vec3::zeros(),
252                Vec3::new(1.0, -1.0, 0.0),
253            ),
254            (
255                0.0,
256                10.0,
257                Vec3::new(5.0, 0.0, 0.0),
258                Vec3::zeros(),
259                Vec3::new(10.0 * 5.0 * DT, 0.0, 0.0),
260            ),
261        ];
262        for (p, i, desired, estimated, expected) in cases {
263            let mut c = BodyRateController::default();
264            let out = c.control(&config(p, i, 0.0), DT, desired, estimated);
265            assert!(
266                (out - expected).amax() < 1e-6,
267                "p={p} i={i} {desired:?}/{estimated:?}: {out:?}"
268            );
269        }
270    }
271
272    /// Closed loop against a constant yaw disturbance torque (`testing::settled_yaw_rate`),
273    /// commanding zero rate: the integral cancels it up to its authority
274    /// `I · max_integral`; past it, the rate settles at `−(D − I · max_integral) / P` (#192).
275    #[test]
276    fn integral_cancels_a_constant_yaw_torque_up_to_its_authority() {
277        let cfg = BodyRateControllerConfig {
278            yaw_gains: Gains {
279                p: 0.6,
280                i: 0.2,
281                d: 0.0,
282            },
283            max_integral: 1.0,
284            ..config(0.0, 0.0, 0.0)
285        };
286        // (disturbance torque, expected settled yaw rate in rad/s)
287        let cases = [
288            (0.0, 0.0),
289            (0.15, 0.0),
290            (-0.15, 0.0),
291            (0.4, -0.333_333), // #192: CCW drift
292            (-0.4, 0.333_333),
293        ];
294        for (disturbance, expected) in cases {
295            let rate = crate::testing::settled_yaw_rate(&cfg, disturbance);
296            assert!(
297                (rate - expected).abs() < 1e-3,
298                "disturbance {disturbance}: settled at {rate} rad/s, expected {expected}"
299            );
300        }
301    }
302
303    /// The output is independent of `dt` for a pure P controller (no hidden normalization).
304    #[test]
305    fn proportional_output_does_not_depend_on_dt() {
306        for dt in [0.0001, 0.004, 0.02, 0.1] {
307            let mut c = BodyRateController::default();
308            let out = c.control(
309                &config(0.15, 0.0, 0.0),
310                dt,
311                Vec3::new(1.0, 0.0, 0.0),
312                Vec3::zeros(),
313            );
314            assert_abs_diff_eq!(out.x, 0.15, epsilon = 1e-6);
315        }
316    }
317
318    /// The derivative term is `D·Δe/dt`; a falling error produces a negative contribution.
319    #[test]
320    fn derivative_term_opposes_a_falling_error() {
321        let cfg = config(0.0, 0.0, 0.003);
322        let mut c = BodyRateController::default();
323        c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
324        let steady = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
325        let falling = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.5, 0.0, 0.0));
326
327        assert_abs_diff_eq!(steady.x, 0.0, epsilon = 1e-6);
328        assert_abs_diff_eq!(falling.x, 0.003 * -0.5 / DT, epsilon = 1e-5);
329    }
330
331    /// A fresh controller has no previous error, so D alone gives nothing on the first tick.
332    #[test]
333    fn first_tick_has_no_derivative_kick() {
334        let mut c = BodyRateController::default();
335        let moments = c.control(
336            &config(0.0, 0.0, 0.01),
337            DT,
338            Vec3::new(1.0, -2.0, 0.5),
339            Vec3::zeros(),
340        );
341        assert!(moments == Vec3::zeros());
342    }
343
344    /// The accumulated error grows by `e·dt` per tick and stops at `max_integral`.
345    #[test]
346    fn integral_accumulates_and_clamps() {
347        let cfg = config(0.0, 0.1, 0.0);
348        let mut c = BodyRateController::default();
349        c.control(&cfg, 0.1, Vec3::new(2.0, -2.0, 0.0), Vec3::zeros());
350        assert!((c.integrated_error() - Vec3::new(0.2, -0.2, 0.0)).amax() < 1e-6);
351
352        for _ in 0..20 {
353            c.control(&cfg, 0.1, Vec3::new(2.0, -2.0, 0.0), Vec3::zeros());
354        }
355        assert!((c.integrated_error() - Vec3::new(1.0, -1.0, 0.0)).amax() < 1e-6);
356    }
357
358    /// Yaw uses `yaw_gains`; roll and pitch use `gains`.
359    #[test]
360    fn yaw_uses_its_own_gains() {
361        let cfg = BodyRateControllerConfig {
362            gains: Gains {
363                p: 0.15,
364                i: 0.0,
365                d: 0.0,
366            },
367            yaw_gains: Gains {
368                p: 0.5,
369                i: 0.0,
370                d: 0.0,
371            },
372            max_integral: 1.0,
373        };
374        let out = BodyRateController::default().control(
375            &cfg,
376            DT,
377            Vec3::new(1.0, 1.0, 1.0),
378            Vec3::zeros(),
379        );
380
381        assert!((out - Vec3::new(0.15, 0.15, 0.5)).amax() < 1e-6);
382    }
383
384    /// A gain change between ticks takes effect on the next tick and keeps the integral.
385    #[test]
386    fn gain_change_between_ticks_keeps_state() {
387        let mut c = BodyRateController::default();
388        c.control(
389            &config(0.0, 0.1, 0.0),
390            0.1,
391            Vec3::new(2.0, 0.0, 0.0),
392            Vec3::zeros(),
393        );
394        let integral = c.integrated_error();
395
396        let out = c.control(&config(0.0, 0.5, 0.0), 0.1, Vec3::zeros(), Vec3::zeros());
397
398        assert!(c.integrated_error() == integral);
399        assert_abs_diff_eq!(out.x, 0.5 * integral.x, epsilon = 1e-6);
400    }
401
402    /// A shrunk `max_integral` clamps the existing integral on the next tick.
403    #[test]
404    fn shrinking_max_integral_clamps_the_integral() {
405        let mut c = BodyRateController::default();
406        c.control(
407            &config(0.0, 0.1, 0.0),
408            1.0,
409            Vec3::new(0.8, 0.0, 0.0),
410            Vec3::zeros(),
411        );
412
413        let shrunk = BodyRateControllerConfig {
414            max_integral: 0.25,
415            ..config(0.0, 0.1, 0.0)
416        };
417        c.control(&shrunk, DT, Vec3::zeros(), Vec3::zeros());
418
419        assert_abs_diff_eq!(c.integrated_error().x, 0.25, epsilon = 1e-6);
420    }
421
422    /// An invalid limit fails `validate` but does not panic `control`: it acts as 0.
423    #[test]
424    fn invalid_max_integral_is_rejected_and_does_not_panic_the_tick() {
425        let invalid = BodyRateControllerConfig {
426            max_integral: -1.0,
427            ..config(0.0, 0.1, 0.0)
428        };
429        assert_eq!(invalid.validate().map_err(|e| e.field), Err("max_integral"));
430        for max_integral in [-1.0, f32::NAN] {
431            let cfg = BodyRateControllerConfig {
432                max_integral,
433                ..config(0.0, 0.1, 0.0)
434            };
435            let mut c = BodyRateController::default();
436            let out = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
437            assert!(
438                c.integrated_error() == Vec3::zeros(),
439                "max_integral {max_integral}"
440            );
441            assert!(out == Vec3::zeros(), "max_integral {max_integral}");
442        }
443    }
444
445    #[test]
446    #[should_panic(expected = "dt must be positive and finite")]
447    fn zero_dt_panics() {
448        BodyRateController::default().control(
449            &config(0.15, 0.0, 0.0),
450            0.0,
451            Vec3::zeros(),
452            Vec3::zeros(),
453        );
454    }
455
456    /// A non-finite desired or estimated rate zeroes that axis alone (#67): the other axes
457    /// match a controller that never saw it, the bad axis's integral is untouched, and its
458    /// first finite tick afterwards has no derivative kick.
459    #[test]
460    fn non_finite_rate_zeroes_only_its_axis() {
461        let nan = f32::NAN;
462        let inf = f32::INFINITY;
463        // (desired, estimated)
464        let cases = [
465            (Vec3::new(inf, 0.3, -0.2), Vec3::zeros()),
466            (Vec3::new(0.4, 0.3, -0.2), Vec3::new(0.0, nan, 0.0)),
467            (Vec3::new(0.4, 0.3, nan), Vec3::zeros()),
468            (Vec3::new(0.4, inf, 0.0), Vec3::new(0.0, inf, 0.0)), // ∞ − ∞
469            (Vec3::new(nan, nan, nan), Vec3::zeros()),
470        ];
471        let cfg = config(0.15, 0.1, 0.003);
472        let warm_up = Vec3::new(0.5, -0.4, 0.3);
473        let after_gap = Vec3::new(0.2, 0.2, 0.2);
474        for (desired, estimated) in cases {
475            let bad = (desired - estimated).map(|e| !e.is_finite());
476            let finite = |v: Vec3| v.map(|c| if c.is_finite() { c } else { 0.0 });
477            let mut c = BodyRateController::default();
478            let mut twin = BodyRateController::default();
479            // A valid tick first, so there is derivative history to go stale.
480            c.control(&cfg, DT, warm_up, Vec3::zeros());
481            twin.control(&cfg, DT, warm_up, Vec3::zeros());
482            let integral_before = c.integrated_error();
483
484            let during = c.control(&cfg, DT, desired, estimated);
485            let twin_during = twin.control(&cfg, DT, finite(desired), finite(estimated));
486            let after = c.control(&cfg, DT, after_gap, Vec3::zeros());
487            let twin_after = twin.control(&cfg, DT, after_gap, Vec3::zeros());
488
489            for axis in 0..3 {
490                let row = format!("{desired:?}/{estimated:?} axis {axis}");
491                if bad[axis] {
492                    assert!(during[axis] == 0.0, "{row}: {during:?}");
493                    // After the gap: P + I only, no derivative from the pre-gap error.
494                    let integral = integral_before[axis] + DT * after_gap[axis];
495                    let expected = 0.15 * after_gap[axis] + 0.1 * integral;
496                    assert!((after[axis] - expected).abs() < 1e-6, "{row}: {after:?}");
497                } else {
498                    assert!(during[axis] == twin_during[axis], "{row}: {during:?}");
499                    assert!(after[axis] == twin_after[axis], "{row}: {after:?}");
500                }
501            }
502        }
503    }
504}