Skip to main content

stable_flight/stabilizers/plane/
tuning.rs

1//! Autotune stages hosted by the [`PlaneStabilizer`]: one loop's setpoint replaced by a
2//! [`Probe`]. See the "Tuning" section on the [module docs](super).
3
4use crate::VehicleState;
5use crate::controllers::RateGains;
6use crate::tuning::{LoopSignals, Probe, ProbeConfig, ProbeStatus, Tunable, WingIdentifyProbe};
7
8use super::{PlaneStabilizer, PlaneStabilizerConfig};
9
10#[cfg(test)]
11mod tests;
12
13/// A loop of the [`PlaneStabilizer`] that a tuning stage can replace.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum PlaneLoop {
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    /// Roll angle loop: a probe sets the bank setpoint, in rad.
21    Roll,
22    /// Pitch angle loop: a probe sets the pitch setpoint, in rad.
23    Pitch,
24}
25
26/// One axis's gains on the [`PlaneStabilizer`]: its rate loop's, and its attitude loop's time
27/// constant. A loop's stage reads and sets its whole axis: on a plane the rate loop's
28/// feedforward and the attitude loop's time constant are tuned together, against one attitude
29/// step.
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub struct PlaneAxisGains {
32    /// The rate loop's gains.
33    pub rate: RateGains,
34    /// The attitude loop's time constant, in s: the rate target is the error divided by it.
35    pub time_constant_s: f32,
36}
37
38impl PlaneLoop {
39    /// The body axis this loop flies: 0 roll, 1 pitch.
40    ///
41    /// # Examples
42    ///
43    /// ```
44    /// use stable_flight::stabilizers::plane::PlaneLoop;
45    ///
46    /// assert_eq!(PlaneLoop::Pitch.axis(), 1);
47    /// ```
48    pub fn axis(self) -> usize {
49        match self {
50            Self::RollRate | Self::Roll => 0,
51            Self::PitchRate | Self::Pitch => 1,
52        }
53    }
54
55    /// Whether this is a rate loop (the others are angle loops).
56    pub fn is_rate(self) -> bool {
57        matches!(self, Self::RollRate | Self::PitchRate)
58    }
59
60    /// The rate loop under this angle loop; `None` for a rate loop.
61    ///
62    /// # Examples
63    ///
64    /// ```
65    /// use stable_flight::stabilizers::plane::PlaneLoop;
66    ///
67    /// assert_eq!(PlaneLoop::Roll.inner(), Some(PlaneLoop::RollRate));
68    /// assert_eq!(PlaneLoop::RollRate.inner(), None);
69    /// ```
70    pub fn inner(self) -> Option<Self> {
71        match self {
72            Self::Roll => Some(Self::RollRate),
73            Self::Pitch => Some(Self::PitchRate),
74            Self::RollRate | Self::PitchRate => None,
75        }
76    }
77
78    /// The gains of this loop's axis in `config`.
79    ///
80    /// # Examples
81    ///
82    /// ```
83    /// use stable_flight::stabilizers::plane::{PlaneLoop, PlaneStabilizerConfig};
84    ///
85    /// let mut config = PlaneStabilizerConfig::default();
86    /// let mut gains = PlaneLoop::Pitch.gains(&config);
87    /// gains.time_constant_s = 0.6;
88    /// PlaneLoop::PitchRate.set_gains(&mut config, gains);
89    /// assert_eq!(config.time_constant_s.y, 0.6);
90    /// ```
91    pub fn gains(self, config: &PlaneStabilizerConfig) -> PlaneAxisGains {
92        match self.axis() {
93            0 => PlaneAxisGains {
94                rate: config.rate.roll,
95                time_constant_s: config.time_constant_s.x,
96            },
97            _ => PlaneAxisGains {
98                rate: config.rate.pitch,
99                time_constant_s: config.time_constant_s.y,
100            },
101        }
102    }
103
104    /// Sets the gains of this loop's axis in `config`.
105    pub fn set_gains(self, config: &mut PlaneStabilizerConfig, gains: PlaneAxisGains) {
106        match self.axis() {
107            0 => {
108                config.rate.roll = gains.rate;
109                config.time_constant_s.x = gains.time_constant_s;
110            }
111            _ => {
112                config.rate.pitch = gains.rate;
113                config.time_constant_s.y = gains.time_constant_s;
114            }
115        }
116    }
117}
118
119/// A tuning stage: the loop under test and its probe.
120#[derive(Clone, Debug, PartialEq)]
121pub(super) struct Stage {
122    target: PlaneLoop,
123    probe: StageProbe,
124    /// The loop has been handed back (finished, interrupted, or stopped): no more override.
125    handed_back: bool,
126    interrupted: bool,
127}
128
129/// A stage's probe: a wing identification, which only a plane hosts, or any other.
130// The wing's window (9 KB) makes its variant the larger; a host holds one probe at a time.
131#[allow(clippy::large_enum_variant)]
132#[derive(Clone, Debug, PartialEq)]
133enum StageProbe {
134    Wing(WingIdentifyProbe),
135    Other(Probe),
136}
137
138impl StageProbe {
139    fn new(config: ProbeConfig) -> Self {
140        match config {
141            ProbeConfig::IdentifyWing(config) => Self::Wing(WingIdentifyProbe::new(config)),
142            config => Self::Other(Probe::new(config)),
143        }
144    }
145
146    /// The setpoint the loop flies this tick, `dt` on ([`Probe::step`]).
147    fn step(&mut self, dt: f32, signals: &LoopSignals) -> f32 {
148        match self {
149            Self::Wing(wing) => {
150                let offset = wing.step(
151                    dt,
152                    signals.rate_radps,
153                    signals.last_moment,
154                    signals.alpha_rad,
155                );
156                signals.setpoint + offset
157            }
158            Self::Other(probe) => probe.step(dt, signals),
159        }
160    }
161
162    fn status(&self) -> ProbeStatus {
163        match self {
164            Self::Wing(wing) => wing.status().into(),
165            Self::Other(probe) => probe.status(),
166        }
167    }
168}
169
170impl Stage {
171    fn status(&self) -> ProbeStatus {
172        if self.interrupted {
173            ProbeStatus::Interrupted
174        } else {
175            self.probe.status()
176        }
177    }
178}
179
180impl Tunable<PlaneLoop> for PlaneStabilizer {
181    /// Starts a probe on `target`: from the next [`stabilize`](crate::Stabilizer::stabilize),
182    /// a [`Probe`] with `config` sets that loop's setpoint (see the "Tuning" section on the
183    /// [module docs](super)).
184    ///
185    /// # Examples
186    ///
187    /// ```
188    /// use stable_flight::stabilizers::plane::{PlaneLoop, PlaneStabilizer, PlaneStabilizerConfig};
189    /// use stable_flight::tuning::{ProbeConfig, ProbeStatus, StepConfig, Tunable};
190    /// use stable_flight::{PlaneSetpoint, Setpoint, Stabilizer, VehicleState};
191    ///
192    /// let mut stabilizer = PlaneStabilizer::new(PlaneStabilizerConfig::default());
193    /// let step = StepConfig { amplitude: 0.3, duration_s: 1.0, settle_band: 0.1, filter_hz: 0.0 };
194    /// stabilizer.start_probe(PlaneLoop::Roll, ProbeConfig::Step(step));
195    ///
196    /// // Level, with a level setpoint: the step asks for 0.3 rad of bank, so the wing rolls right.
197    /// let level = Setpoint::Plane(PlaneSetpoint { thrust: 0.6, ..Default::default() });
198    /// let output = stabilizer.stabilize(0.004, &level, &VehicleState::default());
199    /// assert!(output.moments.x > 0.0);
200    ///
201    /// assert!(matches!(stabilizer.probe(), Some((PlaneLoop::Roll, ProbeStatus::Running(_)))));
202    /// stabilizer.stop_probe(); // hands the roll loop back
203    /// assert!(Tunable::<PlaneLoop>::probe(&stabilizer).is_none());
204    /// ```
205    fn start_probe(&mut self, target: PlaneLoop, config: ProbeConfig) {
206        self.stop_probe();
207        self.stage = Some(Stage {
208            target,
209            probe: StageProbe::new(config),
210            handed_back: false,
211            interrupted: false,
212        });
213    }
214
215    fn probe(&self) -> Option<(PlaneLoop, ProbeStatus)> {
216        self.stage
217            .as_ref()
218            .map(|stage| (stage.target, stage.status()))
219    }
220
221    fn stop_probe(&mut self) -> Option<(PlaneLoop, ProbeStatus)> {
222        self.stage
223            .take()
224            .map(|stage| (stage.target, stage.status()))
225    }
226}
227
228impl PlaneStabilizer {
229    /// Ends a running stage as interrupted: its loop is idle, or the setpoint stopped flying
230    /// the plane side (another setpoint, a transition). The loops have no derivative to reset,
231    /// so handing back only stops the override; the rate integral stays.
232    pub(crate) fn interrupt_stage(&mut self) {
233        if let Some(stage) = self.stage.as_mut().filter(|stage| !stage.handed_back) {
234            stage.handed_back = true;
235            stage.interrupted = true;
236        }
237    }
238
239    /// Ends a running angle stage as interrupted: a rate setpoint idles the attitude loops.
240    pub(super) fn interrupt_angle_stage(&mut self) {
241        if self.running_stage().is_some_and(|target| !target.is_rate()) {
242            self.interrupt_stage();
243        }
244    }
245
246    /// The loop the running stage replaces a setpoint on, or `None` when no stage runs.
247    fn running_stage(&self) -> Option<PlaneLoop> {
248        self.stage
249            .as_ref()
250            .filter(|stage| !stage.handed_back)
251            .map(|stage| stage.target)
252    }
253
254    /// Steps a probe on an angle loop before its rate target is computed. `angles_rad` are the
255    /// saturated bank and pitch setpoints, `error_rad` the body-frame attitude error the loops
256    /// act on, `rates_radps` the body rates: the probe replaces its axis's angle.
257    pub(super) fn probe_angles(
258        &mut self,
259        dt: f32,
260        angles_rad: &mut [f32; 2],
261        error_rad: [f32; 2],
262        rates_radps: &crate::Vec3,
263    ) {
264        let Some(target) = self.running_stage().filter(|target| !target.is_rate()) else {
265            return;
266        };
267        let axis = target.axis();
268        let signals = LoopSignals {
269            setpoint: angles_rad[axis],
270            error: error_rad[axis],
271            saturated: self.moment_clipped(axis),
272            rate_radps: rates_radps[axis],
273            last_moment: self.last_moments[axis],
274            alpha_rad: 0.0,
275        };
276        if let Some(angle_rad) = self.step_stage(dt, &signals) {
277            angles_rad[axis] = angle_rad;
278        }
279    }
280
281    /// Steps a probe on a rate loop before the rate controller runs: the probe replaces its
282    /// axis's rate in `desired_radps`, read against `state`'s body rates; a pitch probe also
283    /// reads the angle of attack.
284    pub(super) fn probe_rates(
285        &mut self,
286        dt: f32,
287        desired_radps: &mut crate::Vec3,
288        state: &VehicleState,
289    ) {
290        let Some(target) = self.running_stage().filter(|target| target.is_rate()) else {
291            return;
292        };
293        let axis = target.axis();
294        let rates_radps = &state.angular_velocity_radps;
295        let alpha_rad = match target {
296            PlaneLoop::PitchRate => self.angle_of_attack_rad(state),
297            _ => 0.0,
298        };
299        let signals = LoopSignals {
300            setpoint: desired_radps[axis],
301            error: desired_radps[axis] - rates_radps[axis],
302            saturated: self.moment_clipped(axis),
303            rate_radps: rates_radps[axis],
304            last_moment: self.last_moments[axis],
305            alpha_rad,
306        };
307        if let Some(rate_radps) = self.step_stage(dt, &signals) {
308            desired_radps[axis] = rate_radps;
309        }
310    }
311
312    /// Hands the loop back once its probe has finished; call it at the end of the tick, after
313    /// the loop's controller ran on the probe's last setpoint.
314    pub(super) fn finish_stage(&mut self) {
315        if let Some(stage) = self.stage.as_mut()
316            && !stage.handed_back
317            && !stage.probe.status().is_running()
318        {
319            stage.handed_back = true;
320        }
321    }
322
323    fn step_stage(&mut self, dt: f32, signals: &LoopSignals) -> Option<f32> {
324        let stage = self.stage.as_mut().filter(|stage| !stage.handed_back)?;
325        Some(stage.probe.step(dt, signals))
326    }
327
328    /// Whether `axis`'s moment was at full deflection on the last tick.
329    fn moment_clipped(&self, axis: usize) -> bool {
330        self.last_moments[axis].abs() >= 1.0
331    }
332}