Skip to main content

stable_flight/tuning/
autotune.rs

1//! The copter autotune supervisor: see [`Autotune`].
2
3use core::fmt;
4
5use crate::controllers::low_pass::LowPass;
6use crate::controllers::{
7    Gains, InvalidConfig, RATE_I_PER_P, YAW_RATE_I_PER_P, check, check_limit, check_positive,
8    check_unit_interval,
9};
10use crate::math::euler_angles;
11use crate::stabilizers::copter::{CopterStabilizerConfig, TunedLoop};
12use crate::{Configurable, FlightLoop, Vec3, VehicleState};
13use nalgebra::UnitQuaternion;
14
15use super::{
16    DesignError, IdentifyConfig, LoopShapingConfig, Measurement, ProbeAbort, ProbeConfig,
17    ProbeStatus, RateModel, StepConfig, StepSummary, Tunable, design_angle_p, design_rate,
18};
19
20use procedure::{Action, Input, Procedure};
21
22mod procedure;
23#[cfg(test)]
24mod tests;
25
26/// The most stages a plan may hold: [`StagePlan::copter_design_search`] and a step test of
27/// each loop it tunes.
28pub const MAX_STAGES: usize = 14;
29
30/// One stage of an autotune: which loop, and the method that tunes it.
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub struct StagePlan {
33    /// The loop to tune.
34    pub target: TunedLoop,
35    /// How to tune it.
36    pub method: Method,
37}
38
39impl StagePlan {
40    /// A step test of `target` with the copter defaults ([`StepTestPlan::copter`]).
41    pub fn copter_step_test(target: TunedLoop) -> Self {
42        Self {
43            target,
44            method: Method::StepTest(StepTestPlan::copter(target)),
45        }
46    }
47
48    /// A step test of `target` on a full-size multirotor's steps
49    /// ([`StepTestPlan::large_copter`]): the steps
50    /// [`large_copter_search`](Self::large_copter_search) judges, so its results read against
51    /// the search's.
52    pub fn large_copter_step_test(target: TunedLoop) -> Self {
53        Self {
54            target,
55            method: Method::StepTest(StepTestPlan::large_copter(target)),
56        }
57    }
58
59    /// The copter design search: [`DesignPlan::copter`] for roll and pitch rate, then roll
60    /// and pitch angle (each angle design flies on its designed rate loop), then
61    /// [`SearchPlan::copter`] for each in the same order, starting from its design, then
62    /// [`SearchPlan::copter_yaw_rate`] from the start's yaw gains.
63    /// The design spares the search most of its climb from the start gains; the search keeps
64    /// only gains that passed steps, so a design from a bad fit doesn't outlive it (on
65    /// QuadCopterX in RealFlight one fit designed roll rate P 0.41 against 0.63–1.04, #518).
66    /// Every loop is designed before any is searched: a loop still on its start gains can
67    /// ring and keep another's steps from settling (pitch on `racer`'s high start with 25 ms
68    /// of delay, #518). On the sim its roll and pitch stages took 152–380 s against the
69    /// search's 308–693 s, and tuned the high starts with delay the search can't (#518); with
70    /// the yaw search, the passing robustness rows take 202–280 s (#296).
71    ///
72    /// Yaw rate is searched without a design: the design's yaw P (5–8 on the sim's quads)
73    /// clips 0.5 rad/s steps for 44–116 ms, and the search from its D (0.22–0.25) left steps
74    /// short of 90% in the window (#296).
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// use stable_flight::stabilizers::copter::TunedLoop;
80    /// use stable_flight::tuning::autotune::{Method, StagePlan};
81    ///
82    /// let plan = StagePlan::copter_design_search();
83    /// assert!(matches!(plan[0].method, Method::Design(_)));
84    /// assert!(matches!(plan[4].method, Method::Search(_)));
85    /// assert_eq!(plan[4].target, TunedLoop::RollRate);
86    /// assert_eq!(plan[8].target, TunedLoop::YawRate);
87    /// ```
88    pub fn copter_design_search() -> [Self; 9] {
89        let loops = [
90            TunedLoop::RollRate,
91            TunedLoop::PitchRate,
92            TunedLoop::Roll,
93            TunedLoop::Pitch,
94        ];
95        let design = loops.map(|target| Self {
96            target,
97            method: Method::Design(DesignPlan::copter()),
98        });
99        let search = loops.map(|target| Self {
100            target,
101            method: Method::Search(SearchPlan::copter(target)),
102        });
103        let [roll_rate, pitch_rate, roll, pitch] = design;
104        let [
105            search_roll_rate,
106            search_pitch_rate,
107            search_roll,
108            search_pitch,
109        ] = search;
110        [
111            roll_rate,
112            pitch_rate,
113            roll,
114            pitch,
115            search_roll_rate,
116            search_pitch_rate,
117            search_roll,
118            search_pitch,
119            Self {
120                target: TunedLoop::YawRate,
121                method: Method::Search(SearchPlan::copter_yaw_rate()),
122            },
123        ]
124    }
125
126    /// The step search for a full-size multirotor: [`SearchPlan::copter`] for roll and pitch
127    /// rate, then roll and pitch angle, each on the slower steps a large aircraft needs
128    /// ([`LARGE_COPTER_RATE_STEP`], [`LARGE_COPTER_TILT_STEP`]), clipping for up to
129    /// [`LARGE_COPTER_MAX_SATURATED_S`], and keeping the start's rate I: with I at
130    /// [`RATE_I_PER_P`] of P, the Alia 250's rate steps (no rate D, rising in 0.5 s) overshoot
131    /// by 10% and its pitch rate search tilts out of the envelope (#374). Fly it within
132    /// [`Envelope::large_copter`].
133    ///
134    /// The design search doesn't fit a full-size aircraft yet: on the sim's Alia it designs
135    /// rate P about 19× the step search's, and the search after it tilts out of the envelope
136    /// (#572). From rate P 1 and 3 this search tunes the Alia's sim model to within 25% of its
137    /// hand tune in 11–15 min of sim time (#572).
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// use stable_flight::stabilizers::copter::TunedLoop;
143    /// use stable_flight::tuning::autotune::{LARGE_COPTER_RATE_STEP, Method, StagePlan};
144    ///
145    /// let plan = StagePlan::large_copter_search();
146    /// assert_eq!(plan[0].target, TunedLoop::RollRate);
147    /// let Method::Search(search) = plan[0].method else { unreachable!() };
148    /// assert_eq!(search.test.step, LARGE_COPTER_RATE_STEP);
149    /// assert_eq!(search.i_per_p, None);
150    /// ```
151    pub fn large_copter_search() -> [Self; 4] {
152        [
153            TunedLoop::RollRate,
154            TunedLoop::PitchRate,
155            TunedLoop::Roll,
156            TunedLoop::Pitch,
157        ]
158        .map(|target| Self {
159            target,
160            method: Method::Search(SearchPlan::large_copter(target)),
161        })
162    }
163}
164
165/// How a stage tunes its loop: which probes it runs and what gains follow from them.
166#[derive(Clone, Copy, Debug, PartialEq)]
167pub enum Method {
168    /// Alternating step responses, measured and reported; the gains don't change.
169    StepTest(StepTestPlan),
170    /// A search for the largest gain of one term whose step responses meet a criterion, from
171    /// the stage's start gains, kept only if it flies no worse than a start that met the
172    /// criterion.
173    Search(SearchPlan),
174    /// Gains designed from a fitted model of the loop's axis, committed without steps.
175    Design(DesignPlan),
176}
177
178impl Method {
179    /// Checks the method's own fields and probe configs (its settle is checked against the
180    /// envelope by [`Autotune::new`]).
181    ///
182    /// # Errors
183    ///
184    /// When the step test is invalid ([`StepTestPlan::validate`]), the search is
185    /// ([`SearchPlan::validate`]), or the design is ([`DesignPlan::validate`]).
186    pub fn validate(&self) -> Result<(), InvalidConfig> {
187        match self {
188            Self::StepTest(plan) => plan.validate(),
189            Self::Search(plan) => plan.validate(),
190            Self::Design(plan) => plan.validate(),
191        }
192    }
193
194    /// The settle this method asks for before each probe; `None` uses the envelope's.
195    pub fn settle(&self) -> Option<Settle> {
196        match self {
197            Self::Design(_) => None,
198            Self::StepTest(plan) => Some(plan.settle),
199            Self::Search(plan) => Some(plan.test.settle),
200        }
201    }
202
203    /// The section [`Autotune::new`] reports this method's errors in.
204    fn plan_section(&self) -> &'static str {
205        match self {
206            Self::StepTest(_) => "plan.step_test",
207            Self::Search(_) => "plan.search",
208            Self::Design(_) => "plan.design",
209        }
210    }
211}
212
213/// Identification of a copter rate axis: a 0.7 rad/s square wave added to its rate setpoint
214/// for 3 s, washed out at 0.2 s (PX4's `MC_AT_SYSID_AMP` and time constant). On the sim 3 s
215/// fit the same model as 20 s on every airframe, from any start (#312). On the rate setpoint
216/// the excitation doesn't scale with the angle P and no edge kicks the angle D (#561).
217pub const COPTER_IDENTIFY: IdentifyConfig = IdentifyConfig {
218    amplitude: 0.7,
219    duration_s: 3.0,
220    washout_tc_s: 0.2,
221};
222
223/// Share of a search's largest pass it keeps, and of loop shaping's largest angle P: 10% off,
224/// as ArduPilot backs off its autotune result.
225const SEARCH_BACK_OFF: f32 = 0.9;
226
227/// The copter's angle P range, in rad/s of rate per rad of angle, searched or designed in.
228const COPTER_ANGLE_P_MIN: f32 = 1.0;
229const COPTER_ANGLE_P_MAX: f32 = 10.0;
230
231/// Loop shaping of a copter's roll and pitch: 65° of phase margin on the rate and angle loops,
232/// angle P within the angle search's range (1–10) less its 10% margin
233/// ([`SearchPlan::copter_angle`]). On the sim 65° met the step spec on every clean and delayed
234/// row of the three copter airframes, and put angle P at the range's top as the angle search
235/// does (#312, #517).
236pub const COPTER_LOOP_SHAPING: LoopShapingConfig = LoopShapingConfig {
237    rate_margin_deg: 65.0,
238    angle_margin_deg: 65.0,
239    angle_p_min: COPTER_ANGLE_P_MIN,
240    angle_p_max: COPTER_ANGLE_P_MAX,
241    angle_back_off: SEARCH_BACK_OFF,
242};
243
244/// Step response of a copter rate loop: 1 rad/s (57°/s) held for 0.25 s, about four of the
245/// 67 ms period QuadCopterX's rate loops oscillate at on the edge of stability (#295), which
246/// tilts it about 14°; filtered at 40 Hz.
247pub const COPTER_RATE_STEP: StepConfig = StepConfig {
248    amplitude: 1.0,
249    duration_s: 0.25,
250    settle_band: 0.1,
251    filter_hz: 40.0,
252};
253
254/// Step response of a copter yaw rate loop, searched: [`COPTER_RATE_STEP`] at half the size
255/// (0.5 rad/s). Prop drag gives a quad little yaw authority (about 7 rad/s² per unit moment on
256/// the sim's `quad_x`), so 1 rad/s steps clip at any P that rises within PX4's yaw target,
257/// 0.2 s; the sim yaw search clipped 4–10× as long at 1 rad/s and settled on a lower P (#296).
258/// QuadCopterX has half `quad_x`'s yaw authority, and its steps reach only about half the step
259/// in the 0.25 s window, so its search stops on clipping rather than on the criterion. On a
260/// sim plant fitted to it that bound lands on the same P from every start (1.11–1.15), whose
261/// steps overshoot at most 0.03 and settle within 0.56 s. Longer windows fail: at 1 s a start
262/// with I as high as P overshoots on the I alone, and the search falls to P 0.51 (#558).
263pub const COPTER_YAW_RATE_STEP: StepConfig = StepConfig {
264    amplitude: 0.5,
265    ..COPTER_RATE_STEP
266};
267
268/// Step response of a copter yaw rate loop, step-tested: [`COPTER_YAW_RATE_STEP`] held for
269/// 1 s, so a yaw as slow as QuadCopterX's rises and settles within it (within 0.50 and 0.56 s
270/// on the sim plant fitted to it, #558).
271pub const COPTER_YAW_RATE_TEST_STEP: StepConfig = StepConfig {
272    duration_s: 1.0,
273    ..COPTER_YAW_RATE_STEP
274};
275
276/// Step response of a copter roll or pitch loop, searched and step-tested: 5° held for 1.5 s,
277/// filtered at 20 Hz. QuadCopterX's hand-tuned angle loop (P 3) reaches only 89% of a step in
278/// 0.8 s (#298), so the window covers about four of its time constants; the vehicle drifts
279/// about 1 m meanwhile. At 10°, an angle P of about 6 asks the tuned rate loop (P about 1) for
280/// a full moment; at 5°, about 12 (#304). At the tuned angle P 9 on the sim, `quad_x`'s 10°
281/// steps clip for 13 ticks and `heavy_quad`'s for 15, past [`COPTER_MAX_SATURATED_S`]; 5°
282/// steps clip for 5 (#310).
283pub const COPTER_TILT_STEP: StepConfig = StepConfig {
284    amplitude: 0.0875,
285    duration_s: 1.5,
286    settle_band: 0.1,
287    filter_hz: 20.0,
288};
289
290/// Step response of a copter heading loop: [`COPTER_TILT_STEP`] at twice the size (10°).
291pub const COPTER_HEADING_STEP: StepConfig = StepConfig {
292    amplitude: 2.0 * COPTER_TILT_STEP.amplitude,
293    ..COPTER_TILT_STEP
294};
295
296/// Level before each copter step: within 2.5° and 0.1 rad/s for 0.5 s (ArduPilot's
297/// `AUTOTUNE_LEVEL_ANGLE_CD` and `AUTOTUNE_REQUIRED_LEVEL_TIME_MS`), so each step starts from
298/// rest.
299pub const COPTER_STEP_SETTLE: Settle = Settle {
300    tilt_rad: 0.044,
301    rate_radps: 0.1,
302    hold_s: 0.5,
303};
304
305/// Step response of a full-size multirotor's rate loop: 0.2 rad/s held for 1.5 s, rising in
306/// about 0.6 s on the Alia 250's sim model (motor lag 0.17 s). On [`COPTER_RATE_STEP`] the
307/// Alia's rate steps never rise within the window, so the overshoot criterion passes any gain
308/// (#351).
309pub const LARGE_COPTER_RATE_STEP: StepConfig = StepConfig {
310    amplitude: 0.2,
311    duration_s: 1.5,
312    ..COPTER_RATE_STEP
313};
314
315/// Step response of a full-size multirotor's roll or pitch loop: [`COPTER_TILT_STEP`] held for
316/// 2.5 s, rising in about 1.2 s on the Alia 250's sim model (#351).
317pub const LARGE_COPTER_TILT_STEP: StepConfig = StepConfig {
318    duration_s: 2.5,
319    ..COPTER_TILT_STEP
320};
321
322/// How long a full-size multirotor's step may clip, in s: its rate step's moment saturates for
323/// the first few ticks while the slow motors catch up (#351).
324pub const LARGE_COPTER_MAX_SATURATED_S: f32 = 0.2;
325
326/// A step test: `pairs` pairs of steps, alternating `+step` and `−step` so a trim or CG offset
327/// shows as asymmetry rather than bias, each from a [`Settle`]. A step clipped for longer than
328/// `max_saturated_s` (a clipped step measures the limit, not the loop) is invalid and runs
329/// again; `max_invalid` in a row fail the stage. A step flagged stalled
330/// ([`Autotune::note_stall`]) runs again too, on its own budget: a stall says nothing about the
331/// loop, so `max_stalled` in a row (the host can't keep time) fail the stage.
332#[derive(Clone, Copy, Debug, PartialEq)]
333pub struct StepTestPlan {
334    /// The step, in its positive direction.
335    pub step: StepConfig,
336    /// Pairs of steps to measure. At least 1.
337    pub pairs: usize,
338    /// Level before each step.
339    pub settle: Settle,
340    /// How long a step may be clipped and still count, in s. Non-negative and finite: a D kick
341    /// clips the first tick or so of a rate step.
342    pub max_saturated_s: f32,
343    /// Clipped steps in a row that fail the stage. At least 1.
344    pub max_invalid: usize,
345    /// Stalled steps in a row that fail the stage. At least 1.
346    pub max_stalled: usize,
347}
348
349/// How long a copter step may clip and still count, in s: 10 ticks at 250 Hz, half a tick
350/// clear of `f32` rounding (clipped time sums `dt`; ten 4 ms ticks come to slightly over
351/// 0.04). A step's first ticks ask for more than full moment until the loop catches up: a
352/// real limit, not a bad response. Above P 1, a 1 rad/s rate step does (tuned rate loops reach
353/// P 1.3 on QuadCopterX); so does a 5° angle step at the tuned angle P 9, for 5 ticks on the
354/// sim's `quad_x` and 6–10 under its trim rows. A 5-tick allowance fails those rows, and in
355/// RealFlight left 3 of 16 angle searches on their start after points whose every step
356/// clipped (#310). Heading steps share it as one rule; it isn't measured on them.
357pub const COPTER_MAX_SATURATED_S: f32 = 0.042;
358
359impl StepTestPlan {
360    /// The copter defaults for `target`: three pairs of [`COPTER_RATE_STEP`] (roll and pitch
361    /// rate), [`COPTER_YAW_RATE_TEST_STEP`] (yaw rate),
362    /// [`COPTER_TILT_STEP`] (roll and pitch), or [`COPTER_HEADING_STEP`] (heading), from
363    /// [`COPTER_STEP_SETTLE`], each clipping for up to [`COPTER_MAX_SATURATED_S`], allowing
364    /// 3 clipped steps in a row and 10 stalled steps in a row (RealFlight's proxy has frozen
365    /// for 100 ms dozens of times a run).
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// use stable_flight::stabilizers::copter::TunedLoop;
371    /// use stable_flight::tuning::autotune::{COPTER_TILT_STEP, StepTestPlan};
372    ///
373    /// assert_eq!(StepTestPlan::copter(TunedLoop::Roll).step, COPTER_TILT_STEP);
374    /// ```
375    pub fn copter(target: TunedLoop) -> Self {
376        let step = match target {
377            TunedLoop::RollRate | TunedLoop::PitchRate => COPTER_RATE_STEP,
378            TunedLoop::YawRate => COPTER_YAW_RATE_TEST_STEP,
379            TunedLoop::Roll | TunedLoop::Pitch => COPTER_TILT_STEP,
380            TunedLoop::Heading => COPTER_HEADING_STEP,
381        };
382        Self {
383            step,
384            pairs: 3,
385            settle: COPTER_STEP_SETTLE,
386            max_saturated_s: COPTER_MAX_SATURATED_S,
387            max_invalid: 3,
388            max_stalled: 10,
389        }
390    }
391
392    /// [`copter`](Self::copter) for roll or pitch, on a full-size multirotor's steps
393    /// ([`LARGE_COPTER_RATE_STEP`] or [`LARGE_COPTER_TILT_STEP`]), clipping for up to
394    /// [`LARGE_COPTER_MAX_SATURATED_S`]. Yaw rate and heading are [`copter`](Self::copter)'s
395    /// unchanged.
396    ///
397    /// # Examples
398    ///
399    /// ```
400    /// use stable_flight::stabilizers::copter::TunedLoop;
401    /// use stable_flight::tuning::autotune::{LARGE_COPTER_TILT_STEP, StepTestPlan};
402    ///
403    /// assert_eq!(StepTestPlan::large_copter(TunedLoop::Roll).step, LARGE_COPTER_TILT_STEP);
404    /// ```
405    pub fn large_copter(target: TunedLoop) -> Self {
406        let mut plan = Self::copter(target);
407        plan.step = match target {
408            TunedLoop::RollRate | TunedLoop::PitchRate => LARGE_COPTER_RATE_STEP,
409            TunedLoop::Roll | TunedLoop::Pitch => LARGE_COPTER_TILT_STEP,
410            TunedLoop::YawRate | TunedLoop::Heading => return plan,
411        };
412        plan.max_saturated_s = LARGE_COPTER_MAX_SATURATED_S;
413        plan
414    }
415
416    /// Checks the step ([`StepConfig::validate`]) and the counts and clip allowance.
417    pub fn validate(&self) -> Result<(), InvalidConfig> {
418        self.step.validate()?;
419        check("pairs", self.pairs >= 1, "at least 1")?;
420        check_limit("max_saturated_s", self.max_saturated_s)?;
421        check("max_invalid", self.max_invalid >= 1, "at least 1")?;
422        check("max_stalled", self.max_stalled >= 1, "at least 1")
423    }
424}
425
426/// A gain search on one term of a loop: the largest gain whose step responses meet
427/// `criterion`, found by bracketing and bisection, then backed off by `margin` and verified.
428///
429/// 1. **Baseline:** `test.pairs` pairs at the start gains; if they meet the criterion, their
430///    summary is what the result must not be worse than. A start above `max` (a gain the
431///    search would never pick) isn't flown: its term is lowered to `max` and committed
432///    ([`AutotuneEvent::Lowered`]), so the vehicle settles on it and it stays if nothing
433///    better passes or the stage fails. A start whose steps abort or keep clipping leaves no
434///    baseline.
435/// 2. **Bracket** from the start's gain: `× factor` per point while points pass, up to `max`;
436///    `÷ factor` while they fail, down to `min` (nothing passing: see below). A
437///    point passes when `confirm` pairs in a row pass, so one lucky pair near a sharp limit
438///    doesn't (ArduPilot's `ignore_next`); the first failing pair fails it.
439/// 3. **Bisect** (geometric mean) until the bracket is within `resolution`.
440/// 4. **Verify** `margin ×` the largest pass with `test.pairs` pairs, and keep it only if it
441///    passes [`Acceptance`] against a baseline that met the criterion, or, without one, meets
442///    the criterion itself.
443///
444/// A search that keeps no result keeps its start gains if their steps met the criterion, and
445/// otherwise puts back the loop's gains at the run's start ([`Autotune::start`]): a start the
446/// search was seeded with (a design, [`StagePlan::copter_design_search`]) that never passed
447/// doesn't outlive it. The run's start lowered to `max` stays lowered.
448///
449/// A pair is judged on its two steps' means, so a trim offset doesn't bias it. A step that
450/// aborts (reversed or runaway) fails its pair, as do `test.max_invalid` clipped steps in a
451/// row (a gain whose steps keep clipping measures the limit) and an [`Envelope`] breach while
452/// the candidate flies; on the baseline, aborts and clipping leave no baseline, and a breach
453/// fails the stage. Stalled steps only run again
454/// (`test.max_stalled`). Only the step under test flies a candidate;
455/// the vehicle settles on the committed gains between steps.
456#[derive(Clone, Copy, Debug, PartialEq)]
457pub struct SearchPlan {
458    /// The term searched.
459    pub term: Term,
460    /// What a pair must meet to pass.
461    pub criterion: Criterion,
462    /// The steps, their settle, clip allowance, and invalid limit; `pairs` sizes the baseline
463    /// and the verify.
464    pub test: StepTestPlan,
465    /// Pairs in a row a bracket point must pass. At least 1.
466    pub confirm: usize,
467    /// The bracket's growth per pair. Above 1.
468    pub factor: f32,
469    /// The bracket's ratio at which bisection stops. Above 1.
470    pub resolution: f32,
471    /// The fraction of the largest pass to verify and keep. In (0, 1].
472    pub margin: f32,
473    /// The least gain tried. Positive.
474    pub min: f32,
475    /// The largest gain tried. Above `min`.
476    pub max: f32,
477    /// How much worse than the baseline the result may fly.
478    pub acceptance: Acceptance,
479    /// With [`Term::P`] only: I at this share of each P tried, in 1/s, so every P carries the
480    /// I that holds the trim moment ([`RATE_I_PER_P`] on roll and pitch, [`YAW_RATE_I_PER_P`]
481    /// on yaw); `None` keeps the start's I. The
482    /// baseline flies the start's gains as they are, so from a start whose I isn't at this
483    /// share, a candidate differs from the baseline in I as well as P. Non-negative and finite.
484    pub i_per_p: Option<f32>,
485}
486
487/// `gains` with I at `i_per_p` of P, in 1/s; unchanged for `None`
488/// ([`SearchPlan::i_per_p`], [`DesignPlan::rate_i_per_p`]).
489pub(crate) fn with_i_per_p(gains: Gains, i_per_p: Option<f32>) -> Gains {
490    Gains {
491        i: i_per_p.map_or(gains.i, |ratio| ratio * gains.p),
492        ..gains
493    }
494}
495
496/// `Ok` when `i_per_p` is `None` or non-negative and finite.
497fn check_i_per_p(field: &'static str, i_per_p: Option<f32>) -> Result<(), InvalidConfig> {
498    i_per_p.map_or(Ok(()), |ratio| check_limit(field, ratio))
499}
500
501impl SearchPlan {
502    /// The copter defaults for a rate loop's P, with I at [`RATE_I_PER_P`] of it and D as it
503    /// starts (a design sets it, [`StagePlan::copter_design_search`]):
504    /// [`Criterion::Overshoot`] at ArduPilot's default aggressiveness (0.1: overshoot 0.05,
505    /// bounce-back 0.1) in [0.1, 3]. Steps of [`COPTER_RATE_STEP`], two pairs for the baseline
506    /// and the verify; a bracket point passes on two pairs in a row; brackets of `× 1.3`
507    /// bisected to 10%, a 0.9 margin. Steps clip for up to 10 ticks ([`StepTestPlan::copter`]):
508    /// with 5, clipping rather than overshoot caps P on QuadCopterX, and a 0.5 rad/s step
509    /// doubles the noise relative to the step (#304).
510    ///
511    /// ArduPilot's D search (largest D before bounce-back) doesn't bound D on closed-loop
512    /// steps: with the rate I, overshoot decays without falling back, so D climbs until the
513    /// response overdamps. The design's D comes from the fitted lag instead (#517).
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// use stable_flight::tuning::autotune::{SearchPlan, Term};
519    ///
520    /// let plan = SearchPlan::copter_rate();
521    /// assert_eq!(plan.term, Term::P);
522    /// ```
523    pub fn copter_rate() -> Self {
524        Self {
525            term: Term::P,
526            criterion: Criterion::Overshoot {
527                max_overshoot: 0.05,
528                max_bounce_back: 0.1,
529                settled_past: None,
530            },
531            test: StepTestPlan {
532                pairs: 2,
533                ..StepTestPlan::copter(TunedLoop::RollRate)
534            },
535            confirm: 2,
536            factor: 1.3,
537            resolution: 1.1,
538            margin: SEARCH_BACK_OFF,
539            min: 0.1,
540            max: 3.0,
541            acceptance: Acceptance::default(),
542            i_per_p: Some(RATE_I_PER_P),
543        }
544    }
545
546    /// The copter defaults for a roll or pitch angle loop's P (ArduPilot's angle-P stage),
547    /// from the start gains in [1, 10] (above about 10, 5° steps clip the moment on
548    /// QuadCopterX); overshoot and bounce-back at most 0.05
549    /// (ArduPilot's aggressiveness halved, as for its angle P). Bounce-back is the overshoot
550    /// above where the response levels off, so it counts even when a disturbance holds the
551    /// response short of the step (about 8% on QuadCopterX). Overshoot counts from where the
552    /// response ends, within the settle band past the step, so a disturbance holding it past
553    /// doesn't count either: on the Titan Cobra every P from 6.5 down to 1.7 ended 5–7% past
554    /// without ringing, and judged from the step the search walked P down to 1.3 (#564). Steps
555    /// of [`COPTER_TILT_STEP`]; otherwise as [`copter_rate`](Self::copter_rate).
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// use stable_flight::tuning::autotune::SearchPlan;
561    ///
562    /// assert_eq!(SearchPlan::copter_angle().max, 10.0);
563    /// ```
564    pub fn copter_angle() -> Self {
565        Self {
566            criterion: Criterion::Overshoot {
567                max_overshoot: 0.05,
568                max_bounce_back: 0.05,
569                settled_past: Some(COPTER_TILT_STEP.settle_band),
570            },
571            test: StepTestPlan {
572                pairs: 2,
573                ..StepTestPlan::copter(TunedLoop::Roll)
574            },
575            min: COPTER_ANGLE_P_MIN,
576            max: COPTER_ANGLE_P_MAX,
577            i_per_p: None,
578            ..Self::copter_rate()
579        }
580    }
581
582    /// The copter yaw rate search: [`copter_rate`](Self::copter_rate) on steps of
583    /// [`COPTER_YAW_RATE_STEP`], D as it starts (0 on yaw by default, as ArduPilot's
584    /// `ATC_RAT_YAW_D` and PX4's `MC_YAWRATE_D`), I at [`YAW_RATE_I_PER_P`] of P. That I holds
585    /// a yaw trim only up to `yaw_max_integral` (`BodyRateControllerConfig`); with the start's
586    /// I kept instead, small P overshoots on the I alone, the bracket stops there, and the
587    /// result depends on the start: 0.35 against 0.91 on the sim's `racer` with a 0.40 yaw
588    /// trim (#296).
589    ///
590    /// # Examples
591    ///
592    /// ```
593    /// use stable_flight::tuning::autotune::{COPTER_YAW_RATE_STEP, SearchPlan};
594    ///
595    /// assert_eq!(SearchPlan::copter_yaw_rate().test.step, COPTER_YAW_RATE_STEP);
596    /// ```
597    pub fn copter_yaw_rate() -> Self {
598        Self {
599            test: StepTestPlan {
600                step: COPTER_YAW_RATE_STEP,
601                pairs: 2,
602                ..StepTestPlan::copter(TunedLoop::YawRate)
603            },
604            i_per_p: Some(YAW_RATE_I_PER_P),
605            ..Self::copter_rate()
606        }
607    }
608
609    /// The copter search for `target` from a design ([`StagePlan::copter_design_search`]):
610    /// [`copter_rate`](Self::copter_rate) for roll or pitch rate, whose D the design set,
611    /// [`copter_yaw_rate`](Self::copter_yaw_rate), or [`copter_angle`](Self::copter_angle).
612    ///
613    /// # Examples
614    ///
615    /// ```
616    /// use stable_flight::stabilizers::copter::TunedLoop;
617    /// use stable_flight::tuning::autotune::SearchPlan;
618    ///
619    /// assert_eq!(SearchPlan::copter(TunedLoop::RollRate), SearchPlan::copter_rate());
620    /// assert_eq!(SearchPlan::copter(TunedLoop::Roll), SearchPlan::copter_angle());
621    /// ```
622    pub fn copter(target: TunedLoop) -> Self {
623        match target {
624            TunedLoop::RollRate | TunedLoop::PitchRate => Self::copter_rate(),
625            TunedLoop::YawRate => Self::copter_yaw_rate(),
626            TunedLoop::Roll | TunedLoop::Pitch | TunedLoop::Heading => Self::copter_angle(),
627        }
628    }
629
630    /// [`copter`](Self::copter) for roll or pitch, on a full-size multirotor's steps
631    /// ([`StepTestPlan::large_copter`], in [`copter`](Self::copter)'s pairs), keeping the
632    /// start's rate I ([`StagePlan::large_copter_search`] says why). Yaw rate and heading,
633    /// which the large search doesn't tune, are [`copter`](Self::copter)'s unchanged.
634    pub fn large_copter(target: TunedLoop) -> Self {
635        let plan = Self::copter(target);
636        if matches!(target, TunedLoop::YawRate | TunedLoop::Heading) {
637            return plan;
638        }
639        Self {
640            test: StepTestPlan {
641                pairs: plan.test.pairs,
642                ..StepTestPlan::large_copter(target)
643            },
644            i_per_p: None,
645            ..plan
646        }
647    }
648
649    /// Checks the steps ([`StepTestPlan::validate`]), the criterion, the bracket's factors and
650    /// bounds, the acceptance, and `i_per_p`.
651    pub fn validate(&self) -> Result<(), InvalidConfig> {
652        check(
653            "i_per_p",
654            self.i_per_p.is_none() || self.term == Term::P,
655            "None unless term is P",
656        )?;
657        check_i_per_p("i_per_p", self.i_per_p)?;
658        self.test.validate()?;
659        self.criterion.validate()?;
660        check("confirm", self.confirm >= 1, "at least 1")?;
661        check(
662            "factor",
663            self.factor > 1.0 && self.factor.is_finite(),
664            "above 1",
665        )?;
666        check(
667            "resolution",
668            self.resolution > 1.0 && self.resolution.is_finite(),
669            "above 1",
670        )?;
671        check_unit_interval("margin", self.margin)?;
672        check_positive("min", self.min)?;
673        check(
674            "max",
675            self.max > self.min && self.max.is_finite(),
676            "above min and finite",
677        )?;
678        self.acceptance.validate()
679    }
680}
681
682/// A term of a PID loop's [`Gains`].
683#[derive(Clone, Copy, Debug, PartialEq, Eq)]
684pub enum Term {
685    /// The proportional gain.
686    P,
687    /// The derivative gain.
688    D,
689}
690
691impl Term {
692    /// This term's gain in `gains`.
693    pub fn get(self, gains: Gains) -> f32 {
694        match self {
695            Self::P => gains.p,
696            Self::D => gains.d,
697        }
698    }
699
700    /// `gains` with this term set to `gain`.
701    pub fn with(self, gains: Gains, gain: f32) -> Gains {
702        match self {
703            Self::P => Gains { p: gain, ..gains },
704            Self::D => Gains { d: gain, ..gains },
705        }
706    }
707}
708
709/// What a search's pair of steps must meet, on the means of [`StepSummary`]; limits are
710/// fractions of the step (ArduPilot's aggressiveness).
711#[derive(Clone, Copy, Debug, PartialEq)]
712pub enum Criterion {
713    /// The response overshoots at most `max_overshoot` and falls back at most
714    /// `max_bounce_back` after its peak: for a P search, a rate loop's judging overshoot from
715    /// the step and an angle loop's from where its steps end ([`settled_past`]).
716    ///
717    /// [`settled_past`]: Criterion::Overshoot::settled_past
718    Overshoot {
719        /// The most overshoot. Non-negative.
720        max_overshoot: f32,
721        /// The most bounce-back. Non-negative.
722        max_bounce_back: f32,
723        /// When set, overshoot counts from where each step ended
724        /// ([`StepSummary::overshoot_past_end`]) rather than from the step, and no step may
725        /// end more than this past the step. For a window that outlasts the rise, as an angle
726        /// step's 1.5 s does (the slowest pass on the Titan Cobra, P 1.43, rose in 812 ms,
727        /// #564): a disturbance holding the response past the step, without ringing,
728        /// isn't overshoot that a lower P removes (#564). `None` judges from the step, for a
729        /// window that may end mid-rise (a 0.25 s yaw rate step). Non-negative.
730        settled_past: Option<f32>,
731    },
732}
733
734impl Criterion {
735    /// Whether `steps` meet it: their means within the limits. No steps don't.
736    pub fn passes(&self, steps: &StepSummary) -> bool {
737        let Self::Overshoot {
738            max_overshoot,
739            max_bounce_back,
740            settled_past,
741        } = *self;
742        let overshoot = match settled_past {
743            Some(_) => steps.overshoot_past_end.mean(),
744            None => steps.overshoot.mean(),
745        };
746        let (Some(overshoot), Some(bounce_back)) = (overshoot, steps.bounce_back.mean()) else {
747            return false;
748        };
749        let ended_past = steps.final_value.max - 1.0;
750        overshoot <= max_overshoot
751            && bounce_back <= max_bounce_back
752            && settled_past.is_none_or(|limit| ended_past <= limit)
753    }
754
755    /// The most bounce-back it allows.
756    pub fn max_bounce_back(&self) -> f32 {
757        match *self {
758            Self::Overshoot {
759                max_bounce_back, ..
760            } => max_bounce_back,
761        }
762    }
763
764    fn validate(&self) -> Result<(), InvalidConfig> {
765        match *self {
766            Self::Overshoot {
767                max_overshoot,
768                max_bounce_back,
769                settled_past,
770            } => {
771                check_limit("criterion.max_overshoot", max_overshoot)?;
772                check_limit("criterion.max_bounce_back", max_bounce_back)?;
773                settled_past.map_or(Ok(()), |limit| check_limit("criterion.settled_past", limit))
774            }
775        }
776    }
777}
778
779/// How a search's verify compares with a baseline that met the criterion: the result is kept
780/// unless it is worse.
781/// Worse is more overshoot than the baseline's plus `overshoot_margin`, a mean settling time
782/// above the baseline's times `settling_ratio`, more steps unsettled, or more bounce-back than
783/// both the baseline's and the criterion's limit.
784#[derive(Clone, Copy, Debug, PartialEq)]
785pub struct Acceptance {
786    /// Overshoot allowed above the baseline's. Non-negative.
787    pub overshoot_margin: f32,
788    /// Settling time allowed, as a multiple of the baseline's. At least 1.
789    pub settling_ratio: f32,
790}
791
792impl Default for Acceptance {
793    /// 0.05 more overshoot, 10% slower settling.
794    fn default() -> Self {
795        Self {
796            overshoot_margin: 0.05,
797            settling_ratio: 1.1,
798        }
799    }
800}
801
802impl Acceptance {
803    /// Whether `verify` flies no worse than `baseline` (see [`Acceptance`]); a mean the
804    /// baseline lacks (no valid steps, none settled) can't be worse.
805    pub fn accepts(
806        &self,
807        criterion: &Criterion,
808        baseline: &StepSummary,
809        verify: &StepSummary,
810    ) -> bool {
811        verify.count() > 0
812            && no_worse(baseline.overshoot.mean(), verify.overshoot.mean(), |base| {
813                base + self.overshoot_margin
814            })
815            && no_worse(
816                baseline.settling_time_s.mean(),
817                verify.settling_time_s.mean(),
818                |base| base * self.settling_ratio,
819            )
820            && verify.not_settled <= baseline.not_settled
821            && no_worse(
822                baseline.bounce_back.mean(),
823                verify.bounce_back.mean(),
824                |base| base.max(criterion.max_bounce_back()),
825            )
826    }
827
828    fn validate(&self) -> Result<(), InvalidConfig> {
829        check_limit("acceptance.overshoot_margin", self.overshoot_margin)?;
830        check(
831            "acceptance.settling_ratio",
832            self.settling_ratio >= 1.0 && self.settling_ratio.is_finite(),
833            "at least 1 and finite",
834        )
835    }
836}
837
838/// Whether `value` is within `limit(base)`: a missing baseline allows anything, a missing
839/// value against a present baseline is worse.
840fn no_worse(base: Option<f32>, value: Option<f32>, limit: impl FnOnce(f32) -> f32) -> bool {
841    match (base, value) {
842        (Some(base), Some(value)) => value <= limit(base),
843        (Some(_), None) => false,
844        (None, _) => true,
845    }
846}
847
848/// Gains for one loop from a fitted model of its axis, committed without steps: search from
849/// them once every loop is designed ([`StagePlan::copter_design_search`]).
850///
851/// 1. **Identify:** `identify` excites the axis on its rate loop's setpoint (an angle loop's
852///    probe runs on the rate loop under it) and fits a [`RateModel`]. The fit starts at the
853///    settle timeout even when the vehicle hasn't settled: a loop that rings on its start gains only
854///    adds excitation (#356). A slow host may stop it 3 times in a row before the stage fails.
855/// 2. **Design:** a rate loop's P and D by [`design_rate`], its I at `rate_i_per_p` of P; an
856///    angle loop's P by [`design_angle_p`] on the rate loop's committed gains, its I and D
857///    kept. A fit the design can't use runs again; the third fails the stage
858///    ([`AutotuneAbort::Design`]).
859/// 3. **Hold:** the design flies until the vehicle holds the settle about the loop's axis on
860///    it. One that doesn't within the settle timeout ([`AutotuneEvent::Unsettled`]), or
861///    breaches the envelope, goes back and counts as an unusable fit. The design flies from
862///    then on ([`Outcome::Designed`]), but a failure before its loop's search finishes puts
863///    the loop's earlier gains back.
864#[derive(Clone, Copy, Debug, PartialEq)]
865pub struct DesignPlan {
866    /// The excitation and fit.
867    pub identify: IdentifyConfig,
868    /// The design's margins and angle P range.
869    pub design: LoopShapingConfig,
870    /// A rate design's I at this share of its P, in 1/s ([`SearchPlan::i_per_p`]); `None`
871    /// keeps the start's I. Non-negative and finite.
872    pub rate_i_per_p: Option<f32>,
873}
874
875impl DesignPlan {
876    /// The copter defaults: [`COPTER_IDENTIFY`], [`COPTER_LOOP_SHAPING`], and rate I at
877    /// [`RATE_I_PER_P`].
878    ///
879    /// # Examples
880    ///
881    /// ```
882    /// use stable_flight::tuning::autotune::{COPTER_LOOP_SHAPING, DesignPlan};
883    ///
884    /// assert_eq!(DesignPlan::copter().design, COPTER_LOOP_SHAPING);
885    /// ```
886    pub fn copter() -> Self {
887        Self {
888            identify: COPTER_IDENTIFY,
889            design: COPTER_LOOP_SHAPING,
890            rate_i_per_p: Some(RATE_I_PER_P),
891        }
892    }
893
894    /// Checks the fit ([`IdentifyConfig::validate`]), the design
895    /// ([`LoopShapingConfig::validate`]), and `rate_i_per_p`.
896    pub fn validate(&self) -> Result<(), InvalidConfig> {
897        check_i_per_p("rate_i_per_p", self.rate_i_per_p)?;
898        self.identify.validate()?;
899        self.design.validate()
900    }
901
902    /// The gains `model` designs from the loop's `start`: a rate loop's (`inner` `None`), or
903    /// an angle loop's P flown on the `inner` rate gains, through a gyro low-pass at
904    /// `gyro_cutoff_hz`.
905    fn gains(
906        &self,
907        model: &RateModel,
908        start: Gains,
909        inner: Option<Gains>,
910        gyro_cutoff_hz: f32,
911    ) -> Result<Gains, DesignError> {
912        match inner {
913            None => design_rate(model, start, gyro_cutoff_hz, &self.design)
914                .map(|gains| with_i_per_p(gains, self.rate_i_per_p)),
915            Some(rate) => design_angle_p(model, rate, start, gyro_cutoff_hz, &self.design)
916                .map(|p| Gains { p, ..start }),
917        }
918    }
919}
920
921/// How level and still the vehicle must hold before a probe starts.
922#[derive(Clone, Copy, Debug, PartialEq)]
923pub struct Settle {
924    /// Roll and pitch within this, in rad, in the probed loops' frame
925    /// ([`Tunable::probe_frame`]), as are the rates.
926    pub tilt_rad: f32,
927    /// Roll and pitch rates within this, in rad/s, read through the stabilizer's gyro
928    /// low-pass; the yaw rate too for a yaw rate or heading stage, as ArduPilot's level check
929    /// does (`AC_AutoTune::currently_level`, `AUTOTUNE_LEVEL_RATE_Y_CD`, 7.5°/s). Roll and
930    /// pitch stages leave yaw out: with 25 ms of delay it rings on its start gains at ±0.18
931    /// rad/s on `racer` without tilting the vehicle (#518).
932    pub rate_radps: f32,
933    /// For this long, in s.
934    pub hold_s: f32,
935}
936
937impl Settle {
938    /// Whether `motion` is level and still enough.
939    fn holds(&self, motion: &Motion) -> bool {
940        motion.tilt_rad < self.tilt_rad && motion.tilt_rate_radps < self.rate_radps
941    }
942
943    /// Whether `motion` is level and still enough about `axis` alone (0 roll, 1 pitch).
944    fn holds_axis(&self, motion: &Motion, axis: usize) -> bool {
945        motion.axis_tilt_rad[axis] < self.tilt_rad && motion.axis_rate_radps[axis] < self.rate_radps
946    }
947
948    /// Whether `motion` is level and still enough, and turning slowly enough too.
949    fn holds_yaw(&self, motion: &Motion) -> bool {
950        self.holds(motion) && motion.yaw_rate_radps < self.rate_radps
951    }
952
953    /// Whether `motion` holds this settle for a probe on `target`: before a step on it the
954    /// vehicle is still about that loop's axis, so a yaw rate or heading stage waits for yaw
955    /// too.
956    fn holds_for(&self, motion: &Motion, target: TunedLoop) -> bool {
957        match tilt_axis(target) {
958            Some(_) => self.holds(motion),
959            None => self.holds_yaw(motion),
960        }
961    }
962}
963
964/// Limits that end a stage, and how still the vehicle must be before a probe starts.
965#[derive(Clone, Copy, Debug, PartialEq)]
966pub struct Envelope {
967    /// Roll or pitch beyond this aborts the stage, in rad, in the probed loops' frame
968    /// ([`Tunable::probe_frame`]): a tailsitter's view, where nose-up hover is level.
969    pub max_tilt_rad: f32,
970    /// A rate about any of the probed loops' axes beyond this aborts the stage, in rad/s.
971    pub max_rate_radps: f32,
972    /// Sinking more than this below the altitude at [`Autotune::start`] aborts, in m.
973    pub max_altitude_loss_m: f32,
974    /// Level and still enough to start a probe, unless the stage's method sets its own
975    /// ([`Method::settle`]).
976    pub settle: Settle,
977    /// How long to wait for a settle, in s. At the timeout a step fails the stage, and an
978    /// identification starts anyway: a fit only gains excitation from a ringing loop.
979    pub settle_timeout_s: f32,
980    /// After a probe on candidate gains ends, how long the vehicle has on the committed gains
981    /// to come back inside the limits before a breach fails the stage, in s. A breach while
982    /// the candidate flies fails only the candidate. After a freeze
983    /// ([`Autotune::note_stall`]), breaches don't count for as long. Non-negative.
984    pub recovery_s: f32,
985    /// How long the host may go without a fresh vehicle state
986    /// ([`Autotune::set_state_stale`]) before the run fails
987    /// [`HostFault`](AutotuneAbort::HostFault), in s: meanwhile the vehicle flies on unseen.
988    /// Positive.
989    pub max_stale_s: f32,
990}
991
992impl Default for Envelope {
993    /// Copter limits: 35° tilt, 4 rad/s, 3 m sink; settle within 6° and 0.3 rad/s for 1 s,
994    /// waiting up to 10 s; 1 s to recover from a candidate; 2 s without a fresh state.
995    /// RealFlight's reconnects come 0.5, 1.5, and 3.5 s into an outage, so the run rides
996    /// through the first two; a QuadCopterX unseen for 3.5 s mid-step rolled over (#309).
997    fn default() -> Self {
998        Self {
999            max_tilt_rad: 0.6,
1000            max_rate_radps: 4.0,
1001            max_altitude_loss_m: 3.0,
1002            settle: Settle {
1003                tilt_rad: 0.1,
1004                rate_radps: 0.3,
1005                hold_s: 1.0,
1006            },
1007            settle_timeout_s: 10.0,
1008            recovery_s: 1.0,
1009            max_stale_s: 2.0,
1010        }
1011    }
1012}
1013
1014impl Envelope {
1015    /// [`Default`]'s limits, waiting up to 30 s to settle: a full-size multirotor brakes a
1016    /// step's sideways speed slowly, and the Alia 250's sim model doesn't level within the
1017    /// default 10 s (#351).
1018    ///
1019    /// # Examples
1020    ///
1021    /// ```
1022    /// use stable_flight::tuning::autotune::Envelope;
1023    ///
1024    /// assert_eq!(Envelope::large_copter().settle_timeout_s, 30.0);
1025    /// ```
1026    pub fn large_copter() -> Self {
1027        Self {
1028            settle_timeout_s: 30.0,
1029            ..Self::default()
1030        }
1031    }
1032
1033    /// Checks that every limit and time is positive and finite, and that settling
1034    /// ([`check_settle`](Self::check_settle)) is tighter than aborting.
1035    pub fn validate(&self) -> Result<(), InvalidConfig> {
1036        check_positive("max_tilt_rad", self.max_tilt_rad)?;
1037        check_positive("max_rate_radps", self.max_rate_radps)?;
1038        check_positive("max_altitude_loss_m", self.max_altitude_loss_m)?;
1039        check_positive("settle_timeout_s", self.settle_timeout_s)?;
1040        check_limit("recovery_s", self.recovery_s)?;
1041        check_positive("max_stale_s", self.max_stale_s)?;
1042        self.check_settle(&self.settle)
1043    }
1044
1045    /// Checks that `settle` is positive and tighter than the abort limits, and that its hold
1046    /// fits in `settle_timeout_s`.
1047    pub fn check_settle(&self, settle: &Settle) -> Result<(), InvalidConfig> {
1048        check(
1049            "settle.tilt_rad",
1050            settle.tilt_rad > 0.0 && settle.tilt_rad < self.max_tilt_rad,
1051            "positive and below max_tilt_rad",
1052        )?;
1053        check(
1054            "settle.rate_radps",
1055            settle.rate_radps > 0.0 && settle.rate_radps < self.max_rate_radps,
1056            "positive and below max_rate_radps",
1057        )?;
1058        check(
1059            "settle.hold_s",
1060            settle.hold_s > 0.0 && settle.hold_s < self.settle_timeout_s,
1061            "positive and below settle_timeout_s",
1062        )
1063    }
1064
1065    /// The limit `motion` breaks, if any. NaN never counts as a breach.
1066    fn breach(&self, motion: &Motion, start_altitude_m: f32) -> Option<AutotuneAbort> {
1067        if motion.tilt_rad > self.max_tilt_rad {
1068            Some(AutotuneAbort::Tilt)
1069        } else if motion.rate_radps > self.max_rate_radps {
1070            Some(AutotuneAbort::Rate)
1071        } else if start_altitude_m - motion.altitude_m > self.max_altitude_loss_m {
1072            Some(AutotuneAbort::AltitudeLoss)
1073        } else {
1074            None
1075        }
1076    }
1077}
1078
1079/// What the envelope and the settle check, read once per update from the state. The settle's
1080/// rates are filtered through the stabilizer's gyro low-pass, the rates its loops fly on: read
1081/// raw, a still vehicle's gyro noise and vibration hold them over the settle (0.2 rad/s on the
1082/// sim's noise rows, the settle 0.1), so no stage starts (#373). The envelope reads the raw
1083/// rate, so a breach shows on its first tick. Angles and rates are in the probed loops' frame
1084/// ([`Tunable::probe_frame`]): view axes for a tailsitter's hover, where nose-up reads level.
1085struct Motion {
1086    /// The larger of |roll| and |pitch|, in rad.
1087    tilt_rad: f32,
1088    /// The largest raw body rate magnitude, in rad/s.
1089    rate_radps: f32,
1090    /// The larger of the filtered |roll| and |pitch| rates, in rad/s.
1091    tilt_rate_radps: f32,
1092    /// |roll| and |pitch|, in rad.
1093    axis_tilt_rad: [f32; 2],
1094    /// The filtered |roll| and |pitch| rates, in rad/s.
1095    axis_rate_radps: [f32; 2],
1096    /// The filtered |yaw| rate, in rad/s.
1097    yaw_rate_radps: f32,
1098    altitude_m: f32,
1099}
1100
1101impl Motion {
1102    /// `state`'s motion in `frame` (the probed loops' frame, in the body frame), with
1103    /// `filtered_radps` its body rates through the gyro low-pass.
1104    fn of(state: &VehicleState, frame: &UnitQuaternion<f32>, filtered_radps: Vec3) -> Self {
1105        // The view as `VehicleState::rotate_body` builds it, without cloning the state.
1106        let (roll, pitch, _) = euler_angles(&(state.attitude * frame));
1107        let raw_radps = frame.inverse_transform_vector(&state.angular_velocity_radps);
1108        let filtered_radps = frame.inverse_transform_vector(&filtered_radps);
1109        Self {
1110            tilt_rad: roll.abs().max(pitch.abs()),
1111            rate_radps: raw_radps.amax(),
1112            tilt_rate_radps: filtered_radps.xy().amax(),
1113            axis_tilt_rad: [roll.abs(), pitch.abs()],
1114            axis_rate_radps: [filtered_radps.x.abs(), filtered_radps.y.abs()],
1115            yaw_rate_radps: filtered_radps.z.abs(),
1116            altitude_m: state.position_m.z,
1117        }
1118    }
1119}
1120
1121/// Why a stage failed.
1122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1123pub enum AutotuneAbort {
1124    /// Roll or pitch passed [`Envelope::max_tilt_rad`].
1125    Tilt,
1126    /// A body rate passed [`Envelope::max_rate_radps`].
1127    Rate,
1128    /// The vehicle sank more than [`Envelope::max_altitude_loss_m`].
1129    AltitudeLoss,
1130    /// The vehicle didn't settle within [`Envelope::settle_timeout_s`].
1131    NotSettled,
1132    /// Too many clipped steps in a row ([`StepTestPlan::max_invalid`]).
1133    Invalid,
1134    /// Too many steps in a row during which the host stalled
1135    /// ([`StepTestPlan::max_stalled`]): it can't keep time for a measurement.
1136    Stalled,
1137    /// The probe gave up.
1138    Probe(ProbeAbort),
1139    /// The stabilizer idled the loop under test (e.g. a rate setpoint), or the probe was
1140    /// stopped from outside.
1141    Interrupted,
1142    /// The stabilizer rejected the tuned config.
1143    Rejected,
1144    /// The design found no gains for the fitted model.
1145    Design(DesignError),
1146    /// The host lost the vehicle for too long to go on: its state stayed stale past
1147    /// [`Envelope::max_stale_s`] (e.g. a simulator link down for seconds), or the host ended
1148    /// the run with [`Autotune::abort`].
1149    HostFault,
1150}
1151
1152/// What an [`Autotune::update`] did, for the caller to log.
1153// `StageDone` carries two step summaries (about 450 bytes); boxing them would allocate, which
1154// core doesn't, and the caller handles one event per tick.
1155#[allow(clippy::large_enum_variant)]
1156#[derive(Clone, Copy, Debug, PartialEq)]
1157#[non_exhaustive]
1158pub enum AutotuneEvent {
1159    /// A stage started: it settles, then probes its loop.
1160    StageStarted(TunedLoop),
1161    /// A probe on the stage's loop finished.
1162    Measured {
1163        /// The probed loop.
1164        target: TunedLoop,
1165        /// What the probe measured.
1166        measurement: Measurement,
1167    },
1168    /// The host's timing spoiled a probe, which runs again: it was stopped as the host
1169    /// turned slow ([`Autotune::set_host_slow`], no measurement), or it finished across a
1170    /// stall ([`Autotune::note_stall`]).
1171    Stalled {
1172        /// The probed loop.
1173        target: TunedLoop,
1174        /// What the probe measured, if it finished; its timing can't be trusted.
1175        measurement: Option<Measurement>,
1176    },
1177    /// A search judged a pair of steps (or its baseline) on a gain.
1178    Tried {
1179        /// The judged loop.
1180        target: TunedLoop,
1181        /// The gains the steps flew.
1182        gains: Gains,
1183        /// Whether they met the criterion.
1184        passed: bool,
1185        /// The valid steps.
1186        steps: StepSummary,
1187    },
1188    /// A stage finished and committed its loop's gains.
1189    StageDone {
1190        /// The tuned loop.
1191        target: TunedLoop,
1192        /// The gains committed for it.
1193        gains: Gains,
1194        /// What the stage did to them.
1195        outcome: Outcome,
1196        /// A step test's valid steps, or a search's verify (invalid ones, which ran again, left
1197        /// out).
1198        steps: Option<StepSummary>,
1199        /// A search's baseline, when flown: its steps at the start gains.
1200        baseline: Option<StepSummary>,
1201    },
1202    /// A search lowered its loop's gains, which started above its `max`, and committed them: the stage settles on them, and
1203    /// they stay if it fails or nothing better passes.
1204    Lowered {
1205        /// The searched loop.
1206        target: TunedLoop,
1207        /// The gains committed.
1208        gains: Gains,
1209    },
1210    /// A design didn't hold the settle on its loop's axis within the settle timeout; the
1211    /// committed gains are back, and the design stage fits again.
1212    Unsettled {
1213        /// The designed loop.
1214        target: TunedLoop,
1215        /// The gains that didn't hold.
1216        gains: Gains,
1217    },
1218    /// A stage failed: the config went back to the last kept one (earlier stages stay, except
1219    /// designs not yet searched), and the run ends.
1220    StageFailed {
1221        /// The loop the stage was for.
1222        target: TunedLoop,
1223        /// Why.
1224        reason: AutotuneAbort,
1225    },
1226    /// Every stage committed; the run is over and its gains stay.
1227    Complete,
1228    /// Disarmed before completion: every stage reverted to the config at
1229    /// [`Autotune::start`].
1230    Reverted,
1231}
1232
1233/// What a finished stage did to its loop's gains.
1234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1235pub enum Outcome {
1236    /// Set them from its measurements.
1237    Tuned,
1238    /// Measured only; they didn't change.
1239    Measured,
1240    /// Designed from a fit: they fly, but a failure puts the loop's kept gains back until its
1241    /// search finishes ([`Method::Design`]).
1242    Designed,
1243    /// Kept no result: the start gains, or the run's ([`SearchPlan`]).
1244    Kept(KeepReason),
1245}
1246
1247/// Why a search kept the start gains.
1248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1249pub enum KeepReason {
1250    /// No gain down to the search's `min` passed.
1251    NoPass,
1252    /// The result flew worse than the start ([`Acceptance`]), or its steps aborted or kept
1253    /// clipping.
1254    Worse,
1255}
1256
1257/// Where a run stands.
1258#[derive(Clone, Copy, Debug, PartialEq)]
1259pub enum AutotuneStatus {
1260    /// Not started.
1261    Idle,
1262    /// Stage `stage` (an index into the plan) is waiting for the vehicle to settle before its
1263    /// next probe.
1264    Settling {
1265        /// The stage.
1266        stage: usize,
1267    },
1268    /// Stage `stage` is probing `target`, or deciding on what a probe measured.
1269    Running {
1270        /// The stage index.
1271        stage: usize,
1272        /// Its loop.
1273        target: TunedLoop,
1274    },
1275    /// Every stage committed.
1276    Complete,
1277    /// Stage `stage` failed; earlier stages stay committed.
1278    Failed {
1279        /// The failed stage's index.
1280        stage: usize,
1281        /// Why.
1282        reason: AutotuneAbort,
1283    },
1284    /// Disarmed before completion; everything reverted.
1285    Reverted,
1286}
1287
1288/// Why [`Autotune::start`] refused.
1289#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1290pub enum StartError {
1291    /// The last tick wasn't armed.
1292    NotArmed,
1293    /// A run is already in progress.
1294    Running,
1295}
1296
1297impl fmt::Display for StartError {
1298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1299        f.write_str(match self {
1300            Self::NotArmed => "not armed",
1301            Self::Running => "already running",
1302        })
1303    }
1304}
1305
1306impl core::error::Error for StartError {}
1307
1308#[derive(Clone, Copy, Debug, PartialEq)]
1309enum Phase {
1310    Idle,
1311    /// Stage `stage` starts on the next update.
1312    Starting {
1313        stage: usize,
1314    },
1315    /// The stage's procedure decides what follows `on`.
1316    Deciding {
1317        stage: usize,
1318        on: Decide,
1319    },
1320    /// Waiting for the vehicle to settle before running `request`.
1321    Settling {
1322        stage: usize,
1323        request: Request,
1324        level_s: f32,
1325        waited_s: f32,
1326    },
1327    /// A probe runs; `candidate`: on gains the procedure asked for, which go back to the
1328    /// committed ones when it ends; `fit`: an identification, which runs through a slow host.
1329    Probing {
1330        stage: usize,
1331        candidate: bool,
1332        fit: bool,
1333    },
1334    /// Candidate `gains` fly until the stage's axis holds the settle on them, or the settle
1335    /// timeout.
1336    Holding {
1337        stage: usize,
1338        gains: Gains,
1339        level_s: f32,
1340        waited_s: f32,
1341    },
1342    /// The last stage committed; the next update reports `Complete`.
1343    Finishing,
1344    Complete,
1345    Failed {
1346        stage: usize,
1347        reason: AutotuneAbort,
1348    },
1349    Reverted,
1350}
1351
1352impl Phase {
1353    /// The stage a run in progress is on; `None` before, between (`Finishing`), and after
1354    /// runs.
1355    fn active_stage(&self) -> Option<usize> {
1356        match *self {
1357            Phase::Starting { stage }
1358            | Phase::Deciding { stage, .. }
1359            | Phase::Settling { stage, .. }
1360            | Phase::Probing { stage, .. }
1361            | Phase::Holding { stage, .. } => Some(stage),
1362            Phase::Idle
1363            | Phase::Finishing
1364            | Phase::Complete
1365            | Phase::Failed { .. }
1366            | Phase::Reverted => None,
1367        }
1368    }
1369}
1370
1371/// What a stage's procedure decides on.
1372#[derive(Clone, Copy, Debug, PartialEq)]
1373enum Decide {
1374    /// The stage's start.
1375    Start,
1376    /// A finished probe's measurement, and whether the host stalled during it.
1377    Measured {
1378        measurement: Measurement,
1379        stalled: bool,
1380    },
1381    /// A probe stopped because the host turned slow, with no measurement.
1382    Stalled,
1383    /// A probe that gave up.
1384    Aborted { abort: ProbeAbort },
1385    /// A probe or a hold on candidate gains that took the vehicle past the envelope.
1386    Breached { reason: AutotuneAbort },
1387    /// A hold ended, `settled` on its candidate or timed out.
1388    Held { settled: bool },
1389}
1390
1391/// A probe a procedure asked for, and the gains to fly it on (`None`: the committed ones).
1392#[derive(Clone, Copy, Debug, PartialEq)]
1393struct Request {
1394    probe: ProbeConfig,
1395    gains: Option<Gains>,
1396}
1397
1398impl Request {
1399    /// Whether the probe starts at the settle timeout rather than fail the stage: a fit only
1400    /// gains excitation from the ringing.
1401    fn starts_anyway(&self) -> bool {
1402        matches!(self.probe, ProbeConfig::Identify(_))
1403    }
1404
1405    /// Whether the probe is a fit, which runs through a slow host: a fit at 223 Hz on the sim
1406    /// (the physics 12% slower than the ticks claim) designs rate P 5–13% lower, and the
1407    /// search climbs from the design (#524).
1408    fn is_fit(&self) -> bool {
1409        matches!(self.probe, ProbeConfig::Identify(_))
1410    }
1411}
1412
1413/// Runs a copter autotune between ticks: each [`StagePlan`]'s procedure decides
1414/// which probes to run on its loop ([`Tunable::start_probe`]) and what gains follow from
1415/// them; the supervisor executes it.
1416///
1417/// - **Start** ([`start`](Self::start)) when armed and hovering; the caller owns the trigger.
1418///   The config and altitude at start are the run's start, what a disarm reverts to.
1419/// - **Settle:** before each probe, the vehicle must hold the method's [`Settle`]
1420///   ([`Method::settle`]), or the [`Envelope`]'s. The settle and the envelope read tilt and
1421///   rates in the frame the probed loops fly ([`Tunable::probe_frame`]), so a tailsitter
1422///   hovering nose up in its view reads level.
1423/// - **Probe and decide:** a finished probe's [`Measurement`] goes to the stage's procedure,
1424///   which asks for another probe or finishes with gains for its loop, committed through
1425///   [`set_stabilizer_config`](FlightLoop::set_stabilizer_config); the next stage flies them.
1426///   With [`Method::StepTest`], alternating steps and the gains unchanged; with
1427///   [`Method::Search`], a gain search verified against a baseline
1428///   ([`AutotuneEvent::Tried`] per judgment, the [`Outcome`] in `StageDone`); with
1429///   [`Method::Design`], one fit, the gains designed from it, and a hold on them.
1430/// - **Candidates:** a procedure may ask for a probe on other gains; they go in once the
1431///   vehicle has settled on the committed ones and come out when the probe ends, so only the
1432///   probe flies them. An envelope breach while they fly fails the candidate, not the stage;
1433///   the committed gains then have [`Envelope::recovery_s`] to bring the vehicle back. A
1434///   design stage holds its design instead: it goes in at once and stays only if the vehicle
1435///   settles about the loop's axis on it.
1436/// - **Stalls:** [`note_stall`](Self::note_stall) (a freeze) marks the running probe's
1437///   measurement as untimely, and breaches for [`Envelope::recovery_s`] after it fail nothing:
1438///   the vehicle moved while the host saw nothing. A candidate or a held design still comes
1439///   out on one, as a stall. A step test runs that step again. While the
1440///   host is slow ([`set_host_slow`](Self::set_host_slow)), the running probe stops at once (a
1441///   step held for its ticks at half the tick rate would tilt twice as far) and counts as
1442///   stalled, and settling waits: it gains no level time and doesn't time out. A design
1443///   stage's fit and hold run through a slow host: it only lowers the design. While the
1444///   vehicle's state is stale ([`set_state_stale`](Self::set_state_stale): the host holds
1445///   the last one it got while the vehicle flies on unseen), every tick is a freeze, so the
1446///   breach excuse runs until [`Envelope::recovery_s`] after the state clears; any running
1447///   probe, fit included, stops as stalled, and settling and holds wait. Stale past
1448///   [`Envelope::max_stale_s`], the stage fails [`HostFault`](AutotuneAbort::HostFault).
1449/// - **Fail:** an envelope breach, a probe abort the procedure can't use (a search counts a
1450///   step's abort against its gain), an interrupt, or a rejected config stops the stage, puts
1451///   back the config as of the last kept stage (the earlier stages' gains stay, but a design
1452///   counts only once its loop's search finishes), and ends the run.
1453/// - **Disarm** before completion reverts every stage to the run's start.
1454/// - **Complete:** the gains stay; read them from the stabilizer's config.
1455///
1456/// The procedures are pure (they see measurements and gains, never the loop), so the
1457/// supervisor alone flies, guards, and commits. [`update`](Self::update) returns an
1458/// [`AutotuneEvent`] when something happens, for the caller to log; the supervisor has no
1459/// clock (the caller passes `dt`) and does no I/O.
1460///
1461/// # Examples
1462///
1463/// ```no_run
1464/// # use stable_flight::FlightLoop;
1465/// # use stable_flight::stabilizers::copter::CopterStabilizer;
1466/// # use stable_flight::guidance::copter::CopterGuidance;
1467/// # use stable_flight::mixers::TableMixer;
1468/// # use stable_flight::testing::{ConstantCommander, NullVehicle};
1469/// use stable_flight::tuning::autotune::{Autotune, AutotuneEvent, Envelope, StagePlan};
1470///
1471/// # fn fly(flight_loop: &mut FlightLoop<ConstantCommander, NullVehicle, CopterGuidance, CopterStabilizer, TableMixer<4>, ()>) {
1472/// let mut autotune = Autotune::new(&StagePlan::copter_design_search(), Envelope::default())
1473///     .expect("valid plan");
1474/// autotune.start(flight_loop).expect("armed");
1475/// loop {
1476///     flight_loop.step(std::time::Duration::from_millis(4));
1477///     if let Some(event) = autotune.update(flight_loop, 0.004) {
1478///         println!("{event:?}");
1479///         if matches!(event, AutotuneEvent::Complete | AutotuneEvent::Reverted) {
1480///             break;
1481///         }
1482///     }
1483/// }
1484/// # }
1485/// ```
1486#[derive(Clone, Debug, PartialEq)]
1487pub struct Autotune {
1488    plan: [Option<StagePlan>; MAX_STAGES],
1489    stages: usize,
1490    envelope: Envelope,
1491    phase: Phase,
1492    /// The current stage's procedure.
1493    procedure: Procedure,
1494    /// The config at start: what a disarm reverts to.
1495    run_start: Option<CopterStabilizerConfig>,
1496    /// The config as of the last kept stage: what a failure reverts to. A design isn't kept
1497    /// until its loop's search finishes.
1498    last_good: Option<CopterStabilizerConfig>,
1499    /// The config flown between probes: `last_good` plus designs awaiting their search. A
1500    /// candidate goes back to it.
1501    committed: Option<CopterStabilizerConfig>,
1502    start_altitude_m: f32,
1503    /// The host stalled during the running probe ([`note_stall`](Self::note_stall)).
1504    stalled: bool,
1505    /// The host runs slow ([`set_host_slow`](Self::set_host_slow)).
1506    host_slow: bool,
1507    /// The vehicle's state is stale ([`set_state_stale`](Self::set_state_stale)).
1508    state_stale: bool,
1509    /// How long, in s, the state has been stale.
1510    stale_s: f32,
1511    /// Time left, in s, for the vehicle to come back inside the envelope after a candidate
1512    /// ([`Envelope::recovery_s`]); breaches meanwhile don't fail the stage.
1513    recovering_s: f32,
1514    /// Time left, in s, after a freeze ([`note_stall`](Self::note_stall)) during which
1515    /// breaches don't count at all ([`Envelope::recovery_s`]).
1516    frozen_s: f32,
1517    /// The body rates (roll, pitch, yaw) through the stabilizer's gyro low-pass, for the
1518    /// settle ([`Motion`] turns them into the probed loops' frame): a copy of the stabilizer's
1519    /// filter, at its cutoff, since the stabilizer's own sits behind every
1520    /// [`View`](crate::view::View) and VTOL host. Filtering before the rotation is the same
1521    /// as after: every axis has the same cutoff.
1522    rate_filters: [LowPass; 3],
1523}
1524
1525/// What the supervisor needs from the stabilizer: copter probes and config.
1526pub trait CopterTunable:
1527    Tunable<Target = TunedLoop> + Configurable<Config = CopterStabilizerConfig>
1528{
1529}
1530
1531impl<S> CopterTunable for S where
1532    S: Tunable<Target = TunedLoop> + Configurable<Config = CopterStabilizerConfig>
1533{
1534}
1535
1536impl Autotune {
1537    /// A supervisor for `plan` (1 to [`MAX_STAGES`] stages) within `envelope`.
1538    ///
1539    /// # Errors
1540    ///
1541    /// When the plan is empty or too long (`plan`), a stage's method is invalid
1542    /// (`plan.<method>`, e.g. `plan.search`; [`Method::validate`]), or the envelope is
1543    /// (`envelope`).
1544    pub fn new(plan: &[StagePlan], envelope: Envelope) -> Result<Self, InvalidConfig> {
1545        check(
1546            "stages",
1547            (1..=MAX_STAGES).contains(&plan.len()),
1548            "1 to MAX_STAGES",
1549        )
1550        .map_err(|e| e.in_section("plan"))?;
1551        let Some(first) = plan.first() else {
1552            unreachable!("the plan was checked non-empty above");
1553        };
1554        for stage in plan {
1555            stage
1556                .method
1557                .validate()
1558                .map_err(|e| e.in_section(stage.method.plan_section()))?;
1559        }
1560        envelope.validate().map_err(|e| e.in_section("envelope"))?;
1561        for settle in plan.iter().filter_map(|stage| stage.method.settle()) {
1562            envelope
1563                .check_settle(&settle)
1564                .map_err(|e| e.in_section("plan"))?;
1565        }
1566
1567        let mut stages = [None; MAX_STAGES];
1568        for (slot, stage) in stages.iter_mut().zip(plan) {
1569            *slot = Some(*stage);
1570        }
1571        Ok(Self {
1572            plan: stages,
1573            stages: plan.len(),
1574            envelope,
1575            phase: Phase::Idle,
1576            procedure: Procedure::new(first.method),
1577            run_start: None,
1578            last_good: None,
1579            committed: None,
1580            start_altitude_m: 0.0,
1581            stalled: false,
1582            host_slow: false,
1583            state_stale: false,
1584            stale_s: 0.0,
1585            recovering_s: 0.0,
1586            frozen_s: 0.0,
1587            rate_filters: Default::default(),
1588        })
1589    }
1590
1591    /// Starts a run: records the stabilizer's config and the altitude as the run's start; the
1592    /// first stage starts on the next update. A finished run can be started again.
1593    ///
1594    /// # Errors
1595    ///
1596    /// [`StartError::NotArmed`] unless the last tick was armed; [`StartError::Running`]
1597    /// while a run is in progress.
1598    pub fn start<C, V, G, S: CopterTunable, M, T>(
1599        &mut self,
1600        flight_loop: &FlightLoop<C, V, G, S, M, T>,
1601    ) -> Result<(), StartError> {
1602        if self.is_running() {
1603            return Err(StartError::Running);
1604        }
1605        if !flight_loop.armed() {
1606            return Err(StartError::NotArmed);
1607        }
1608        let config = *flight_loop.stabilizer().config();
1609        self.run_start = Some(config);
1610        self.last_good = Some(config);
1611        self.committed = Some(config);
1612        self.start_altitude_m = flight_loop.state().position_m.z;
1613        self.recovering_s = 0.0;
1614        self.frozen_s = 0.0;
1615        self.rate_filters = Default::default();
1616        self.phase = Phase::Starting { stage: 0 };
1617        Ok(())
1618    }
1619
1620    /// Advances the run by `dt` seconds; call it between ticks (after
1621    /// [`step`](FlightLoop::step)). Returns what happened, if anything: at most one event per
1622    /// call.
1623    ///
1624    /// In order: a finished run reports [`Complete`](AutotuneEvent::Complete); a disarm
1625    /// reverts everything; an envelope breach fails the stage; then the run starts a stage,
1626    /// lets its procedure decide, settles, or polls the running probe.
1627    pub fn update<C, V, G, S: CopterTunable, M, T>(
1628        &mut self,
1629        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
1630        dt: f32,
1631    ) -> Option<AutotuneEvent> {
1632        if !self.is_running() {
1633            return None;
1634        }
1635        if self.phase == Phase::Finishing {
1636            self.phase = Phase::Complete;
1637            return Some(AutotuneEvent::Complete);
1638        }
1639        if !flight_loop.armed() {
1640            flight_loop.stop_probe();
1641            if let Some(run_start) = self.run_start {
1642                restore(flight_loop, run_start);
1643            }
1644            self.phase = Phase::Reverted;
1645            return Some(AutotuneEvent::Reverted);
1646        }
1647        if self.state_stale {
1648            self.stale_s += dt;
1649            self.note_stall();
1650            if self.stale_s > self.envelope.max_stale_s
1651                && let Some(stage) = self.phase.active_stage()
1652            {
1653                return Some(self.fail(flight_loop, stage, AutotuneAbort::HostFault));
1654            }
1655        } else {
1656            self.stale_s = 0.0;
1657        }
1658        let rates_radps = self.filter_rates(flight_loop, dt);
1659        let frame = flight_loop.stabilizer().probe_frame();
1660        let motion = Motion::of(flight_loop.state(), &frame, rates_radps);
1661        self.recovering_s = (self.recovering_s - dt).max(0.0);
1662        self.frozen_s = (self.frozen_s - dt).max(0.0);
1663        if let Some(stage) = self.phase.active_stage()
1664            && let Some(reason) = self.envelope.breach(&motion, self.start_altitude_m)
1665        {
1666            // A breach after a freeze is the loop catching up with what the vehicle did
1667            // unseen: on QuadCopterX in RealFlight, 0.47 s of the same state came back at −19°
1668            // pitch, and the recovery peaked at 4.08 rad/s (#524). It fails nothing, but a
1669            // candidate or a held design still comes out, as a stall: unjudged, run again.
1670            let frozen = self.frozen_s > 0.0;
1671            let on = if frozen {
1672                Decide::Stalled
1673            } else {
1674                Decide::Breached { reason }
1675            };
1676            let stalled = frozen.then(|| AutotuneEvent::Stalled {
1677                target: self.target(stage),
1678                measurement: None,
1679            });
1680            // A candidate's breach fails the candidate; the committed gains get time to
1681            // recover from it before a breach fails the stage.
1682            if let Phase::Probing {
1683                candidate: true, ..
1684            } = self.phase
1685            {
1686                self.end_probe(flight_loop, stage, true, on);
1687                return stalled;
1688            }
1689            if let Phase::Holding { .. } = self.phase {
1690                self.end_hold(flight_loop, stage, on);
1691                return stalled;
1692            }
1693            if !frozen && self.recovering_s <= 0.0 {
1694                return Some(self.fail(flight_loop, stage, reason));
1695            }
1696        }
1697        match self.phase {
1698            Phase::Starting { stage } => self.begin(stage),
1699            Phase::Deciding { stage, on } => self.decide(flight_loop, stage, on),
1700            // A slow host holds a probe's settle where it is, with no level time: the vehicle
1701            // settles again once the host keeps time. A fit's goes on, but not on a stale
1702            // state, which shows a vehicle that isn't there.
1703            Phase::Settling {
1704                stage,
1705                request,
1706                waited_s,
1707                ..
1708            } if (self.host_slow && !request.is_fit()) || self.state_stale => {
1709                self.phase = Phase::Settling {
1710                    stage,
1711                    request,
1712                    level_s: 0.0,
1713                    waited_s,
1714                };
1715                None
1716            }
1717            Phase::Probing {
1718                stage,
1719                candidate,
1720                fit,
1721            } if (self.host_slow && !fit) || self.state_stale => {
1722                self.end_probe(flight_loop, stage, candidate, Decide::Stalled);
1723                Some(AutotuneEvent::Stalled {
1724                    target: self.target(stage),
1725                    measurement: None,
1726                })
1727            }
1728            Phase::Settling {
1729                stage,
1730                request,
1731                level_s,
1732                waited_s,
1733            } => self.settle(
1734                flight_loop,
1735                &motion,
1736                (stage, request),
1737                level_s + dt,
1738                waited_s + dt,
1739            ),
1740            Phase::Probing {
1741                stage, candidate, ..
1742            } => self.poll_probe(flight_loop, stage, candidate),
1743            Phase::Holding {
1744                stage,
1745                gains,
1746                waited_s,
1747                ..
1748            } if self.state_stale => {
1749                self.phase = Phase::Holding {
1750                    stage,
1751                    gains,
1752                    level_s: 0.0,
1753                    waited_s,
1754                };
1755                None
1756            }
1757            Phase::Holding {
1758                stage,
1759                gains,
1760                level_s,
1761                waited_s,
1762            } => self.hold(
1763                flight_loop,
1764                &motion,
1765                (stage, gains),
1766                level_s + dt,
1767                waited_s + dt,
1768            ),
1769            Phase::Idle
1770            | Phase::Finishing
1771            | Phase::Complete
1772            | Phase::Failed { .. }
1773            | Phase::Reverted => None,
1774        }
1775    }
1776
1777    /// The state's body rates through the stabilizer's gyro low-pass at its configured cutoff,
1778    /// stepped `dt` on.
1779    fn filter_rates<C, V, G, S: CopterTunable, M, T>(
1780        &mut self,
1781        flight_loop: &FlightLoop<C, V, G, S, M, T>,
1782        dt: f32,
1783    ) -> Vec3 {
1784        let cutoff_hz = flight_loop.stabilizer().config().gyro_cutoff_hz;
1785        let rates_radps = flight_loop.state().angular_velocity_radps;
1786        Vec3::from_fn(|axis, _| self.rate_filters[axis].apply(rates_radps[axis], dt, cutoff_hz))
1787    }
1788
1789    /// Tells the supervisor whether the host runs slow: its ticks come further apart than
1790    /// their `dt`, for a stretch (e.g. RealFlight at half its rate, sitl's `TickRate`). While
1791    /// it does, a running probe stops and runs again later, and settling waits (see the
1792    /// type's **Stalls**). Takes effect on the next [`update`](Self::update).
1793    pub fn set_host_slow(&mut self, slow: bool) {
1794        self.host_slow = slow;
1795    }
1796
1797    /// Tells the supervisor whether the vehicle's state is stale: the host holds the last
1798    /// state it got (e.g. a simulator link down awaiting a reconnect) while the vehicle flies
1799    /// on unseen, so the first fresh state can jump. While it is, the run waits and every
1800    /// tick is a freeze ([`note_stall`](Self::note_stall)); past
1801    /// [`Envelope::max_stale_s`] the stage fails [`HostFault`](AutotuneAbort::HostFault) (see
1802    /// the type's **Stalls**). Takes effect on the next [`update`](Self::update).
1803    pub fn set_state_stale(&mut self, stale: bool) {
1804        self.state_stale = stale;
1805    }
1806
1807    /// Tells the supervisor the host froze (e.g. a stalled simulator exchange, a tick
1808    /// much later than the last): the running probe's timing can't be trusted,
1809    /// so its procedure treats the measurement as invalid, and for [`Envelope::recovery_s`]
1810    /// breaches don't count, as the loop catches up with what the vehicle did meanwhile.
1811    pub fn note_stall(&mut self) {
1812        if matches!(self.phase, Phase::Probing { .. }) {
1813            self.stalled = true;
1814        }
1815        if self.is_running() {
1816            self.frozen_s = self.envelope.recovery_s;
1817        }
1818    }
1819
1820    /// Ends the run from outside for `reason` (e.g. [`AutotuneAbort::HostFault`]), as a
1821    /// breach would: stops the running probe, puts back the config as of the last kept stage,
1822    /// and reports `StageFailed`. `None`, changing nothing, when no stage is active (idle,
1823    /// finishing, or already ended).
1824    ///
1825    /// # Examples
1826    ///
1827    /// ```no_run
1828    /// # use stable_flight::FlightLoop;
1829    /// # use stable_flight::stabilizers::copter::CopterStabilizer;
1830    /// # use stable_flight::guidance::copter::CopterGuidance;
1831    /// # use stable_flight::mixers::TableMixer;
1832    /// # use stable_flight::testing::{ConstantCommander, NullVehicle};
1833    /// use stable_flight::tuning::autotune::{Autotune, AutotuneAbort};
1834    ///
1835    /// # fn fly(flight_loop: &mut FlightLoop<ConstantCommander, NullVehicle, CopterGuidance, CopterStabilizer, TableMixer<4>, ()>, autotune: &mut Autotune, link_down_s: f32) {
1836    /// // The host's link to the vehicle has been down for seconds: end the run.
1837    /// if link_down_s > 2.0 {
1838    ///     if let Some(event) = autotune.abort(flight_loop, AutotuneAbort::HostFault) {
1839    ///         println!("{event:?}");
1840    ///     }
1841    /// }
1842    /// # }
1843    /// ```
1844    pub fn abort<C, V, G, S: CopterTunable, M, T>(
1845        &mut self,
1846        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
1847        reason: AutotuneAbort,
1848    ) -> Option<AutotuneEvent> {
1849        let stage = self.phase.active_stage()?;
1850        Some(self.fail(flight_loop, stage, reason))
1851    }
1852
1853    /// Where the run stands.
1854    pub fn status(&self) -> AutotuneStatus {
1855        match self.phase {
1856            Phase::Idle => AutotuneStatus::Idle,
1857            Phase::Starting { stage }
1858            | Phase::Settling { stage, .. }
1859            | Phase::Deciding {
1860                stage,
1861                on: Decide::Start,
1862            } => AutotuneStatus::Settling { stage },
1863            Phase::Probing { stage, .. }
1864            | Phase::Holding { stage, .. }
1865            | Phase::Deciding {
1866                stage,
1867                on:
1868                    Decide::Measured { .. }
1869                    | Decide::Stalled
1870                    | Decide::Aborted { .. }
1871                    | Decide::Breached { .. }
1872                    | Decide::Held { .. },
1873            } => AutotuneStatus::Running {
1874                stage,
1875                target: self.target(stage),
1876            },
1877            Phase::Finishing | Phase::Complete => AutotuneStatus::Complete,
1878            Phase::Failed { stage, reason } => AutotuneStatus::Failed { stage, reason },
1879            Phase::Reverted => AutotuneStatus::Reverted,
1880        }
1881    }
1882
1883    /// Whether a run is in progress (started, not yet complete, failed, or reverted).
1884    pub fn is_running(&self) -> bool {
1885        !matches!(
1886            self.phase,
1887            Phase::Idle | Phase::Complete | Phase::Failed { .. } | Phase::Reverted
1888        )
1889    }
1890
1891    /// Starts `stage` with a fresh procedure, which decides on the next update.
1892    fn begin(&mut self, stage: usize) -> Option<AutotuneEvent> {
1893        let plan = self.stage(stage)?;
1894        self.procedure = Procedure::new(plan.method);
1895        self.phase = Phase::Deciding {
1896            stage,
1897            on: Decide::Start,
1898        };
1899        Some(AutotuneEvent::StageStarted(plan.target))
1900    }
1901
1902    /// Hands the procedure the stage's start or its last probe's result, with the loop's
1903    /// committed gains, and carries out what it asks for; reports a search's verdict.
1904    fn decide<C, V, G, S: CopterTunable, M, T>(
1905        &mut self,
1906        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
1907        stage: usize,
1908        on: Decide,
1909    ) -> Option<AutotuneEvent> {
1910        let config = flight_loop.stabilizer().config();
1911        let target = self.target(stage);
1912        let gains = target.gains(config);
1913        let input = match on {
1914            Decide::Start => Input::Start {
1915                gains,
1916                inner: target.inner().map(|inner| inner.gains(config)),
1917                run_start: self
1918                    .run_start
1919                    .map_or(gains, |run_start| target.gains(&run_start)),
1920                gyro_cutoff_hz: config.gyro_cutoff_hz,
1921            },
1922            Decide::Measured {
1923                measurement,
1924                stalled,
1925            } => Input::Measured {
1926                measurement,
1927                gains,
1928                stalled,
1929            },
1930            Decide::Stalled => Input::Stalled { gains },
1931            Decide::Aborted { abort } => Input::Aborted { abort, gains },
1932            Decide::Breached { reason } => Input::Breached { reason, gains },
1933            Decide::Held { settled } => Input::Held { settled, gains },
1934        };
1935        match self.procedure.next(input) {
1936            Action::Probe {
1937                probe,
1938                gains,
1939                commit,
1940            } => {
1941                let lowered = commit.map(|gains| self.lower(flight_loop, stage, gains));
1942                if let Some(failed @ AutotuneEvent::StageFailed { .. }) = lowered {
1943                    return Some(failed);
1944                }
1945                self.phase = Phase::Settling {
1946                    stage,
1947                    request: Request { probe, gains },
1948                    level_s: 0.0,
1949                    waited_s: 0.0,
1950                };
1951                let tried = self
1952                    .procedure
1953                    .take_verdict()
1954                    .map(|verdict| AutotuneEvent::Tried {
1955                        target: self.target(stage),
1956                        gains: verdict.gains,
1957                        passed: verdict.passed,
1958                        steps: verdict.steps,
1959                    });
1960                lowered.or(tried)
1961            }
1962            Action::Finish {
1963                gains,
1964                outcome,
1965                steps,
1966                baseline,
1967            } => Some(self.commit(flight_loop, stage, gains, (outcome, steps, baseline))),
1968            Action::Hold { gains } => {
1969                if self.set_gains(flight_loop, stage, gains).is_none() {
1970                    return Some(self.fail(flight_loop, stage, AutotuneAbort::Rejected));
1971                }
1972                self.phase = Phase::Holding {
1973                    stage,
1974                    gains,
1975                    level_s: 0.0,
1976                    waited_s: 0.0,
1977                };
1978                None
1979            }
1980            Action::Fail(reason) => Some(self.fail(flight_loop, stage, reason)),
1981        }
1982    }
1983
1984    /// Waits for the vehicle to hold the stage's [`Settle`] (`level_s` counts it, restarting
1985    /// when it moves), then sets the request's gains, if any, and starts its probe for
1986    /// `stage`; fails after `settle_timeout_s`, except an identification, which starts then
1987    /// instead: a fit only gains excitation from the ringing.
1988    fn settle<C, V, G, S: CopterTunable, M, T>(
1989        &mut self,
1990        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
1991        motion: &Motion,
1992        (stage, request): (usize, Request),
1993        level_s: f32,
1994        waited_s: f32,
1995    ) -> Option<AutotuneEvent> {
1996        let settle = self.settle_for(stage);
1997        let holds = settle.holds_for(motion, self.target(stage));
1998        let level_s = if holds { level_s } else { 0.0 };
1999        let timed_out = waited_s >= self.envelope.settle_timeout_s;
2000        if level_s >= settle.hold_s || (request.starts_anyway() && timed_out) {
2001            if let Some(gains) = request.gains
2002                && self.set_gains(flight_loop, stage, gains).is_none()
2003            {
2004                return Some(self.fail(flight_loop, stage, AutotuneAbort::Rejected));
2005            }
2006            let probed = probed_loop(self.target(stage), &request.probe);
2007            flight_loop.start_probe(probed, request.probe);
2008            self.phase = Phase::Probing {
2009                stage,
2010                candidate: request.gains.is_some(),
2011                fit: request.is_fit(),
2012            };
2013            self.stalled = false;
2014            return None;
2015        }
2016        if timed_out {
2017            return Some(self.fail(flight_loop, stage, AutotuneAbort::NotSettled));
2018        }
2019        self.phase = Phase::Settling {
2020            stage,
2021            request,
2022            level_s,
2023            waited_s,
2024        };
2025        None
2026    }
2027
2028    /// Checks the running probe: a measurement or an abort goes to the procedure on the next
2029    /// update (a stalled probe's abort as a stall), after a candidate's gains go back to the
2030    /// committed ones; a stopped probe fails the run.
2031    fn poll_probe<C, V, G, S: CopterTunable, M, T>(
2032        &mut self,
2033        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2034        stage: usize,
2035        candidate: bool,
2036    ) -> Option<AutotuneEvent> {
2037        let (on, event) = match flight_loop.probe() {
2038            Some((_, ProbeStatus::Running(_))) => return None,
2039            Some((target, ProbeStatus::Done(measurement))) => (
2040                Decide::Measured {
2041                    measurement,
2042                    stalled: self.stalled,
2043                },
2044                Some(if self.stalled {
2045                    AutotuneEvent::Stalled {
2046                        target,
2047                        measurement: Some(measurement),
2048                    }
2049                } else {
2050                    AutotuneEvent::Measured {
2051                        target,
2052                        measurement,
2053                    }
2054                }),
2055            ),
2056            // A stalled probe's abort is the host's, not the loop's: it runs again.
2057            Some((target, ProbeStatus::Aborted(_))) if self.stalled => (
2058                Decide::Stalled,
2059                Some(AutotuneEvent::Stalled {
2060                    target,
2061                    measurement: None,
2062                }),
2063            ),
2064            Some((_, ProbeStatus::Aborted(abort))) => (Decide::Aborted { abort }, None),
2065            Some((_, ProbeStatus::Interrupted)) | None => {
2066                return Some(self.fail(flight_loop, stage, AutotuneAbort::Interrupted));
2067            }
2068        };
2069        self.end_probe(flight_loop, stage, candidate, on);
2070        event
2071    }
2072
2073    /// Stops `stage`'s probe and hands `on` to its procedure on the next update; a
2074    /// candidate's gains go back to the committed ones, which get [`Envelope::recovery_s`] to
2075    /// bring the vehicle back inside the envelope.
2076    fn end_probe<C, V, G, S: CopterTunable, M, T>(
2077        &mut self,
2078        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2079        stage: usize,
2080        candidate: bool,
2081        on: Decide,
2082    ) {
2083        flight_loop.stop_probe();
2084        if candidate && let Some(committed) = self.committed {
2085            restore(flight_loop, committed);
2086            self.recovering_s = self.envelope.recovery_s;
2087        }
2088        self.phase = Phase::Deciding { stage, on };
2089    }
2090
2091    /// Waits for the vehicle to hold the stage's [`Settle`] about its loop's axis on the
2092    /// candidate `gains` (`level_s` counts it): then they stay for the procedure to commit.
2093    /// After `settle_timeout_s` the committed gains go back ([`AutotuneEvent::Unsettled`]).
2094    /// For a roll or pitch loop only its axis counts: the other may still ring on its start
2095    /// gains (pitch on `racer`'s high start with 25 ms of delay, #518). A yaw rate or heading
2096    /// loop needs both level and yaw still.
2097    fn hold<C, V, G, S: CopterTunable, M, T>(
2098        &mut self,
2099        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2100        motion: &Motion,
2101        (stage, gains): (usize, Gains),
2102        level_s: f32,
2103        waited_s: f32,
2104    ) -> Option<AutotuneEvent> {
2105        let settle = self.settle_for(stage);
2106        let target = self.target(stage);
2107        let holds = tilt_axis(target).map_or_else(
2108            || settle.holds_yaw(motion),
2109            |axis| settle.holds_axis(motion, axis),
2110        );
2111        let level_s = if holds { level_s } else { 0.0 };
2112        if level_s >= settle.hold_s {
2113            self.phase = Phase::Deciding {
2114                stage,
2115                on: Decide::Held { settled: true },
2116            };
2117            return None;
2118        }
2119        if waited_s >= self.envelope.settle_timeout_s {
2120            self.end_hold(flight_loop, stage, Decide::Held { settled: false });
2121            return Some(AutotuneEvent::Unsettled { target, gains });
2122        }
2123        self.phase = Phase::Holding {
2124            stage,
2125            gains,
2126            level_s,
2127            waited_s,
2128        };
2129        None
2130    }
2131
2132    /// Ends `stage`'s hold: the committed gains go back, with [`Envelope::recovery_s`] to
2133    /// bring the vehicle inside the envelope, and `on` goes to the procedure.
2134    fn end_hold<C, V, G, S: CopterTunable, M, T>(
2135        &mut self,
2136        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2137        stage: usize,
2138        on: Decide,
2139    ) {
2140        if let Some(committed) = self.committed {
2141            restore(flight_loop, committed);
2142            self.recovering_s = self.envelope.recovery_s;
2143        }
2144        self.phase = Phase::Deciding { stage, on };
2145    }
2146
2147    /// The settle before `stage`'s probes: its method's, or the envelope's.
2148    fn settle_for(&self, stage: usize) -> Settle {
2149        self.stage(stage)
2150            .and_then(|plan| plan.method.settle())
2151            .unwrap_or(self.envelope.settle)
2152    }
2153
2154    fn stage(&self, stage: usize) -> Option<StagePlan> {
2155        self.plan.get(stage).copied().flatten()
2156    }
2157
2158    /// The target of `stage`; `stage` is always in the plan (the phases only hold indices
2159    /// below `stages`).
2160    fn target(&self, stage: usize) -> TunedLoop {
2161        self.stage(stage)
2162            .map_or(TunedLoop::RollRate, |plan| plan.target)
2163    }
2164
2165    /// Commits `gains` lowered mid-stage (a search's start above its `max`): the stage
2166    /// settles on them, and a failure restores them if the stage started on the loop's kept
2167    /// gains. A lowered design is still a design: a failure puts the loop's kept gains back.
2168    /// `StageFailed` if the stabilizer rejected them, else `Lowered`.
2169    fn lower<C, V, G, S: CopterTunable, M, T>(
2170        &mut self,
2171        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2172        stage: usize,
2173        gains: Gains,
2174    ) -> AutotuneEvent {
2175        let target = self.target(stage);
2176        let designed = self
2177            .committed
2178            .zip(self.last_good)
2179            .is_some_and(|(flown, kept)| target.gains(&flown) != target.gains(&kept));
2180        let Some(config) = self.set_gains(flight_loop, stage, gains) else {
2181            return self.fail(flight_loop, stage, AutotuneAbort::Rejected);
2182        };
2183        self.committed = Some(config);
2184        if !designed {
2185            self.keep(target, gains);
2186        }
2187        AutotuneEvent::Lowered {
2188            target: self.target(stage),
2189            gains,
2190        }
2191    }
2192
2193    /// Commits a finished stage's gains and moves on. A design is flown but not yet kept: a
2194    /// failure before its loop's search puts the loop's earlier gains back. Any other stage
2195    /// keeps its loop's gains, and only those: other loops' designs still wait on their own.
2196    fn commit<C, V, G, S: CopterTunable, M, T>(
2197        &mut self,
2198        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2199        stage: usize,
2200        gains: Gains,
2201        (outcome, steps, baseline): (Outcome, Option<StepSummary>, Option<StepSummary>),
2202    ) -> AutotuneEvent {
2203        let Some(config) = self.set_gains(flight_loop, stage, gains) else {
2204            return self.fail(flight_loop, stage, AutotuneAbort::Rejected);
2205        };
2206        self.committed = Some(config);
2207        if outcome != Outcome::Designed {
2208            self.keep(self.target(stage), gains);
2209        }
2210        self.phase = if stage + 1 < self.stages {
2211            Phase::Starting { stage: stage + 1 }
2212        } else {
2213            Phase::Finishing
2214        };
2215        AutotuneEvent::StageDone {
2216            target: self.target(stage),
2217            gains,
2218            outcome,
2219            steps,
2220            baseline,
2221        }
2222    }
2223
2224    /// Sets `gains` on `stage`'s loop; the config flown, or `None` if the stabilizer
2225    /// rejected it.
2226    fn set_gains<C, V, G, S: CopterTunable, M, T>(
2227        &self,
2228        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2229        stage: usize,
2230        gains: Gains,
2231    ) -> Option<CopterStabilizerConfig> {
2232        let mut config = *flight_loop.stabilizer().config();
2233        *self.target(stage).gains_mut(&mut config) = gains;
2234        flight_loop
2235            .set_stabilizer_config(config)
2236            .ok()
2237            .map(|()| config)
2238    }
2239
2240    /// Keeps `target`'s `gains` in what a failure reverts to, leaving the other loops as kept.
2241    fn keep(&mut self, target: TunedLoop, gains: Gains) {
2242        if let Some(kept) = &mut self.last_good {
2243            *target.gains_mut(kept) = gains;
2244        }
2245    }
2246
2247    /// Ends the run at `stage`: stops its probe and puts back the config as of the last kept
2248    /// stage.
2249    fn fail<C, V, G, S: CopterTunable, M, T>(
2250        &mut self,
2251        flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2252        stage: usize,
2253        reason: AutotuneAbort,
2254    ) -> AutotuneEvent {
2255        flight_loop.stop_probe();
2256        if let Some(last_good) = self.last_good {
2257            restore(flight_loop, last_good);
2258        }
2259        self.committed = self.last_good;
2260        self.phase = Phase::Failed { stage, reason };
2261        AutotuneEvent::StageFailed {
2262            target: self.target(stage),
2263            reason,
2264        }
2265    }
2266}
2267
2268/// The loop `probe` runs on for a stage on `target`: an identification excites an angle
2269/// loop's axis on the rate loop under it ([`DesignPlan`]); every other probe runs on `target`
2270/// itself.
2271fn probed_loop(target: TunedLoop, probe: &ProbeConfig) -> TunedLoop {
2272    match probe {
2273        ProbeConfig::Identify(_) => target.inner().unwrap_or(target),
2274        ProbeConfig::Step(_) => target,
2275    }
2276}
2277
2278/// The tilt axis `target` holds (0 roll, 1 pitch); `None` for yaw and heading.
2279fn tilt_axis(target: TunedLoop) -> Option<usize> {
2280    match target {
2281        TunedLoop::RollRate | TunedLoop::Roll => Some(0),
2282        TunedLoop::PitchRate | TunedLoop::Pitch => Some(1),
2283        TunedLoop::YawRate | TunedLoop::Heading => None,
2284    }
2285}
2286
2287/// Puts back a config the stabilizer flew before. It was valid then and validation doesn't
2288/// change between calls, so it can't be rejected.
2289fn restore<C, V, G, S: CopterTunable, M, T>(
2290    flight_loop: &mut FlightLoop<C, V, G, S, M, T>,
2291    config: CopterStabilizerConfig,
2292) {
2293    let _ = flight_loop.set_stabilizer_config(config);
2294}