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