Skip to main content

stable_flight/stabilizers/copter/
tuning.rs

1//! Autotune stages hosted by the [`CopterStabilizer`]: one loop's setpoint replaced by a
2//! [`Probe`]. See the "Tuning" section on [`CopterStabilizer`].
3
4use crate::Vec3;
5use crate::tuning::{LoopSignals, Probe, ProbeConfig, ProbeStatus, Tunable};
6
7use super::{CopterStabilizer, CopterStabilizerConfig};
8use crate::controllers::Gains;
9
10#[cfg(test)]
11mod tests;
12
13/// A loop of the [`CopterStabilizer`] that a tuning stage can replace.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum TunedLoop {
16    /// Roll rate loop: a probe sets the roll rate setpoint, in rad/s.
17    RollRate,
18    /// Pitch rate loop: a probe sets the pitch rate setpoint, in rad/s.
19    PitchRate,
20    /// Yaw rate loop: a probe sets the yaw rate setpoint, in rad/s.
21    YawRate,
22    /// Roll angle loop: a probe sets the roll angle setpoint, in rad.
23    Roll,
24    /// Pitch angle loop: a probe sets the pitch angle setpoint, in rad.
25    Pitch,
26    /// Heading loop: a probe sets the heading setpoint, in rad.
27    Heading,
28}
29
30/// Where a [`TunedLoop`] sits in the cascade: the controller that owns it and its axis.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub(super) enum Location {
33    /// The body-rate loop, axis 0 roll, 1 pitch, 2 yaw.
34    Rate(usize),
35    /// The attitude loop, axis 0 roll, 1 pitch.
36    Angle(usize),
37    /// The heading loop.
38    Heading,
39}
40
41impl TunedLoop {
42    /// The gains this loop flies in `config`.
43    ///
44    /// # Examples
45    ///
46    /// ```
47    /// use stable_flight::stabilizers::copter::{CopterStabilizerConfig, TunedLoop};
48    ///
49    /// let mut config = CopterStabilizerConfig::default();
50    /// TunedLoop::Heading.gains_mut(&mut config).p = 4.0;
51    /// assert_eq!(config.yaw.gains.p, 4.0);
52    /// assert_eq!(TunedLoop::Heading.gains(&config).p, 4.0);
53    /// ```
54    pub fn gains(self, config: &CopterStabilizerConfig) -> Gains {
55        let mut config = *config;
56        *self.gains_mut(&mut config)
57    }
58
59    /// The gains this loop flies in `config`, to retune them.
60    pub fn gains_mut(self, config: &mut CopterStabilizerConfig) -> &mut Gains {
61        match self {
62            Self::RollRate => &mut config.body_rate.roll_gains,
63            Self::PitchRate => &mut config.body_rate.pitch_gains,
64            Self::YawRate => &mut config.body_rate.yaw_gains,
65            Self::Roll => &mut config.attitude.roll_gains,
66            Self::Pitch => &mut config.attitude.pitch_gains,
67            Self::Heading => &mut config.yaw.gains,
68        }
69    }
70
71    /// Whether this is a rate loop (the others are angle and heading loops).
72    ///
73    /// # Examples
74    ///
75    /// ```
76    /// use stable_flight::stabilizers::copter::TunedLoop;
77    ///
78    /// assert!(TunedLoop::YawRate.is_rate());
79    /// assert!(!TunedLoop::Heading.is_rate());
80    /// ```
81    pub fn is_rate(self) -> bool {
82        matches!(self.location(), Location::Rate(_))
83    }
84
85    /// The rate loop under this angle or heading loop, which flies its rate setpoint; `None`
86    /// for a rate loop.
87    ///
88    /// # Examples
89    ///
90    /// ```
91    /// use stable_flight::stabilizers::copter::TunedLoop;
92    ///
93    /// assert_eq!(TunedLoop::Roll.inner(), Some(TunedLoop::RollRate));
94    /// assert_eq!(TunedLoop::RollRate.inner(), None);
95    /// ```
96    pub fn inner(self) -> Option<Self> {
97        match self {
98            Self::Roll => Some(Self::RollRate),
99            Self::Pitch => Some(Self::PitchRate),
100            Self::Heading => Some(Self::YawRate),
101            Self::RollRate | Self::PitchRate | Self::YawRate => None,
102        }
103    }
104
105    /// The angle or heading loop over this rate loop, which sets its setpoint; `None` for an
106    /// angle or heading loop.
107    ///
108    /// # Examples
109    ///
110    /// ```
111    /// use stable_flight::stabilizers::copter::TunedLoop;
112    ///
113    /// assert_eq!(TunedLoop::PitchRate.outer(), Some(TunedLoop::Pitch));
114    /// assert_eq!(TunedLoop::Pitch.outer(), None);
115    /// ```
116    pub fn outer(self) -> Option<Self> {
117        match self {
118            Self::RollRate => Some(Self::Roll),
119            Self::PitchRate => Some(Self::Pitch),
120            Self::YawRate => Some(Self::Heading),
121            Self::Roll | Self::Pitch | Self::Heading => None,
122        }
123    }
124
125    pub(super) fn location(self) -> Location {
126        match self {
127            Self::RollRate => Location::Rate(0),
128            Self::PitchRate => Location::Rate(1),
129            Self::YawRate => Location::Rate(2),
130            Self::Roll => Location::Angle(0),
131            Self::Pitch => Location::Angle(1),
132            Self::Heading => Location::Heading,
133        }
134    }
135}
136
137/// A tuning stage: the loop under test and its probe.
138#[derive(Clone, Debug, PartialEq)]
139pub(super) struct Stage {
140    pub(super) target: TunedLoop,
141    pub(super) probe: Probe,
142    /// The loop has been handed back (finished, interrupted, or stopped): no more override.
143    handed_back: bool,
144    interrupted: bool,
145}
146
147impl Stage {
148    /// Whether the probe still flies the loop.
149    pub(super) fn is_running(&self) -> bool {
150        !self.handed_back
151    }
152
153    fn status(&self) -> ProbeStatus {
154        if self.interrupted {
155            ProbeStatus::Interrupted
156        } else {
157            self.probe.status()
158        }
159    }
160}
161
162impl Tunable for CopterStabilizer {
163    type Target = TunedLoop;
164
165    /// Starts a probe on `target`: from the next [`stabilize`](crate::Stabilizer::stabilize),
166    /// a [`Probe`] with `config` sets that loop's setpoint (see the "Tuning" section on
167    /// [`CopterStabilizer`]).
168    ///
169    /// # Examples
170    ///
171    /// ```
172    /// use stable_flight::stabilizers::copter::{
173    ///     CopterStabilizer, CopterStabilizerConfig, TunedLoop,
174    /// };
175    /// use stable_flight::tuning::autotune::COPTER_RATE_STEP;
176    /// use stable_flight::tuning::{ProbeConfig, ProbeStatus, Tunable};
177    /// use stable_flight::{RateSetpoint, Setpoint, Stabilizer, VehicleState};
178    ///
179    /// let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
180    /// stabilizer.start_probe(TunedLoop::RollRate, ProbeConfig::Step(COPTER_RATE_STEP));
181    ///
182    /// // At rest with a zero rate setpoint: the step asks for 1 rad/s of roll, so the loop
183    /// // pushes right.
184    /// let state = VehicleState::default();
185    /// let output = stabilizer.stabilize(0.004, &Setpoint::Rate(RateSetpoint::default()), &state);
186    /// assert!(output.moments.x > 0.0);
187    ///
188    /// assert!(matches!(stabilizer.probe(), Some((TunedLoop::RollRate, ProbeStatus::Running(_)))));
189    /// stabilizer.stop_probe(); // hands the roll rate loop back
190    /// assert!(stabilizer.probe().is_none());
191    /// ```
192    fn start_probe(&mut self, target: TunedLoop, config: ProbeConfig) {
193        self.stop_probe();
194        self.stage = Some(Stage {
195            target,
196            probe: Probe::new(config),
197            handed_back: false,
198            interrupted: false,
199        });
200    }
201
202    fn probe(&self) -> Option<(TunedLoop, ProbeStatus)> {
203        self.stage
204            .as_ref()
205            .map(|stage| (stage.target, stage.status()))
206    }
207
208    fn stop_probe(&mut self) -> Option<(TunedLoop, ProbeStatus)> {
209        self.hand_back();
210        self.stage
211            .take()
212            .map(|stage| (stage.target, stage.status()))
213    }
214}
215
216impl CopterStabilizer {
217    /// Hands a running stage's loop back to its controller: the loop restarts with no
218    /// derivative history, so the setpoint's jump back doesn't kick it, and keeps its I term.
219    /// A no-op when no stage is running.
220    pub(super) fn hand_back(&mut self) {
221        let Some(stage) = &mut self.stage else {
222            return;
223        };
224        if stage.handed_back {
225            return;
226        }
227        stage.handed_back = true;
228        match stage.target.location() {
229            Location::Rate(axis) => self.body_rate.hand_back(axis),
230            Location::Angle(axis) => self.attitude.hand_back(axis),
231            Location::Heading => self.yaw.hand_back(),
232        }
233    }
234
235    /// Ends a running angle or heading stage as interrupted (its loop is idle on a rate tick).
236    pub(super) fn interrupt_attitude_stage(&mut self) {
237        let Some(stage) = &mut self.stage else {
238            return;
239        };
240        let angle_loop = !matches!(stage.target.location(), Location::Rate(_));
241        if angle_loop && stage.is_running() {
242            stage.interrupted = true;
243            self.hand_back();
244        }
245    }
246
247    /// Where the running stage replaces a value, or None when no stage runs: the one check an
248    /// idle tick pays.
249    pub(super) fn running_stage(&self) -> Option<Location> {
250        self.stage
251            .as_ref()
252            .filter(|stage| stage.is_running())
253            .map(|stage| stage.target.location())
254    }
255
256    /// Steps the running stage with its loop's `signals` and returns the setpoint the loop
257    /// runs on (`None` when no stage runs). The loop is handed back at the end of the tick
258    /// ([`finish_stage`](Self::finish_stage)), after its controller ran.
259    fn step_stage(&mut self, dt: f32, signals: &LoopSignals) -> Option<f32> {
260        let stage = self.stage.as_mut().filter(|stage| stage.is_running())?;
261        Some(stage.probe.step(dt, signals))
262    }
263
264    /// Hands the loop back once its probe has finished; call it at the end of the tick.
265    pub(super) fn finish_stage(&mut self) {
266        let finished = self
267            .stage
268            .as_ref()
269            .is_some_and(|stage| stage.is_running() && !stage.probe.status().is_running());
270        if finished {
271            self.hand_back();
272        }
273    }
274
275    /// Steps a probe on an angle or heading loop before the controllers run. `setpoints` are
276    /// the saturated roll, pitch, and heading setpoints, `error` the body-frame attitude error
277    /// the loops act on, `rates_radps` the body rates: the probe replaces one setpoint.
278    pub(super) fn probe_attitude(
279        &mut self,
280        dt: f32,
281        setpoints: &mut Vec3,
282        error: &Vec3,
283        rates_radps: &Vec3,
284    ) {
285        let Some(location) = self.running_stage() else {
286            return;
287        };
288        let saturated = self.loop_saturated(location);
289        let axis = match location {
290            Location::Angle(axis) => axis,
291            Location::Heading => 2,
292            Location::Rate(_) => return,
293        };
294        let signals = LoopSignals {
295            setpoint: setpoints[axis],
296            error: error[axis],
297            saturated,
298            rate_radps: rates_radps[axis],
299            last_moment: self.last_moments[axis],
300        };
301        self.inject(dt, axis, &signals, setpoints)
302    }
303
304    /// Steps a probe on a rate loop before the rate controller runs: the probe replaces that
305    /// axis's rate in `setpoints`. `filtered_rates_radps` holds the filtered rates the loop
306    /// runs on, `raw_rates_radps` the unfiltered ones the identify fit models the airframe from.
307    pub(super) fn probe_rates(
308        &mut self,
309        dt: f32,
310        setpoints: &mut Vec3,
311        filtered_rates_radps: &Vec3,
312        raw_rates_radps: &Vec3,
313    ) {
314        let Some(location @ Location::Rate(axis)) = self.running_stage() else {
315            return;
316        };
317        let signals = LoopSignals {
318            setpoint: setpoints[axis],
319            error: setpoints[axis] - filtered_rates_radps[axis],
320            saturated: self.loop_saturated(location),
321            rate_radps: raw_rates_radps[axis],
322            last_moment: self.last_moments[axis],
323        };
324        self.inject(dt, axis, &signals, setpoints)
325    }
326
327    /// Steps the running probe with `signals` for `axis` of `setpoints`: its setpoint
328    /// replaces `setpoints[axis]`.
329    fn inject(&mut self, dt: f32, axis: usize, signals: &LoopSignals, setpoints: &mut Vec3) {
330        if let Some(setpoint) = self.step_stage(dt, signals) {
331            setpoints[axis] = setpoint;
332        }
333    }
334
335    /// Whether `location`'s loop, or the loop under it, clipped on the last tick: a rate
336    /// loop's moment; an angle or heading loop's rate setpoint or that axis's moment.
337    fn loop_saturated(&self, location: Location) -> bool {
338        let clipped = &self.clipped;
339        match location {
340            Location::Rate(axis) => clipped.moments[axis],
341            Location::Angle(axis) => clipped.rates[axis] || clipped.moments[axis],
342            Location::Heading => clipped.rates[2] || clipped.moments[2],
343        }
344    }
345}