stable_flight/controllers/body_rate.rs
1use crate::Vec3;
2
3use super::derivative::DerivativeState;
4use super::{Gains, InvalidConfig, check};
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/// Roll and pitch rate I as a share of rate P, in 1/s: the autotune's rule for every gain it sets
12/// (`tuning::autotune`). The I term holds a steady trim moment (a CG offset, a weak motor)
13/// so the vehicle doesn't tilt while the attitude loop's slow I winds. Higher: trim held
14/// sooner; the sim autotune passed every clean and delayed robustness row at 0.1–0.3 and
15/// failed most at 1.0, ArduPilot's final ratio (`AUTOTUNE_PI_RATIO_FINAL`) (#374).
16pub const RATE_I_PER_P: f32 = 0.2;
17/// Yaw rate I as a share of yaw rate P, in 1/s: the autotune's rule for the yaw I it sets. A
18/// multirotor's yaw trim is large (0.40 of the moment on QuadCopterX, #192), and after liftoff
19/// the I has to rebuild it. Higher: trim back sooner; on the sim's QuadCopterX yaw the
20/// liftoff heading is back within 2° in 4.9 s against 7.3 s at 0.2, with the same tuned P.
21/// Past 0.3 the tuned steps overshoot more: 0.05 at 0.4, past the step spec's 0.05 at 0.5
22/// (#558).
23pub const YAW_RATE_I_PER_P: f32 = 0.3;
24/// Default yaw proportional gain. Yaw authority comes only from differential prop drag, so
25/// yaw needs more gain than roll and pitch.
26const DEFAULT_YAW_P: f32 = 0.3;
27/// Default yaw integral gain, in normalized moment per rad of accumulated error.
28const DEFAULT_YAW_I: f32 = 0.1;
29/// Default roll and pitch I term limit, in normalized moment: half of full scale, ArduPilot's
30/// default rate IMAX (`AC_ATC_MULTI_RATE_RP_IMAX`). It holds a CG offset's trim whatever the
31/// I gain: limited to `i` × 1 rad of error, core's default gains held 0.03, and the sim
32/// autotune couldn't start under a 1 cm CG offset (#374). PX4's 0.3 (`MC_RR_INT_LIM`) passes
33/// the same rows.
34const DEFAULT_MAX_INTEGRAL: f32 = 0.5;
35/// Default yaw I term limit, in normalized moment: ArduPilot's default yaw IMAX
36/// (`AC_ATC_MULTI_RATE_YAW_IMAX`). A multirotor's yaw trim can be large: QuadCopterX hovers on
37/// 0.40 of yaw moment in RealFlight (#192), past PX4's 0.3 (`MC_YR_INT_LIM`).
38const DEFAULT_YAW_MAX_INTEGRAL: f32 = 0.5;
39
40/// Configures the [BodyRateController] with PID gains and operational limits.
41///
42/// Gains map rate error (rad/s) straight to a normalized moment in `[-1, 1]`: `p` is moment per
43/// rad/s, `i` per rad of accumulated error, and `d` per rad/s².
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub struct BodyRateControllerConfig {
46 /// PID gains for the roll rate.
47 pub roll_gains: Gains,
48
49 /// PID gains for the pitch rate.
50 pub pitch_gains: Gains,
51
52 /// PID gains for the yaw rate.
53 pub yaw_gains: Gains,
54
55 /// Most moment the roll and pitch I terms hold, each, in normalized moment: the trim they
56 /// can carry, and their windup limit. Like ArduPilot's rate IMAX and PX4's
57 /// `MC_RR_INT_LIM`, it doesn't depend on the I gain.
58 pub max_integral: f32,
59
60 /// Most moment the yaw I term holds, in normalized moment.
61 pub yaw_max_integral: f32,
62}
63
64impl Default for BodyRateControllerConfig {
65 fn default() -> Self {
66 let roll_pitch_gains = Gains {
67 p: DEFAULT_P,
68 i: RATE_I_PER_P * DEFAULT_P,
69 d: DEFAULT_D,
70 };
71 Self {
72 roll_gains: roll_pitch_gains,
73 pitch_gains: roll_pitch_gains,
74 yaw_gains: Gains {
75 p: DEFAULT_YAW_P,
76 i: DEFAULT_YAW_I,
77 d: 0.0,
78 },
79 max_integral: DEFAULT_MAX_INTEGRAL,
80 yaw_max_integral: DEFAULT_YAW_MAX_INTEGRAL,
81 }
82 }
83}
84
85impl BodyRateControllerConfig {
86 /// Checks the config: `max_integral` and `yaw_max_integral` must be in `[0, 1]`. The output
87 /// clips at ±1, so a larger limit would only leave the I term free to wind up; rejecting it
88 /// also catches a value saved under the old unit, rad of error (1 and 5 by default).
89 ///
90 /// # Examples
91 ///
92 /// ```
93 /// use stable_flight::controllers::BodyRateControllerConfig;
94 ///
95 /// assert!(BodyRateControllerConfig::default().validate().is_ok());
96 /// let bad = BodyRateControllerConfig { max_integral: -1.0, ..Default::default() };
97 /// assert!(bad.validate().is_err());
98 /// let rad = BodyRateControllerConfig { yaw_max_integral: 5.0, ..Default::default() };
99 /// assert!(rad.validate().is_err());
100 /// ```
101 pub fn validate(&self) -> Result<(), InvalidConfig> {
102 check_moment_limit("max_integral", self.max_integral)?;
103 check_moment_limit("yaw_max_integral", self.yaw_max_integral)
104 }
105
106 /// Gains per axis: roll, pitch, yaw.
107 fn axis_gains(&self) -> [Gains; 3] {
108 [self.roll_gains, self.pitch_gains, self.yaw_gains]
109 }
110
111 /// I term limits per axis, in normalized moment: roll, pitch, yaw.
112 fn axis_max_integrals(&self) -> [f32; 3] {
113 [self.max_integral, self.max_integral, self.yaw_max_integral]
114 }
115}
116
117/// `Ok` when an I term limit is in `[0, 1]` of normalized moment.
118fn check_moment_limit(field: &'static str, limit: f32) -> Result<(), InvalidConfig> {
119 check(field, (0.0..=1.0).contains(&limit), "in [0, 1]")
120}
121
122/// A PID-based controller for managing angular rates (roll, pitch, yaw) of a vehicle.
123///
124/// This controller uses a PID algorithm to compute corrective moments based on desired and estimated
125/// angular rates. It is designed as the innermost control loop, directly affecting motor commands.
126///
127/// It holds only state (integral and derivative history); gains and limits come from the
128/// [`BodyRateControllerConfig`] passed to each [`control`](Self::control) call, so they can
129/// change between ticks without resetting the state.
130///
131/// # Units
132/// - Time (`dt`) is in seconds.
133/// - Desired and estimated rates are expected in rad/s.
134/// - Output moments are `P·e + ∫I·e − D·ω̇`, saturated to `[-1, 1]` per axis; the mixer scales
135/// them to motor commands.
136///
137/// # The I term
138///
139/// The integral accumulates `I·e·dt`, the moment itself, as ArduPilot's `AC_PID` and PX4's
140/// `RateControl` do, and is clamped to the config's limit in moment. A change of I gain
141/// changes how fast it grows, not what it holds, so a retune doesn't bump the output; setting
142/// I to 0 drops it.
143///
144/// # D on the measured rate
145///
146/// D damps the measured rate's change (`ω̇`, the angular acceleration), not the error's, so a
147/// setpoint step adds no derivative kick: on the error, a step of `A` rad/s would kick the
148/// moment by `D·A/dt` for one tick (35·A with a designed `d` of 0.139 at 250 Hz), clipping it
149/// and showing as overshoot. Inside the loop the two are the same, so stability and the
150/// response to a disturbance don't change; only a setpoint change is followed by P and I alone.
151/// PX4's `RateControl` takes D on the measured rate too; ArduPilot's `AC_PID` takes it on the
152/// error and low-passes it (`ATC_RAT_RLL_FLTD`).
153#[derive(Clone, Debug, Default, PartialEq)]
154pub struct BodyRateController {
155 /// Roll, pitch, and yaw, each with its own PID state.
156 axes: [RateAxis; 3],
157}
158
159/// One axis of the rate loop: its I term and derivative history.
160#[derive(Clone, Copy, Debug, Default, PartialEq)]
161struct RateAxis {
162 /// The I term, `∫I·e dt`, in normalized moment.
163 integral: f32,
164
165 /// Previous measured rate for the derivative term; empty on the first tick and after a gap.
166 derivative: DerivativeState<f32>,
167}
168
169impl RateAxis {
170 /// `P·e + ∫I·e − D·ω̇` for one axis, with `e = desired − measured` and `ω̇` the measured
171 /// rate's change, saturated to `[-1, 1]`. A non-finite error gives 0 and stays out of the
172 /// integral and derivative state. A zero I gain zeroes the integral.
173 ///
174 /// While the moment is clipped, the integral may shrink but not grow: growing it can't
175 /// add moment, and it would wind up and overshoot once the clip ends (anti-windup). The
176 /// clip is this loop's own ±1; a mixer limit below it isn't seen, where ArduPilot's
177 /// `AC_PID::update_i` holds the integral on the mixer's limit flags.
178 fn step(
179 &mut self,
180 gains: Gains,
181 max_integral: f32,
182 dt: f32,
183 desired_radps: f32,
184 measured_radps: f32,
185 ) -> f32 {
186 let error_radps = desired_radps - measured_radps;
187 if !error_radps.is_finite() {
188 self.derivative.forget();
189 return 0.0;
190 }
191
192 let accel_radps2 = self.derivative.step(measured_radps, dt);
193 let pd = gains.p * error_radps - gains.d * accel_radps2;
194 if gains.i == 0.0 {
195 self.integral = 0.0;
196 }
197 let integral = clamp_symmetric(self.integral + gains.i * error_radps * dt, max_integral);
198 let clipped = (pd + integral).abs() > 1.0;
199 if !clipped || integral.abs() < self.integral.abs() {
200 self.integral = integral;
201 }
202
203 clamp_symmetric(pd + self.integral, 1.0)
204 }
205}
206
207impl BodyRateController {
208 /// Controls the angular velocity (body rates) of the vehicle using a PID controller.
209 ///
210 /// Computes the error between desired and estimated rates (both rad/s) and applies PID
211 /// control to it, per axis with `config.roll_gains`, `pitch_gains`, and `yaw_gains`.
212 ///
213 /// # Arguments
214 ///
215 /// * `config` - Gains and limits; assumed valid ([`BodyRateControllerConfig::validate`]).
216 /// An invalid limit does not panic: a negative or NaN integral limit acts as 0.
217 /// * `dt` - Time step since the last update in seconds (must be positive and finite).
218 /// * `desired_rates_radps` - Desired angular rates (roll, pitch, yaw) in rad/s.
219 /// * `estimated_rates_radps` - Current measured angular rates (roll, pitch, yaw) in rad/s.
220 ///
221 /// # Returns
222 ///
223 /// Moments (roll, pitch, yaw), each saturated to `[-1, 1]`.
224 ///
225 /// # Panics
226 ///
227 /// If `dt` is not positive and finite.
228 ///
229 /// A non-finite component in `desired_rates_radps` or `estimated_rates_radps` gives a zero
230 /// moment on that axis alone and leaves that axis's state untouched, so a bad gyro axis
231 /// doesn't take damping off the others (the input policy in `architecture.md`).
232 ///
233 /// # Examples
234 ///
235 /// ```
236 /// use stable_flight::controllers::{BodyRateController, BodyRateControllerConfig};
237 /// use stable_flight::Vec3;
238 ///
239 /// let config = BodyRateControllerConfig::default();
240 /// let mut controller = BodyRateController::default();
241 /// let dt = 0.004; // seconds; 250 Hz control loop
242 /// let desired_rates_radps = Vec3::new(0.1, 0.0, 0.05); // roll, pitch, yaw rates (rad/s)
243 /// let estimated_rates_radps = Vec3::zeros();
244 ///
245 /// let moments = controller.control(&config, dt, desired_rates_radps, estimated_rates_radps);
246 /// assert!(moments.x > 0.0 && moments.z > 0.0);
247 /// assert!(moments.iter().all(|m| (-1.0..=1.0).contains(m)));
248 /// ```
249 pub fn control(
250 &mut self,
251 config: &BodyRateControllerConfig,
252 dt: f32,
253 desired_rates_radps: Vec3,
254 estimated_rates_radps: Vec3,
255 ) -> Vec3 {
256 assert_dt(dt);
257 let gains = config.axis_gains();
258 let max_integrals = config.axis_max_integrals();
259 Vec3::from_fn(|axis, _| {
260 self.axes[axis].step(
261 gains[axis],
262 max_integrals[axis],
263 dt,
264 desired_rates_radps[axis],
265 estimated_rates_radps[axis],
266 )
267 })
268 }
269
270 /// Zeroes every axis's integral, keeping the derivative history.
271 pub(crate) fn clear_integral(&mut self) {
272 for axis in &mut self.axes {
273 axis.integral = 0.0;
274 }
275 }
276
277 /// The I term of `axis` (0 roll, 1 pitch, 2 yaw): the moment the loop holds as trim.
278 #[cfg(test)]
279 pub(crate) fn integral_term(&self, axis: usize) -> f32 {
280 self.axes[axis].integral
281 }
282
283 /// Restarts `axis` with no derivative history, keeping its integral. The other axes are
284 /// untouched.
285 pub(crate) fn hand_back(&mut self, axis: usize) {
286 self.axes[axis].derivative = DerivativeState::default();
287 }
288
289 /// The I term per axis, in normalized moment.
290 #[cfg(test)]
291 fn integral(&self) -> Vec3 {
292 Vec3::from_fn(|axis, _| self.axes[axis].integral)
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 use approx::assert_abs_diff_eq;
300 use assert2::assert;
301
302 const DT: f32 = 0.004;
303
304 /// The same gains on every axis.
305 fn config(p: f32, i: f32, d: f32) -> BodyRateControllerConfig {
306 BodyRateControllerConfig {
307 roll_gains: Gains { p, i, d },
308 pitch_gains: Gains { p, i, d },
309 yaw_gains: Gains { p, i, d },
310 max_integral: 1.0,
311 yaw_max_integral: 1.0,
312 }
313 }
314
315 /// Handing back one axis clears its derivative history and keeps its integral; the other
316 /// axes keep both.
317 #[test]
318 fn hand_back_restarts_one_axis_only() {
319 let config = config(1.0, 2.0, 0.5);
320 let mut controller = BodyRateController::default();
321 controller.control(&config, DT, Vec3::new(0.5, 0.5, 0.5), Vec3::zeros());
322 let before = controller.axes;
323
324 controller.hand_back(0);
325
326 assert!(controller.axes[0].integral == before[0].integral);
327 assert!(controller.axes[0].derivative == DerivativeState::default());
328 assert!(controller.axes[1..] == before[1..]);
329 }
330
331 /// One tick from a fresh controller is `P·e + I·e·dt` (no derivative history yet; see
332 /// `first_tick_has_no_derivative_kick`), saturated to `[-1, 1]` per axis.
333 #[test]
334 fn first_tick_output_is_saturated_p_plus_i() {
335 // (p, i, desired, estimated, expected)
336 let cases = [
337 (0.15, 0.0, Vec3::zeros(), Vec3::zeros(), Vec3::zeros()),
338 (
339 0.15,
340 0.0,
341 Vec3::new(1.0, 0.0, 0.0),
342 Vec3::zeros(),
343 Vec3::new(0.15, 0.0, 0.0),
344 ),
345 (
346 0.15,
347 0.0,
348 Vec3::new(0.0, 2.0, -2.0),
349 Vec3::zeros(),
350 Vec3::new(0.0, 0.3, -0.3),
351 ),
352 (
353 0.15,
354 0.0,
355 Vec3::new(1.0, 1.0, 1.0),
356 Vec3::new(1.0, 2.0, 0.0),
357 Vec3::new(0.0, -0.15, 0.15),
358 ),
359 (
360 0.15,
361 0.0,
362 Vec3::new(10.0, -10.0, 0.0),
363 Vec3::zeros(),
364 Vec3::new(1.0, -1.0, 0.0),
365 ),
366 (
367 0.0,
368 10.0,
369 Vec3::new(5.0, 0.0, 0.0),
370 Vec3::zeros(),
371 Vec3::new(10.0 * 5.0 * DT, 0.0, 0.0),
372 ),
373 ];
374 for (p, i, desired, estimated, expected) in cases {
375 let mut c = BodyRateController::default();
376 let out = c.control(&config(p, i, 0.0), DT, desired, estimated);
377 assert!(
378 (out - expected).amax() < 1e-6,
379 "p={p} i={i} {desired:?}/{estimated:?}: {out:?}"
380 );
381 }
382 }
383
384 /// Closed loop against a constant yaw disturbance torque (`testing::settled_yaw_rate`),
385 /// commanding zero rate: the integral cancels it up to `yaw_max_integral`; past it, the
386 /// rate settles at `−(D − yaw_max_integral) / P` (#192).
387 #[test]
388 fn integral_cancels_a_constant_yaw_torque_up_to_its_authority() {
389 let cfg = BodyRateControllerConfig {
390 yaw_gains: Gains {
391 p: 0.6,
392 i: 0.2,
393 d: 0.0,
394 },
395 yaw_max_integral: 0.2,
396 ..config(0.0, 0.0, 0.0)
397 };
398 // (disturbance torque, expected settled yaw rate in rad/s)
399 let cases = [
400 (0.0, 0.0),
401 (0.15, 0.0),
402 (-0.15, 0.0),
403 (0.4, -0.333_333), // past the authority: CCW drift (#192)
404 (-0.4, 0.333_333),
405 ];
406 for (disturbance, expected) in cases {
407 let rate = crate::testing::settled_yaw_rate(&cfg, disturbance);
408 assert!(
409 (rate - expected).abs() < 1e-3,
410 "disturbance {disturbance}: settled at {rate} rad/s, expected {expected}"
411 );
412 }
413 }
414
415 /// The output is independent of `dt` for a pure P controller (no hidden normalization).
416 #[test]
417 fn proportional_output_does_not_depend_on_dt() {
418 for dt in [0.0001, 0.004, 0.02, 0.1] {
419 let mut c = BodyRateController::default();
420 let out = c.control(
421 &config(0.15, 0.0, 0.0),
422 dt,
423 Vec3::new(1.0, 0.0, 0.0),
424 Vec3::zeros(),
425 );
426 assert_abs_diff_eq!(out.x, 0.15, epsilon = 1e-6);
427 }
428 }
429
430 /// The derivative term is `−D·Δω/dt` on the measured rate: a rising rate is damped.
431 #[test]
432 fn derivative_term_opposes_a_rising_rate() {
433 let cfg = config(0.0, 0.0, 0.003);
434 let mut c = BodyRateController::default();
435 c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
436 let steady = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
437 let rising = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.5, 0.0, 0.0));
438
439 assert_abs_diff_eq!(steady.x, 0.0, epsilon = 1e-6);
440 assert_abs_diff_eq!(rising.x, 0.003 * -0.5 / DT, epsilon = 1e-5);
441 }
442
443 /// A setpoint step on a held rate moves the moment by `P·A` alone: no `D·A/dt` kick, for
444 /// any step size or D (#373).
445 #[test]
446 fn a_setpoint_step_has_no_derivative_kick() {
447 // (step in rad/s, d): the d's span the hand tune (0.003) to a designed quad_x (0.139).
448 let rows = [
449 (1.0, 0.003),
450 (-1.0, 0.003),
451 (0.2, 0.139),
452 (1.0, 0.139),
453 (-3.0, 0.05),
454 ];
455 let p = 0.15;
456 for (step_radps, d) in rows {
457 let cfg = config(p, 0.0, d);
458 let mut c = BodyRateController::default();
459 let measured = Vec3::new(0.3, 0.3, 0.3);
460 c.control(&cfg, DT, measured, measured);
461 let stepped = measured + Vec3::repeat(step_radps);
462 let moments = c.control(&cfg, DT, stepped, measured);
463 let expected = clamp_symmetric(p * step_radps, 1.0);
464 assert!(
465 (moments - Vec3::repeat(expected)).amax() < 1e-6,
466 "step {step_radps} rad/s, d {d}: {moments:?}"
467 );
468 }
469 }
470
471 /// A fresh controller has no previous rate, so D alone gives nothing on the first tick.
472 #[test]
473 fn first_tick_has_no_derivative_kick() {
474 let mut c = BodyRateController::default();
475 let moments = c.control(
476 &config(0.0, 0.0, 0.01),
477 DT,
478 Vec3::new(1.0, -2.0, 0.5),
479 Vec3::zeros(),
480 );
481 assert!(moments == Vec3::zeros());
482 }
483
484 /// The I term grows by `I·e·dt` per tick and stops at the axis's limit, in moment:
485 /// `max_integral` for roll and pitch, `yaw_max_integral` for yaw.
486 #[test]
487 fn integral_accumulates_and_clamps_per_axis() {
488 let cfg = BodyRateControllerConfig {
489 max_integral: 0.1,
490 yaw_max_integral: 0.15,
491 ..config(0.0, 0.1, 0.0)
492 };
493 let error = Vec3::new(2.0, -2.0, 2.0);
494 let mut c = BodyRateController::default();
495 c.control(&cfg, 0.1, error, Vec3::zeros());
496 assert!((c.integral() - Vec3::new(0.02, -0.02, 0.02)).amax() < 1e-6);
497
498 for _ in 0..20 {
499 c.control(&cfg, 0.1, error, Vec3::zeros());
500 }
501 assert!((c.integral() - Vec3::new(0.1, -0.1, 0.15)).amax() < 1e-6);
502 }
503
504 /// A limit set to the I gain × the old limit in rad of error flies as the old law did,
505 /// windup and clipping included: the conversion the airframes took (#374).
506 #[test]
507 fn a_limit_of_i_times_the_rad_limit_flies_as_the_rad_limit_did() {
508 /// The rate loop before #374, one axis: the error integrated in rad and clamped there.
509 fn rad_law(
510 integrated_error: &mut f32,
511 gains: Gains,
512 limit_rad: f32,
513 dt: f32,
514 e: f32,
515 ) -> f32 {
516 let pd = gains.p * e;
517 let integral = clamp_symmetric(*integrated_error + dt * e, limit_rad);
518 let clipped = (pd + gains.i * integral).abs() > 1.0;
519 if !clipped || integral.abs() < integrated_error.abs() {
520 *integrated_error = integral;
521 }
522 clamp_symmetric(pd + gains.i * *integrated_error, 1.0)
523 }
524 // (airframe, roll I, the old limit in rad): the converted RealFlight and X-Plane sets.
525 let rows = [
526 (
527 "eXplora pitch",
528 Gains {
529 p: 1.4217,
530 i: 0.2844,
531 d: 0.0,
532 },
533 1.0,
534 ),
535 (
536 "Cobra roll",
537 Gains {
538 p: 0.4847,
539 i: 0.0969,
540 d: 0.0,
541 },
542 3.0,
543 ),
544 (
545 "Alia",
546 Gains {
547 p: 1.52,
548 i: 0.2,
549 d: 0.0,
550 },
551 1.0,
552 ),
553 ];
554 // A trim held long enough to reach the limit, a clipping push, then release.
555 let errors = (0..2000).map(|tick| match tick {
556 0..1000 => 0.8,
557 1000..1100 => 3.0,
558 1100..1500 => -0.5,
559 _ => 0.05,
560 });
561 for (name, gains, limit_rad) in rows {
562 let cfg = BodyRateControllerConfig {
563 roll_gains: gains,
564 max_integral: gains.i * limit_rad,
565 ..config(0.0, 0.0, 0.0)
566 };
567 let mut c = BodyRateController::default();
568 let mut integrated_error = 0.0;
569 for (tick, e) in errors.clone().enumerate() {
570 let new = c.control(&cfg, DT, Vec3::new(e, 0.0, 0.0), Vec3::zeros()).x;
571 let old = rad_law(&mut integrated_error, gains, limit_rad, DT, e);
572 assert!(
573 (new - old).abs() < 1e-5,
574 "{name} tick {tick}: {new} vs {old}"
575 );
576 }
577 }
578 }
579
580 /// The limit is in moment whatever the I gain: a small I holds as much trim as a large
581 /// one, given time (#374).
582 #[test]
583 fn integral_limit_does_not_scale_with_the_i_gain() {
584 for i in [0.03, 0.3, 3.0] {
585 let cfg = config(0.0, i, 0.0);
586 let mut c = BodyRateController::default();
587 for _ in 0..10_000 {
588 c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
589 }
590 assert_abs_diff_eq!(c.integral().x, cfg.max_integral, epsilon = 1e-6);
591 }
592 }
593
594 /// While the moment is clipped, the integral shrinks but doesn't grow; unclipped, it
595 /// grows as usual.
596 #[test]
597 fn clipped_moment_stops_the_integral_growing() {
598 let start = 0.5;
599 // (case, p, error, expected integral after one 0.1 s tick at I 0.1)
600 let rows = [
601 ("unclipped grows", 0.1, 1.0, start + 0.01),
602 ("clipped toward the error holds", 2.0, 1.0, start),
603 (
604 "clipped against the integral shrinks",
605 2.0,
606 -1.0,
607 start - 0.01,
608 ),
609 (
610 "clipped, error crossing zero shrinks",
611 2.0,
612 -0.6,
613 start - 0.006,
614 ),
615 ];
616 for (case, p, error, expected) in rows {
617 let cfg = config(p, 0.1, 0.0);
618 let mut c = BodyRateController::default();
619 c.axes[0].integral = start;
620 let out = c.control(&cfg, 0.1, Vec3::new(error, 0.0, 0.0), Vec3::zeros());
621 let integral = c.integral().x;
622 assert!((integral - expected).abs() < 1e-6, "{case}: {integral}");
623 assert!(out.x.abs() <= 1.0, "{case}");
624 }
625 }
626
627 /// Each axis uses its own gains: roll `roll_gains`, pitch `pitch_gains`, yaw `yaw_gains`.
628 #[test]
629 fn each_axis_uses_its_own_gains() {
630 let p_only = |p| Gains { p, i: 0.0, d: 0.0 };
631 let cfg = BodyRateControllerConfig {
632 roll_gains: p_only(0.15),
633 pitch_gains: p_only(0.25),
634 yaw_gains: p_only(0.5),
635 max_integral: 1.0,
636 yaw_max_integral: 1.0,
637 };
638 let out = BodyRateController::default().control(
639 &cfg,
640 DT,
641 Vec3::new(1.0, 1.0, 1.0),
642 Vec3::zeros(),
643 );
644
645 assert!((out - Vec3::new(0.15, 0.25, 0.5)).amax() < 1e-6);
646 }
647
648 /// An I gain change between ticks keeps the I term, so the output doesn't bump; a zero I
649 /// gain drops it, and it restarts from zero.
650 #[test]
651 fn i_gain_change_keeps_the_i_term_or_drops_it_at_zero() {
652 // (case, new I, expected I term after a tick at zero error)
653 let rows = [
654 ("raised", 0.5, 0.02),
655 ("lowered", 0.01, 0.02),
656 ("zeroed", 0.0, 0.0),
657 ];
658 for (case, new_i, expected) in rows {
659 let mut c = BodyRateController::default();
660 c.control(
661 &config(0.0, 0.1, 0.0),
662 0.1,
663 Vec3::new(2.0, 0.0, 0.0),
664 Vec3::zeros(),
665 );
666
667 let out = c.control(&config(0.0, new_i, 0.0), 0.1, Vec3::zeros(), Vec3::zeros());
668
669 assert!((c.integral().x - expected).abs() < 1e-6, "{case}");
670 assert!((out.x - expected).abs() < 1e-6, "{case}");
671 }
672 }
673
674 /// A shrunk `max_integral` clamps the existing integral on the next tick.
675 #[test]
676 fn shrinking_max_integral_clamps_the_integral() {
677 let mut c = BodyRateController::default();
678 c.control(
679 &config(0.0, 0.1, 0.0),
680 1.0,
681 Vec3::new(8.0, 0.0, 0.0),
682 Vec3::zeros(),
683 );
684
685 let shrunk = BodyRateControllerConfig {
686 max_integral: 0.25,
687 ..config(0.0, 0.1, 0.0)
688 };
689 c.control(&shrunk, DT, Vec3::zeros(), Vec3::zeros());
690
691 assert_abs_diff_eq!(c.integral().x, 0.25, epsilon = 1e-6);
692 }
693
694 /// An invalid limit fails `validate` but does not panic `control`: a negative or NaN one
695 /// acts as 0 on its axes. Past 1 (a value in the old rad unit) fails too.
696 #[test]
697 fn invalid_max_integral_is_rejected_and_does_not_panic_the_tick() {
698 type SetLimit = fn(&mut BodyRateControllerConfig, f32);
699 // (field, how to set it, the error axis it limits)
700 let rows: [(&str, SetLimit, Vec3); 2] = [
701 ("max_integral", |c, v| c.max_integral = v, Vec3::x()),
702 ("yaw_max_integral", |c, v| c.yaw_max_integral = v, Vec3::z()),
703 ];
704 for (field, set, error) in rows {
705 for limit in [5.0, 1.01] {
706 let mut cfg = config(0.0, 0.1, 0.0);
707 set(&mut cfg, limit);
708 assert_eq!(cfg.validate().map_err(|e| e.field), Err(field));
709 }
710 for limit in [-1.0, f32::NAN] {
711 let mut cfg = config(0.0, 0.1, 0.0);
712 set(&mut cfg, limit);
713 assert_eq!(cfg.validate().map_err(|e| e.field), Err(field));
714 let mut c = BodyRateController::default();
715 let out = c.control(&cfg, DT, error, Vec3::zeros());
716 assert!(c.integral() == Vec3::zeros(), "{field} {limit}");
717 assert!(out == Vec3::zeros(), "{field} {limit}");
718 }
719 }
720 }
721
722 #[test]
723 #[should_panic(expected = "dt must be positive and finite")]
724 fn zero_dt_panics() {
725 BodyRateController::default().control(
726 &config(0.15, 0.0, 0.0),
727 0.0,
728 Vec3::zeros(),
729 Vec3::zeros(),
730 );
731 }
732
733 /// A non-finite desired or estimated rate zeroes that axis alone: the other axes
734 /// match a controller that never saw it, the bad axis's integral is untouched, and its
735 /// first finite tick afterwards has no derivative kick.
736 #[test]
737 fn non_finite_rate_zeroes_only_its_axis() {
738 let nan = f32::NAN;
739 let inf = f32::INFINITY;
740 // (desired, estimated)
741 let cases = [
742 (Vec3::new(inf, 0.3, -0.2), Vec3::zeros()),
743 (Vec3::new(0.4, 0.3, -0.2), Vec3::new(0.0, nan, 0.0)),
744 (Vec3::new(0.4, 0.3, nan), Vec3::zeros()),
745 (Vec3::new(0.4, inf, 0.0), Vec3::new(0.0, inf, 0.0)), // ∞ − ∞
746 (Vec3::new(nan, nan, nan), Vec3::zeros()),
747 ];
748 let cfg = config(0.15, 0.1, 0.003);
749 let warm_up = Vec3::new(0.5, -0.4, 0.3);
750 let after_gap = Vec3::new(0.2, 0.2, 0.2);
751 for (desired, estimated) in cases {
752 let bad = (desired - estimated).map(|e| !e.is_finite());
753 let finite = |v: Vec3| v.map(|c| if c.is_finite() { c } else { 0.0 });
754 let mut c = BodyRateController::default();
755 let mut twin = BodyRateController::default();
756 // A valid tick first, so there is derivative history to go stale.
757 c.control(&cfg, DT, warm_up, Vec3::zeros());
758 twin.control(&cfg, DT, warm_up, Vec3::zeros());
759 let integral_before = c.integral();
760
761 let during = c.control(&cfg, DT, desired, estimated);
762 let twin_during = twin.control(&cfg, DT, finite(desired), finite(estimated));
763 let after = c.control(&cfg, DT, after_gap, Vec3::zeros());
764 let twin_after = twin.control(&cfg, DT, after_gap, Vec3::zeros());
765
766 for axis in 0..3 {
767 let row = format!("{desired:?}/{estimated:?} axis {axis}");
768 if bad[axis] {
769 assert!(during[axis] == 0.0, "{row}: {during:?}");
770 // After the gap: P + I only, no derivative from the pre-gap error.
771 let integral = integral_before[axis] + 0.1 * after_gap[axis] * DT;
772 let expected = 0.15 * after_gap[axis] + integral;
773 assert!((after[axis] - expected).abs() < 1e-6, "{row}: {after:?}");
774 } else {
775 assert!(during[axis] == twin_during[axis], "{row}: {during:?}");
776 assert!(after[axis] == twin_after[axis], "{row}: {after:?}");
777 }
778 }
779 }
780 }
781}