Skip to main content

stable_flight/controllers/
yaw.rs

1use crate::controllers::derivative::DerivativeState;
2use crate::controllers::{Gains, InvalidConfig, check_limit, rescale_integral};
3use crate::math::{assert_dt, clamp_symmetric, wrap_angle};
4
5/// Configures the yaw controller with PID gains and operational limits.
6///
7/// This structure defines the control parameters that determine how the yaw controller
8/// responds to heading errors, including responsiveness, stability, and maximum rates.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct YawControllerConfig {
11    /// PID gains that determine controller responsiveness.
12    ///
13    /// * `p` - Proportional gain: controls response strength relative to current error.
14    /// * `i` - Integral gain: eliminates steady-state errors over time.
15    /// * `d` - Derivative gain: provides damping to reduce overshoot and oscillation.
16    pub gains: Gains,
17
18    /// Maximum absolute value of the integrated heading error, in rad·s.
19    ///
20    /// Prevents integral windup by limiting accumulated error, which
21    /// could otherwise cause significant overshoot and control instability.
22    pub max_integral: f32,
23
24    /// Maximum angular rate in radians/second for yaw.
25    ///
26    /// Limits the output commands to physically achievable rates and
27    /// prevents excessive control demands that could destabilize the system.
28    pub max_rate_radps: f32,
29}
30
31impl Default for YawControllerConfig {
32    fn default() -> Self {
33        Self {
34            // Heading hold, flight-checked on RealFlight's QuadCopterX (#62).
35            gains: Gains {
36                p: 2.5,
37                i: 0.0,
38                d: 0.06,
39            },
40            max_integral: 100.0, // Arbitrary limit
41            max_rate_radps: 2.0, // 2 rad/s (~114°/s) for yaw
42        }
43    }
44}
45
46impl YawControllerConfig {
47    /// Checks the config: `max_integral` and `max_rate_radps` must be non-negative and finite.
48    ///
49    /// # Examples
50    ///
51    /// ```
52    /// use stable_flight::controllers::YawControllerConfig;
53    ///
54    /// assert!(YawControllerConfig::default().validate().is_ok());
55    /// let bad = YawControllerConfig { max_rate_radps: f32::NAN, ..Default::default() };
56    /// assert!(bad.validate().is_err());
57    /// ```
58    pub fn validate(&self) -> Result<(), InvalidConfig> {
59        check_limit("max_integral", self.max_integral)?;
60        check_limit("max_rate_radps", self.max_rate_radps)
61    }
62}
63
64/// Yaw controller that maintains a desired heading using PID control.
65///
66/// This controller:
67/// * Takes desired and actual heading measurements
68/// * Calculates the shortest path error accounting for angle wrapping
69/// * Applies PID control to generate appropriate yaw rate commands
70/// * Incorporates anti-windup protection and output limiting
71///
72/// It holds only state (integral and derivative history); gains and limits come from the
73/// [`YawControllerConfig`] passed to each [`control`](Self::control) call, so they can change
74/// between ticks without resetting the state.
75#[derive(Clone, Debug, Default, PartialEq)]
76pub struct YawController {
77    /// Previous error for the derivative term; empty on the first tick and after a gap.
78    derivative: DerivativeState<f32>,
79    integrated_error: f32,
80}
81
82impl YawController {
83    /// Calculates desired yaw rate based on current and target headings.
84    ///
85    /// This implementation:
86    /// 1. Calculates the shortest-path heading error
87    /// 2. Updates the integral term with anti-windup protection
88    /// 3. Applies the PID formula
89    /// 5. Limits the output rate to configured maximum values
90    ///
91    /// # Arguments
92    ///
93    /// * `config` - Gains and limits; assumed valid ([`YawControllerConfig::validate`]). An
94    ///   invalid limit does not panic: a negative or NaN limit acts as 0.
95    /// * `dt` - Time step since the last update in seconds (must be positive and finite).
96    /// * `desired_yaw_rad` - Target yaw angle in radians. Any finite value is accepted; the
97    ///   error is wrapped to the shortest path, so `desired_yaw_rad` and `desired_yaw_rad + 2πk` are
98    ///   equivalent. A non-finite target (or estimate) yields a zero rate and leaves the
99    ///   controller state untouched.
100    /// * `estimated_yaw_rad` - Current measured yaw angle in radians.
101    ///
102    /// # Returns
103    ///
104    /// Desired yaw rate in rad/s, limited to configured maximum rates.
105    ///
106    /// # Panics
107    ///
108    /// If `dt` is not positive and finite.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use std::f32::consts::PI;
114    /// use stable_flight::controllers::{YawController, YawControllerConfig};
115    ///
116    /// let config = YawControllerConfig::default();
117    /// let mut controller = YawController::default();
118    /// let dt = 0.02;
119    /// let desired_yaw_rad = PI / 4.0;  // 45 degrees
120    /// let current_yaw_rad = 0.0;       // 0 degrees
121    ///
122    /// let yaw_rate = controller.control(&config, dt, desired_yaw_rad, current_yaw_rad);
123    /// // Returns a rate command to turn toward the desired heading
124    /// ```
125    pub fn control(
126        &mut self,
127        config: &YawControllerConfig,
128        dt: f32,
129        desired_yaw_rad: f32,
130        estimated_yaw_rad: f32,
131    ) -> f32 {
132        let error = angle_diff(desired_yaw_rad, estimated_yaw_rad); // Use a helper to handle angle wrapping
133        self.control_error(config, dt, error, false)
134    }
135
136    /// The PID of [`control`](Self::control) on a yaw error already taken (radians, the short
137    /// way round): for a caller that measures the error itself, e.g. from quaternions. The
138    /// output is clamped to `max_rate_radps`; a non-finite error gives zero. With
139    /// `hold_integral` the integral stays as it is this tick instead of adding the error.
140    ///
141    /// # Panics
142    ///
143    /// If `dt` is not positive and finite.
144    pub(crate) fn control_error(
145        &mut self,
146        config: &YawControllerConfig,
147        dt: f32,
148        error: f32,
149        hold_integral: bool,
150    ) -> f32 {
151        assert_dt(dt);
152
153        let gains = &config.gains;
154
155        if !error.is_finite() {
156            // Hold (no yaw rate) rather than letting NaN into the integral and derivative
157            // history, where it would stick; clamping passes NaN through. Forget the previous
158            // error too, so the first valid tick after the gap has no derivative kick.
159            self.derivative.forget();
160            return 0.0;
161        }
162        let error_derivative = self.derivative.step(error, dt);
163
164        if !hold_integral {
165            self.integrated_error =
166                clamp_symmetric(self.integrated_error + dt * error, config.max_integral);
167        }
168
169        let yaw_rate =
170            gains.p * error + gains.i * self.integrated_error + gains.d * error_derivative;
171
172        clamp_symmetric(yaw_rate, config.max_rate_radps)
173    }
174
175    /// The integrated heading error, in rad·s.
176    #[cfg(test)]
177    pub(crate) fn integral(&self) -> f32 {
178        self.integrated_error
179    }
180
181    /// Zeroes the integral, keeping the derivative history.
182    pub(crate) fn clear_integral(&mut self) {
183        self.integrated_error = 0.0;
184    }
185
186    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
187    /// tick's I term picks up where the last left off (`rescale_integral`).
188    pub(crate) fn rescale_integral(
189        &mut self,
190        old: &YawControllerConfig,
191        new: &YawControllerConfig,
192    ) {
193        self.integrated_error = rescale_integral(self.integrated_error, old.gains.i, new.gains.i);
194    }
195
196    /// Restarts with no derivative history, keeping the integral.
197    pub(crate) fn hand_back(&mut self) {
198        self.derivative = DerivativeState::default();
199    }
200}
201
202/// The shortest-path yaw error from `current_yaw` to `desired_yaw`, in [-π, π).
203///
204/// # Arguments
205///
206/// * `desired_yaw` - Desired yaw angle in radians.
207/// * `current_yaw` - Current yaw angle in radians.
208///
209/// # Returns
210///
211/// The shortest-path yaw error in radians, in [-π, π) (see [`wrap_angle`]).
212pub(crate) fn angle_diff(desired_yaw: f32, current_yaw: f32) -> f32 {
213    wrap_angle(desired_yaw - current_yaw)
214}
215
216#[cfg(test)]
217mod tests {
218
219    use std::f32::consts::PI;
220
221    use approx::assert_relative_eq;
222
223    use crate::controllers::Gains;
224
225    use super::*;
226
227    const EPSILON: f32 = 1e-5;
228
229    /// Handing back clears the derivative history and keeps the integral.
230    #[test]
231    fn hand_back_keeps_the_integral() {
232        let config = YawControllerConfig {
233            gains: Gains {
234                p: 1.0,
235                i: 2.0,
236                d: 0.5,
237            },
238            ..p_only_config(1.0, 10.0)
239        };
240        let mut controller = YawController::default();
241        controller.control_error(&config, 0.1, 0.5, false);
242        let integral = controller.integrated_error;
243
244        controller.hand_back();
245
246        assert_eq!(controller.integrated_error, integral);
247        assert_eq!(controller.derivative, DerivativeState::default());
248    }
249
250    // Helper functions for test setup
251
252    /// A config with only proportional gain.
253    fn p_only_config(p_gain: f32, max_rate_radps: f32) -> YawControllerConfig {
254        YawControllerConfig {
255            gains: Gains {
256                p: p_gain,
257                i: 0.0,
258                d: 0.0,
259            },
260            max_integral: 10.0,
261            max_rate_radps,
262        }
263    }
264
265    /// A config with only integral gain.
266    fn i_only_config(i_gain: f32, max_integral: f32, max_rate_radps: f32) -> YawControllerConfig {
267        YawControllerConfig {
268            gains: Gains {
269                p: 0.0,
270                i: i_gain,
271                d: 0.0,
272            },
273            max_integral,
274            max_rate_radps,
275        }
276    }
277
278    /// A config with only derivative gain.
279    fn d_only_config(d_gain: f32, max_rate_radps: f32) -> YawControllerConfig {
280        YawControllerConfig {
281            gains: Gains {
282                p: 0.0,
283                i: 0.0,
284                d: d_gain,
285            },
286            max_integral: 10.0,
287            max_rate_radps,
288        }
289    }
290
291    /// Tests that the default controller configuration has expected values.
292    #[test]
293    fn test_default_config() {
294        let config = YawControllerConfig::default();
295
296        assert_relative_eq!(config.gains.p, 2.5, epsilon = EPSILON, max_relative = 1e-3);
297        assert_relative_eq!(config.gains.i, 0.0, epsilon = EPSILON, max_relative = 1e-3);
298        assert_relative_eq!(config.gains.d, 0.06, epsilon = EPSILON, max_relative = 1e-3);
299        assert_relative_eq!(
300            config.max_integral,
301            100.0,
302            epsilon = EPSILON,
303            max_relative = 1e-3
304        );
305        assert_relative_eq!(
306            config.max_rate_radps,
307            2.0,
308            epsilon = EPSILON,
309            max_relative = 1e-3
310        );
311    }
312
313    #[test]
314    fn default_is_zeroed_state() {
315        assert_eq!(
316            YawController::default(),
317            YawController {
318                derivative: DerivativeState::default(),
319                integrated_error: 0.0,
320            }
321        );
322    }
323
324    /// Tests that the proportional control term works correctly in isolation.
325    #[test]
326    fn test_proportional_control() {
327        // Test that the proportional term works correctly
328        let config = p_only_config(2.0, 5.0);
329        let mut controller = YawController::default();
330
331        // Simple case: 0.5 rad error should result in rate = 2.0 * 0.5 = 1.0 rad/s
332        let dt = 0.01;
333        let desired_yaw = 0.5;
334        let estimated_yaw = 0.0;
335
336        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
337        assert_relative_eq!(
338            rate,
339            1.0,
340            epsilon = EPSILON,
341            max_relative = 1e-3,
342            max_relative = 1e-3
343        );
344
345        // Test with negative error
346        let rate = controller.control(&config, dt, 0.0, 0.5);
347        assert_relative_eq!(rate, -1.0, epsilon = EPSILON, max_relative = 1e-3);
348    }
349
350    /// Tests that the integral control term accumulates correctly and respects limits.
351    #[test]
352    fn test_integral_control() {
353        // Test that the integral term accumulates and affects output
354        let config = i_only_config(1.0, 10.0, 5.0);
355        let mut controller = YawController::default();
356
357        // Apply constant error for several iterations
358        let dt = 1.0; // 1 second for easy calculation
359        let desired_yaw = 0.5;
360        let estimated_yaw = 0.0;
361
362        // First iteration: integral = 0.5 * 1.0 = 0.5
363        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
364        assert_relative_eq!(rate, 0.5, epsilon = EPSILON, max_relative = 1e-3);
365
366        // Second iteration: integral = 0.5 + 0.5 * 1.0 = 1.0
367        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
368        assert_relative_eq!(rate, 1.0, epsilon = EPSILON, max_relative = 1e-3);
369
370        // Test integral clamping
371        let config = i_only_config(1.0, 1.5, 5.0);
372        let mut controller = YawController::default();
373
374        // Accumulate for 3 seconds to exceed max_integral
375        controller.control(&config, dt, desired_yaw, estimated_yaw); // 0.5
376        controller.control(&config, dt, desired_yaw, estimated_yaw); // 1.0
377        controller.control(&config, dt, desired_yaw, estimated_yaw); // 1.5
378        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
379
380        // Should be clamped at max_integral * i_gain = 1.5
381        assert_relative_eq!(rate, 1.5, epsilon = EPSILON, max_relative = 1e-3);
382    }
383
384    /// Tests that the derivative control term responds correctly to error changes.
385    #[test]
386    fn test_derivative_control() {
387        // Test that the derivative term works correctly
388        let config = d_only_config(2.0, 5.0);
389        let mut controller = YawController::default();
390
391        let dt = 1.0; // 1 second for easy calculation
392
393        // First call - establishes baseline error
394        let rate = controller.control(&config, dt, 0.5, 0.0);
395        assert_relative_eq!(
396            rate,
397            0.0,
398            epsilon = EPSILON,
399            max_relative = 1e-3,
400            max_relative = 1e-3
401        );
402
403        // Second call - error unchanged, derivative should be zero
404        let rate = controller.control(&config, dt, 0.5, 0.0);
405        assert_relative_eq!(rate, 0.0, epsilon = EPSILON, max_relative = 1e-3);
406
407        // Error increasing by 0.1 rad/s
408        let rate = controller.control(&config, dt, 0.6, 0.0);
409        assert_relative_eq!(rate, 0.2, epsilon = EPSILON, max_relative = 1e-3);
410
411        // Error decreasing by 0.2 rad/s
412        let rate = controller.control(&config, dt, 0.4, 0.0);
413        assert_relative_eq!(rate, -0.4, epsilon = EPSILON, max_relative = 1e-3);
414    }
415
416    /// Tests all PID components working together with detailed calculation.
417    #[test]
418    fn test_pid_combined() {
419        // Test all PID components working together
420        let config = YawControllerConfig {
421            gains: Gains {
422                p: 1.0,
423                i: 0.5,
424                d: 0.2,
425            },
426            max_integral: 10.0,
427            max_rate_radps: 5.0,
428        };
429
430        let mut controller = YawController::default();
431
432        let dt = 1.0;
433
434        // First call:
435        // - P term = 1.0 * 0.5 = 0.5
436        // - I term = 0.5 * (0.5 * 1.0) = 0.25
437        // - D term = 0 (no previous error)
438        // Total = 0.5 + 0.25 + 0 = 0.75
439        let rate = controller.control(&config, dt, 0.5, 0.0);
440        assert_relative_eq!(rate, 0.75, epsilon = EPSILON, max_relative = 1e-3);
441
442        // Second call with same error:
443        // - P term = 1.0 * 0.5 = 0.5
444        // - I term = 0.5 * (0.5 + 0.5) = 0.5
445        // - D term = 0.2 * (0.5 - 0.5) / 1.0 = 0
446        // Total = 0.5 + 0.5 + 0 = 1.0
447        let rate = controller.control(&config, dt, 0.5, 0.0);
448        assert_relative_eq!(rate, 1.0, epsilon = EPSILON, max_relative = 1e-3);
449
450        // Third call with increased error:
451        // - P term = 1.0 * 0.6 = 0.6
452        // - I term = 0.5 * (0.5 + 0.5 + 0.6) = 0.8
453        // - D term = 0.2 * (0.6 - 0.5) / 1.0 = 0.02
454        // Total = 0.6 + 0.8 + 0.02 = 1.42
455        let rate = controller.control(&config, dt, 0.6, 0.0);
456        assert_relative_eq!(rate, 1.42, epsilon = EPSILON, max_relative = 1e-3);
457    }
458
459    /// Tests that the controller handles varying time steps correctly.
460    #[test]
461    fn test_varying_time_steps() {
462        let config = YawControllerConfig {
463            gains: Gains {
464                p: 0.0,
465                i: 1.0,
466                d: 0.0,
467            },
468            max_integral: 10.0,
469            max_rate_radps: 5.0,
470        };
471
472        let mut controller = YawController::default();
473
474        // Control with a 1-second time step
475        let rate_1s = controller.control(&config, 1.0, 0.5, 0.0);
476        assert_relative_eq!(rate_1s, 0.5, epsilon = EPSILON, max_relative = 1e-3);
477
478        // Next control with a 0.5-second time step should accumulate half as much
479        let rate_05s = controller.control(&config, 0.5, 0.5, 0.0);
480        assert_relative_eq!(
481            rate_05s,
482            0.5 + 0.25, // Previous 0.5 plus new 0.5*0.5
483            epsilon = EPSILON,
484            max_relative = 1e-3
485        );
486
487        // Next control with a 0.25-second time step
488        let rate_025s = controller.control(&config, 0.25, 0.5, 0.0);
489        assert_relative_eq!(
490            rate_025s,
491            0.5 + 0.25 + 0.125, // Plus new 0.5*0.25
492            epsilon = EPSILON,
493            max_relative = 1e-3
494        );
495    }
496
497    /// Tests controller behavior with very small time steps.
498    #[test]
499    fn test_small_time_steps() {
500        let config = YawControllerConfig {
501            gains: Gains {
502                p: 1.0,
503                i: 1.0,
504                d: 1.0,
505            },
506            max_integral: 10.0,
507            max_rate_radps: 5.0,
508        };
509
510        let mut controller = YawController::default();
511
512        // Use a very small time step
513        let dt = 0.000001; // 1 microsecond
514        let error = 0.5;
515        let rate = controller.control(&config, dt, error, 0.0);
516
517        // With a tiny dt:
518        // - P term = 1.0 * 0.5 = 0.5
519        // - I term = 1.0 * 0.5 * 1e-6 ≈ 0.0000005 (effectively 0)
520        // - D term = undefined (first call)
521        assert_relative_eq!(
522            rate,
523            0.5, // Only P term is significant
524            epsilon = EPSILON,
525            max_relative = 1e-3
526        );
527
528        // Second call with same error should still have negligible I term
529        let rate = controller.control(&config, dt, error, 0.0);
530        assert_relative_eq!(
531            rate,
532            0.5, // P term only, I term still tiny
533            epsilon = EPSILON,
534            max_relative = 1e-3
535        );
536    }
537
538    /// Tests that angle wrapping is handled correctly at ±π boundaries.
539    #[test]
540    fn test_angle_wrapping() {
541        // Test angle wrapping when crossing the ±π boundary
542        let config = p_only_config(1.0, 5.0);
543        let mut controller = YawController::default();
544
545        let dt = 0.01;
546
547        // Test case: desired = 175°, current = -175°
548        // Shortest path is -10° (not +350°)
549        let desired_yaw = 175.0 * PI / 180.0;
550        let estimated_yaw = -175.0 * PI / 180.0;
551
552        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
553        let expected_rate = -10.0 * PI / 180.0; // -10 degrees converted to radians
554        assert_relative_eq!(rate, expected_rate, epsilon = EPSILON, max_relative = 1e-3);
555
556        // Test case: desired = -175°, current = 175°
557        // Shortest path is +10° (not -350°)
558        let desired_yaw = -175.0 * PI / 180.0;
559        let estimated_yaw = 175.0 * PI / 180.0;
560
561        let rate = controller.control(&config, dt, desired_yaw, estimated_yaw);
562        let expected_rate = 10.0 * PI / 180.0; // 10 degrees converted to radians
563        assert_relative_eq!(rate, expected_rate, epsilon = EPSILON, max_relative = 1e-3);
564    }
565
566    /// Directly tests the angle_diff helper function with various inputs.
567    #[test]
568    fn angle_diff_is_the_shortest_signed_path() {
569        let deg = PI / 180.0;
570        // (desired, current, expected error)
571        let cases = [
572            (0.5, 0.0, 0.5),                        // no wrapping needed
573            (PI + 0.1, -PI - 0.1, 0.2),             // wraps across ±π
574            (350.0 * deg, 10.0 * deg, -20.0 * deg), // turn left through north
575            (10.0 * deg, 350.0 * deg, 20.0 * deg),  // turn right through north
576            (PI, -PI, 0.0),                         // same heading
577            (0.0, 2.0 * PI, 0.0),                   // same heading, one turn apart
578            (5.0, 5.0 - 2.0 * PI, 0.0),             // [0, 2π) heading vs its [-π, π) form
579        ];
580        for (desired, current, expected) in cases {
581            assert_relative_eq!(
582                angle_diff(desired, current),
583                expected,
584                epsilon = EPSILON,
585                max_relative = 1e-3
586            );
587        }
588    }
589
590    #[test]
591    fn test_valid_inputs() {
592        let config = YawControllerConfig::default();
593        let mut controller = YawController::default();
594        let dt = 0.01;
595
596        // Valid inputs should not panic
597        let _ = controller.control(&config, dt, 0.0, 0.0);
598        let _ = controller.control(&config, dt, PI, -PI);
599        let _ = controller.control(&config, dt, 2.0 * PI, 0.0);
600    }
601
602    #[test]
603    #[should_panic(expected = "dt must be positive and finite")]
604    fn zero_dt_panics() {
605        let config = YawControllerConfig::default();
606        let mut controller = YawController::default();
607        let dt = 0.0;
608        let _ = controller.control(&config, dt, 0.0, 0.0);
609    }
610
611    #[test]
612    fn any_finite_target_is_equivalent_to_its_wrapped_heading() {
613        // (target, equivalent target within [-π, π))
614        let cases = [
615            (3.0 * PI, -PI),
616            (10.0 * PI + 0.5, 0.5),
617            (-7.0 * PI / 2.0, PI / 2.0),
618            (1000.0, wrap_angle(1000.0)),
619        ];
620        let config = YawControllerConfig::default();
621        for (target, equivalent) in cases {
622            let rate = YawController::default().control(&config, 0.01, target, 0.2);
623            let expected = YawController::default().control(&config, 0.01, equivalent, 0.2);
624            assert_relative_eq!(rate, expected, epsilon = 1e-3);
625        }
626    }
627
628    #[test]
629    fn non_finite_target_holds_and_does_not_poison_later_ticks() {
630        let config = YawControllerConfig::default();
631        let mut controller = YawController::default();
632        for target in [f32::NAN, f32::INFINITY] {
633            assert!(controller.control(&config, 0.01, target, 0.2) == 0.0);
634        }
635        let after = controller.control(&config, 0.01, 1.0, 0.2);
636        let fresh = YawController::default().control(&config, 0.01, 1.0, 0.2);
637        assert_relative_eq!(after, fresh);
638    }
639
640    #[test]
641    fn nan_gap_does_not_cause_a_derivative_kick() {
642        // P+D only, so the only difference a stale previous error could make is the D term.
643        let config = YawControllerConfig {
644            gains: Gains {
645                p: 1.0,
646                i: 0.0,
647                d: 0.5,
648            },
649            max_integral: 1.0,
650            max_rate_radps: 100.0,
651        };
652        let mut controller = YawController::default();
653
654        controller.control(&config, 0.01, 1.0, 0.2); // error 0.8 becomes the previous error
655        controller.control(&config, 0.01, f32::NAN, 0.2); // gap
656        let after_gap = controller.control(&config, 0.01, 0.5, 0.2); // error 0.3
657
658        // Without the reset, D would add 0.5 * (0.3 - 0.8) / 0.01 = -25 rad/s.
659        let fresh = YawController::default().control(&config, 0.01, 0.5, 0.2);
660        assert_relative_eq!(after_gap, fresh);
661    }
662
663    /// Tests that output rate is properly limited to `max_rate_radps`.
664    #[test]
665    fn test_max_rate_limiting() {
666        // Test that output is clamped to max_rate_radps
667        let config = p_only_config(10.0, 2.0);
668        let mut controller = YawController::default();
669
670        let dt = 0.01;
671
672        // Error of 0.5 rad with P=10 would give 5.0 rad/s
673        // Should be limited to 2.0 rad/s
674        let rate = controller.control(&config, dt, 0.5, 0.0);
675
676        assert_relative_eq!(rate, 2.0, epsilon = EPSILON, max_relative = 1e-3);
677
678        // Test negative limiting too
679        let rate = controller.control(&config, dt, -0.5, 0.0);
680        assert_relative_eq!(rate, -2.0, epsilon = EPSILON, max_relative = 1e-3);
681    }
682
683    /// Tests a realistic maneuver to verify controller convergence and stability.
684    #[test]
685    fn test_realistic_maneuvers() {
686        // Test a realistic 90-degree turn maneuver
687        let config = YawControllerConfig {
688            gains: Gains {
689                p: 2.0,
690                i: 0.3,
691                d: 0.5,
692            },
693            max_integral: 5.0,
694            max_rate_radps: 3.0,
695        };
696
697        let mut controller = YawController::default();
698
699        let dt = 0.1; // 0.1 seconds
700
701        // Simulate a 90-degree turn
702        let desired_yaw = 90.0 * PI / 180.0;
703        let mut current_yaw = 0.0;
704        let mut rates = Vec::new();
705
706        // Simulate control loop for 2 seconds (20 iterations)
707        for _ in 0..20 {
708            let rate = controller.control(&config, dt, desired_yaw, current_yaw);
709            rates.push(rate);
710
711            // Simple integration to update current yaw for next iteration
712            current_yaw += rate * dt;
713
714            // Normalize to [-PI, PI] for realism
715            if current_yaw > PI {
716                current_yaw -= 2.0 * PI;
717            } else if current_yaw < -PI {
718                current_yaw += 2.0 * PI;
719            }
720        }
721
722        // Verify the controller converges to the desired yaw
723        assert!(
724            (desired_yaw - current_yaw).abs() < 0.1,
725            "Controller should converge to desired yaw (within 0.1 rad)"
726        );
727
728        // Verify that the final rate approaches zero as error decreases
729        assert!(
730            rates.last().unwrap().abs() < 0.2,
731            "Rate should approach zero as error decreases"
732        );
733
734        // Additional checks for controller behavior:
735
736        // Initial rates should be high (turning toward target)
737        assert!(
738            rates[0] > 1.0,
739            "Initial rate should be high when error is large"
740        );
741
742        // Rates should gradually decrease as we approach target
743        assert!(
744            rates[0] > rates[rates.len() / 2] && rates[rates.len() / 2] > rates[rates.len() - 1],
745            "Rates should decrease as controller approaches target"
746        );
747    }
748
749    #[test]
750    fn validate_rejects_negative_or_non_finite_limits() {
751        // (max_integral, max_rate_radps, offending field)
752        let cases = [(-1.0, 1.0, "max_integral"), (1.0, -1.0, "max_rate_radps")];
753        for (max_integral, max_rate_radps, field) in cases {
754            let config = YawControllerConfig {
755                max_integral,
756                max_rate_radps,
757                ..Default::default()
758            };
759            assert_eq!(config.validate().map_err(|e| e.field), Err(field));
760        }
761    }
762
763    /// An invalid limit fails `validate` but `control` stays panic-free: the limit acts as 0.
764    #[test]
765    fn invalid_limits_give_neutral_output_without_panicking() {
766        for bad in [-1.0, f32::NAN] {
767            let config = YawControllerConfig {
768                gains: Gains {
769                    p: 1.0,
770                    i: 1.0,
771                    d: 0.0,
772                },
773                max_integral: bad,
774                max_rate_radps: bad,
775            };
776            let mut controller = YawController::default();
777            assert_eq!(
778                controller.control(&config, 0.1, 1.0, 0.0),
779                0.0,
780                "limit {bad}"
781            );
782            assert_eq!(controller.integrated_error, 0.0, "limit {bad}");
783        }
784    }
785
786    /// A gain change between ticks applies on the next tick and keeps the integral.
787    #[test]
788    fn gain_change_between_ticks_keeps_state() {
789        let mut config = i_only_config(1.0, 10.0, 10.0);
790        let mut controller = YawController::default();
791        controller.control(&config, 1.0, 0.5, 0.0);
792        let integral = controller.integrated_error;
793
794        config.gains.i = 2.0;
795        let rate = controller.control(&config, 0.01, 0.0, 0.0);
796
797        assert_eq!(controller.integrated_error, integral);
798        assert_relative_eq!(rate, 2.0 * integral, epsilon = EPSILON);
799    }
800}