Skip to main content

stable_flight/tuning/autotune/
side.rs

1//! The loops a [`Supervisor`](super::Supervisor) tunes ([`Side`]: a copter's or a plane's),
2//! what it reads from the vehicle each update ([`Motion`]), and what a stage's procedure
3//! decides on ([`Decide`]).
4
5use core::fmt;
6
7use super::procedure::{Action, Input, Procedure, Verdict};
8use super::{AutotuneAbort, Envelope, Method, Settle, YAW_AXIS, tilt_axis};
9use crate::controllers::gyro::GyroFilter;
10use crate::controllers::{Gains, InvalidConfig};
11use crate::math::euler_angles;
12use crate::stabilizers::copter::{CopterStabilizerConfig, TunedLoop};
13use crate::tuning::{Measurement, ProbeAbort, ProbeConfig, Tunable};
14use crate::{Configurable, Setpoint, Vec2, Vec3, VehicleState};
15use nalgebra::UnitQuaternion;
16
17/// One set of loops the [`Supervisor`](super::Supervisor) tunes, and how: a copter's
18/// ([`CopterSide`]). The supervisor's phases (settle, probe, decide, commit, revert) are the
19/// same on every side; a side names its loops, gains, config, methods, and envelope, and
20/// supplies the procedures that decide what each stage flies. Sealed: the sides are core's.
21pub trait Side: sealed::Sealed + Copy + fmt::Debug + PartialEq {
22    /// The loops a stage tunes, and the stabilizer hosts probes on ([`Tunable`]).
23    type Target: Copy + fmt::Debug + PartialEq;
24    /// One target's gains.
25    type Gains: Copy + fmt::Debug + PartialEq;
26    /// The config of the stabilizer flying this side ([`SideConfig`]).
27    type Config: Copy + fmt::Debug + PartialEq;
28    /// How a stage tunes its target.
29    type Method: Copy + fmt::Debug + PartialEq;
30    /// The limits that end a stage, and the settle before each probe.
31    type Envelope: Copy + fmt::Debug + PartialEq;
32    /// A stage's method as a pure state machine (core's own).
33    #[doc(hidden)]
34    type Procedure: Copy + fmt::Debug + PartialEq;
35
36    /// `target`'s gains in `config`.
37    #[doc(hidden)]
38    fn gains(target: Self::Target, config: &Self::Config) -> Self::Gains;
39    /// Sets `target`'s gains in `config`.
40    #[doc(hidden)]
41    fn set_gains(target: Self::Target, config: &mut Self::Config, gains: Self::Gains);
42    /// The loop `probe` runs on for a stage on `target`.
43    #[doc(hidden)]
44    fn probed_loop(target: Self::Target, probe: &ProbeConfig) -> Self::Target;
45
46    /// Checks `method`, its error in the plan section it reports.
47    #[doc(hidden)]
48    fn validate_method(method: &Self::Method) -> Result<(), InvalidConfig>;
49    /// The settle `method` asks for before each probe; `None` uses the envelope's.
50    #[doc(hidden)]
51    fn method_settle(method: &Self::Method) -> Option<Settle>;
52    /// A fresh procedure for `method`, at a stage's start.
53    #[doc(hidden)]
54    fn procedure(method: Self::Method) -> Self::Procedure;
55    /// What `procedure` does next on `on`, for the stage `stage` describes.
56    #[doc(hidden)]
57    fn decide(
58        procedure: &mut Self::Procedure,
59        on: Decide,
60        stage: StageView<'_, Self>,
61    ) -> Action<Self::Gains>;
62    /// A search's verdict on the last decision, if any; taking it clears it.
63    #[doc(hidden)]
64    fn take_verdict(procedure: &mut Self::Procedure) -> Option<Verdict<Self::Gains>>;
65
66    /// Checks `envelope`.
67    #[doc(hidden)]
68    fn validate_envelope(envelope: &Self::Envelope) -> Result<(), InvalidConfig>;
69    /// Checks that `settle` is tighter than `envelope`'s limits.
70    #[doc(hidden)]
71    fn check_settle(envelope: &Self::Envelope, settle: &Settle) -> Result<(), InvalidConfig>;
72    /// The settle and times `envelope` gives every side's phases.
73    #[doc(hidden)]
74    fn waits(envelope: &Self::Envelope) -> Waits;
75    /// The limit `motion` breaks, if any, `start_altitude_m` the run's start.
76    #[doc(hidden)]
77    fn breach(
78        envelope: &Self::Envelope,
79        motion: &Motion,
80        start_altitude_m: f32,
81    ) -> Option<AutotuneAbort>;
82
83    /// The body rates the settle reads, `dt` on: through the stabilizer's gyro filters, or raw.
84    #[doc(hidden)]
85    fn filter_rates(
86        filters: &mut RateFilters,
87        config: &Self::Config,
88        rates_radps: Vec3,
89        dt: f32,
90    ) -> Vec3;
91    /// The roll and pitch `setpoint` holds on this side, in rad.
92    #[doc(hidden)]
93    fn attitude_target(setpoint: &Setpoint) -> Vec2;
94    /// Whether `motion` holds `settle`, within `envelope`, for a probe on `target` to start.
95    #[doc(hidden)]
96    fn settles(
97        envelope: &Self::Envelope,
98        settle: &Settle,
99        motion: &Motion,
100        target: Self::Target,
101    ) -> bool;
102    /// Whether `motion` holds `settle` about `target`'s axis on candidate gains.
103    #[doc(hidden)]
104    fn holds(settle: &Settle, motion: &Motion, target: Self::Target) -> bool;
105}
106
107mod sealed {
108    pub trait Sealed {}
109    impl Sealed for super::CopterSide {}
110    impl Sealed for super::super::PlaneSide {}
111}
112
113/// A stabilizer config that holds a [`Side`]'s config: the copter's is its own.
114pub trait SideConfig<K: Side> {
115    /// The side's config.
116    fn side(&self) -> &K::Config;
117    /// The side's config, to change it.
118    fn side_mut(&mut self) -> &mut K::Config;
119}
120
121/// What the [`Supervisor`](super::Supervisor) needs from a stabilizer to tune side `K`: probes
122/// on its loops, and a config holding the side's.
123pub trait SideTunable<K: Side>: Tunable<K::Target> + Configurable<Config: SideConfig<K>> {}
124
125impl<K: Side, S> SideTunable<K> for S where
126    S: Tunable<K::Target> + Configurable<Config: SideConfig<K>>
127{
128}
129
130/// What every side's envelope gives the phases: the settle before a probe and how long the
131/// phases wait. See [`Envelope`] for each.
132#[derive(Clone, Copy, Debug, PartialEq)]
133pub struct Waits {
134    pub(super) settle: Settle,
135    pub(super) settle_timeout_s: f32,
136    pub(super) recovery_s: f32,
137    pub(super) max_stale_s: f32,
138}
139
140/// One gyro filter per body axis (roll, pitch, yaw), for the settle's rates.
141#[derive(Clone, Debug, Default, PartialEq)]
142pub struct RateFilters(pub(super) [GyroFilter; 3]);
143
144/// What a procedure deciding for a stage may read: its target, the side's config as flown,
145/// and as it was at the run's start.
146pub struct StageView<'a, K: Side> {
147    pub(super) target: K::Target,
148    pub(super) config: &'a K::Config,
149    pub(super) run_start: Option<&'a K::Config>,
150}
151
152/// A copter's loops ([`TunedLoop`]), tuned on a [`CopterStabilizerConfig`] by a [`Method`]
153/// within an [`Envelope`]: the [`Autotune`](super::Autotune).
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub struct CopterSide;
156
157impl SideConfig<CopterSide> for CopterStabilizerConfig {
158    fn side(&self) -> &CopterStabilizerConfig {
159        self
160    }
161
162    fn side_mut(&mut self) -> &mut CopterStabilizerConfig {
163        self
164    }
165}
166
167/// A copter [`Procedure`], behind a type the [`Side`] trait can name.
168#[derive(Clone, Copy, Debug, PartialEq)]
169pub struct CopterProcedure(Procedure);
170
171impl Side for CopterSide {
172    type Target = TunedLoop;
173    type Gains = Gains;
174    type Config = CopterStabilizerConfig;
175    type Method = Method;
176    type Envelope = Envelope;
177    type Procedure = CopterProcedure;
178
179    fn gains(target: TunedLoop, config: &CopterStabilizerConfig) -> Gains {
180        target.gains(config)
181    }
182
183    fn set_gains(target: TunedLoop, config: &mut CopterStabilizerConfig, gains: Gains) {
184        *target.gains_mut(config) = gains;
185    }
186
187    /// An identification excites an angle loop's axis on the rate loop under it
188    /// ([`DesignPlan`](super::DesignPlan)); every other probe runs on `target` itself.
189    fn probed_loop(target: TunedLoop, probe: &ProbeConfig) -> TunedLoop {
190        match probe {
191            ProbeConfig::Identify(_) | ProbeConfig::IdentifyWing(_) => {
192                target.inner().unwrap_or(target)
193            }
194            ProbeConfig::Step(_) => target,
195        }
196    }
197
198    fn validate_method(method: &Method) -> Result<(), InvalidConfig> {
199        method
200            .validate()
201            .map_err(|e| e.in_section(method.plan_section()))
202    }
203
204    fn method_settle(method: &Method) -> Option<Settle> {
205        method.settle()
206    }
207
208    fn procedure(method: Method) -> CopterProcedure {
209        CopterProcedure(Procedure::new(method))
210    }
211
212    fn decide(procedure: &mut CopterProcedure, on: Decide, stage: StageView<'_, Self>) -> Action {
213        let StageView {
214            target,
215            config,
216            run_start,
217        } = stage;
218        let gains = target.gains(config);
219        let input = match on {
220            // No copter method computes over updates.
221            Decide::Computing => return Action::Fail(AutotuneAbort::Interrupted),
222            Decide::Start => Input::Start {
223                gains,
224                inner: target.inner().map(|inner| inner.gains(config)),
225                run_start: run_start.map_or(gains, |run_start| target.gains(run_start)),
226                // The stage's own axis: yaw flies no notch.
227                gyro: config.gyro_filters_on(tilt_axis(target).unwrap_or(YAW_AXIS)),
228            },
229            Decide::Measured {
230                measurement,
231                stalled,
232            } => Input::Measured {
233                measurement,
234                gains,
235                stalled,
236            },
237            Decide::Stalled => Input::Stalled { gains },
238            Decide::Aborted { abort } => Input::Aborted { abort, gains },
239            Decide::Breached { reason } => Input::Breached { reason, gains },
240            Decide::Held { settled } => Input::Held { settled, gains },
241            Decide::Unsettled => Input::Unsettled { gains },
242        };
243        procedure.0.next(input)
244    }
245
246    fn take_verdict(procedure: &mut CopterProcedure) -> Option<Verdict> {
247        procedure.0.take_verdict()
248    }
249
250    fn validate_envelope(envelope: &Envelope) -> Result<(), InvalidConfig> {
251        envelope.validate()
252    }
253
254    fn check_settle(envelope: &Envelope, settle: &Settle) -> Result<(), InvalidConfig> {
255        envelope.check_settle(settle)
256    }
257
258    fn waits(envelope: &Envelope) -> Waits {
259        Waits {
260            settle: envelope.settle,
261            settle_timeout_s: envelope.settle_timeout_s,
262            recovery_s: envelope.recovery_s,
263            max_stale_s: envelope.max_stale_s,
264        }
265    }
266
267    fn breach(
268        envelope: &Envelope,
269        motion: &Motion,
270        start_altitude_m: f32,
271    ) -> Option<AutotuneAbort> {
272        envelope.breach(motion, start_altitude_m)
273    }
274
275    /// Through the stabilizer's gyro filters on each axis, at their configured cutoffs.
276    fn filter_rates(
277        filters: &mut RateFilters,
278        config: &CopterStabilizerConfig,
279        rates_radps: Vec3,
280        dt: f32,
281    ) -> Vec3 {
282        Vec3::from_fn(|axis, _| {
283            let gyro = config.gyro_filters_on(axis);
284            filters.0[axis].apply(rates_radps[axis], dt, &gyro)
285        })
286    }
287
288    fn attitude_target(setpoint: &Setpoint) -> Vec2 {
289        attitude_target(setpoint)
290    }
291
292    fn settles(_envelope: &Envelope, settle: &Settle, motion: &Motion, target: TunedLoop) -> bool {
293        settle.holds_for(motion, target)
294    }
295
296    /// For a roll or pitch loop only its axis counts: the other may still ring on its start
297    /// gains (pitch on `racer`'s high start with 25 ms of delay, #518). A yaw rate or heading
298    /// loop needs both level and yaw still.
299    fn holds(settle: &Settle, motion: &Motion, target: TunedLoop) -> bool {
300        tilt_axis(target).map_or_else(
301            || settle.holds_yaw(motion),
302            |axis| settle.holds_axis(motion, axis),
303        )
304    }
305}
306
307/// What the envelope and the settle check, read once per update from the state. The envelope
308/// reads tilt from level and the settle from the attitude target, so a hover leaning to hold
309/// its position settles where it leans. The settle's rates are filtered through the
310/// stabilizer's gyro low-pass, the rates its loops fly on: read raw, a still vehicle's gyro
311/// noise and vibration hold them over the settle (0.2 rad/s on the sim's noise rows, the
312/// settle 0.1), so no stage starts (#373). The envelope reads the raw rate, so a breach shows
313/// on its first tick. Angles and rates are in the probed loops' frame
314/// ([`Tunable::probe_frame`]): view axes for a tailsitter's hover, where nose-up reads level.
315pub struct Motion {
316    /// The larger of |roll| and |pitch|, from level, in rad.
317    pub(super) tilt_rad: f32,
318    /// |roll| from level, in rad.
319    pub(super) bank_rad: f32,
320    /// |pitch| from level, in rad.
321    pub(super) pitch_rad: f32,
322    /// The largest raw body rate magnitude, in rad/s.
323    pub(super) rate_radps: f32,
324    /// The |roll| and |pitch| errors from the attitude target, in rad.
325    pub(super) axis_tilt_error_rad: [f32; 2],
326    /// The horizontal ground speed, in m/s; 0 for a NaN velocity.
327    pub(super) speed_mps: f32,
328    /// The filtered |roll| and |pitch| rates, in rad/s.
329    pub(super) axis_rate_radps: [f32; 2],
330    /// The filtered |yaw| rate, in rad/s.
331    pub(super) yaw_rate_radps: f32,
332    pub(super) altitude_m: f32,
333    /// The airspeed, in m/s, when the state has a valid one.
334    pub(super) airspeed_mps: Option<f32>,
335    /// How fast the airspeed changed since the last update, in m/s²; 0 without an airspeed
336    /// then and now. The supervisor sets it: a single state has no change.
337    pub(super) airspeed_change_mps2: f32,
338}
339
340impl Motion {
341    /// `state`'s motion in `frame` (the probed loops' frame, in the body frame), with
342    /// `filtered_radps` its body rates through the gyro low-pass and `target_rad` the roll
343    /// and pitch the loops hold ([`attitude_target`]), in that frame.
344    pub(super) fn of(
345        state: &VehicleState,
346        frame: &UnitQuaternion<f32>,
347        filtered_radps: Vec3,
348        target_rad: Vec2,
349    ) -> Self {
350        // The view as `VehicleState::rotate_body` builds it, without cloning the state.
351        let (roll, pitch, _) = euler_angles(&(state.attitude * frame));
352        let raw_radps = frame.inverse_transform_vector(&state.angular_velocity_radps);
353        let filtered_radps = frame.inverse_transform_vector(&filtered_radps);
354        let roll_error_rad = (roll - target_rad.x).abs();
355        let pitch_error_rad = (pitch - target_rad.y).abs();
356        Self {
357            tilt_rad: roll.abs().max(pitch.abs()),
358            bank_rad: roll.abs(),
359            pitch_rad: pitch.abs(),
360            rate_radps: raw_radps.amax(),
361            axis_tilt_error_rad: [roll_error_rad, pitch_error_rad],
362            speed_mps: zero_if_nan(state.velocity_mps.xy().norm()),
363            axis_rate_radps: [filtered_radps.x.abs(), filtered_radps.y.abs()],
364            yaw_rate_radps: filtered_radps.z.abs(),
365            altitude_m: state.position_m.z,
366            airspeed_mps: state.valid_airspeed_mps(),
367            airspeed_change_mps2: 0.0,
368        }
369    }
370}
371
372/// The roll and pitch `setpoint` holds, in rad, in the stabilizer's frame: an attitude
373/// setpoint's (a NaN axis is level, as the stabilizer reads it), a blend's hover side's, and
374/// level for a rate or plane setpoint, which holds no hover attitude. Guidance's target,
375/// before the stabilizer caps it at its maximum tilt: a target past the cap never settles, and
376/// the stage times out.
377pub(super) fn attitude_target(setpoint: &Setpoint) -> Vec2 {
378    let attitude = match setpoint {
379        Setpoint::Attitude(attitude) => attitude,
380        Setpoint::Blend(blend) => &blend.hover,
381        _ => return Vec2::zeros(),
382    };
383    Vec2::new(
384        zero_if_nan(attitude.roll_rad),
385        zero_if_nan(attitude.pitch_rad),
386    )
387}
388
389/// `value`, or 0 for NaN: the neutral reading of a missing angle or speed.
390pub(super) fn zero_if_nan(value: f32) -> f32 {
391    if value.is_nan() { 0.0 } else { value }
392}
393
394/// What a stage's procedure decides on.
395#[derive(Clone, Copy, Debug, PartialEq)]
396pub enum Decide {
397    /// The stage's start.
398    Start,
399    /// A finished probe's measurement, and whether the host stalled during it.
400    Measured {
401        measurement: Measurement,
402        stalled: bool,
403    },
404    /// A probe stopped because the host turned slow, with no measurement.
405    Stalled,
406    /// A probe that gave up.
407    Aborted { abort: ProbeAbort },
408    /// A probe or a hold on candidate gains that took the vehicle past the envelope.
409    Breached { reason: AutotuneAbort },
410    /// A hold ended, `settled` on its candidate or timed out.
411    Held { settled: bool },
412    /// The settle before a probe timed out on the committed gains.
413    Unsettled,
414    /// An update after the procedure asked to compute ([`Action::Compute`]).
415    Computing,
416}