Skip to main content

stable_flight/tuning/
identify.rs

1//! Closed-loop identification of a rate axis: see [`IdentifyProbe`].
2//!
3//! Flies the excitation PX4's autotune flies (`mc_autotune_attitude_control`'s
4//! `getIdentificationSignal`, added to the rate setpoint by `mc_att_control`), described, not
5//! copied: a washed-out square wave whose half-periods shrink. PX4 fits a second-order model by
6//! recursive least squares on the measured rate (`ArxRls` in `system_identification`); in
7//! closed loop the controller feeds gyro noise into the moment, and that fit reads every lag as
8//! 0 under the sim's noise. This probe keeps a least-squares fit on the recorded moments for a
9//! quiet window, and fits a noisy one, excited longer and harder, with both sides integrated
10//! instead (`docs/architecture/autotune-design-search.md#identify`, #551, #603).
11
12use nalgebra::{Complex, SMatrix, SVector};
13
14use crate::controllers::{InvalidConfig, check, check_positive};
15use crate::math::{assert_dt, lagged};
16
17#[cfg(test)]
18mod tests;
19
20/// Longest delay the fit tries, in ticks: 40 ms at 250 Hz, past the sim's 25 ms actuator delay
21/// (7 ticks with the hold).
22pub const MAX_DELAY_TICKS: usize = 10;
23
24/// Share of the window's moments at the rate loop's limit past which a noisy window aborts
25/// rather than taking [`fit_integrated`]: a moment clipped at ±1 isn't the moment the airframe
26/// felt, and the copter's ×3 starts ring there for 510–629 of 750 ticks; the low starts and
27/// RealFlight's QuadCopterX don't saturate at all (#551). A quiet window keeps
28/// [`fit_recorded`], which is exact on a clipped moment too.
29const SATURATED_SHARE: f32 = 0.2;
30
31/// A moment at or past this magnitude counts as at the rate loop's ±1 limit.
32const SATURATED_MOMENT: f32 = 0.999;
33
34/// The least-squares fit's residual, RMS per tick in rad/s, past which the window counts as
35/// noisy: the least squares then doesn't explain it, which is gyro noise read through the
36/// closed loop, and the probe extends the window ([`IdentifyConfig::noisy`]) and fits it with
37/// [`fit_integrated`]. Below it the least squares is exact and stays. RealFlight's windows
38/// leave 0.002–0.012 (eXplora and QuadCopterX, 8 windows), the sim eXplora with 0.01 rad/s of
39/// gyro noise 0.012, and the sim's noise rows 0.024–0.100. A clean sim window leaves under
40/// 0.001 whatever its gains, a loop that rings included (#551).
41const NOISY_RESIDUAL_RADPS: f32 = 0.017;
42
43/// Ticks of rate, moment, and excitation the probe records: 8.2 s at 250 Hz, past the copter's
44/// 8 s noisy window. A longer window fits its first `WINDOW_CAPACITY` ticks.
45const WINDOW_CAPACITY: usize = 2048;
46
47/// Time constant, in s, of the leaky integrator [`fit_integrated`] runs both sides of its fit
48/// through. Integrated, the target's gyro noise is mostly the current tick's, which no moment
49/// commanded before it carries; per tick, the rate's change holds the last tick's noise too,
50/// which the moment one tick on answered, and that fit read `quad_x`'s 10 ms delay as 1 to 8
51/// ticks (rate P up to 2.3× the noise-free design's). Longer integrates more of the slow rate
52/// drift into the target: at 0.1 and 0.2 s the delay read 3–4 ticks on every copter over 5
53/// seeds, at 0.4 s some read 2, with rate P to 1.6× (#603).
54const INTEGRATION_TC_S: f32 = 0.1;
55
56/// The lag grid [`fit_integrated`] searches, in s: 0, then `MIN_LAG_S` up to `MAX_LAG_S` in
57/// steps of `LAG_RATIO`, then [`refine`]s between the best point's neighbors. The top is past
58/// the Alia 250's 0.17 s motors on the sim.
59const MIN_LAG_S: f32 = 0.001;
60const MAX_LAG_S: f32 = 0.5;
61const LAG_RATIO: f32 = 1.05;
62
63/// The square wave's half-periods, in s: 1.0 down to 0.2 by 0.1, then 0.6 down to 0.2,
64/// repeating (PX4's sweep, `getIdentificationSignal`).
65fn half_period_s(index: usize) -> f32 {
66    // The first sweep's nine halves, 1.0 down to 0.2 s; then sweeps of five, 0.6 down to 0.2.
67    const FIRST_SWEEP_HALVES: usize = 9;
68    match index {
69        0..FIRST_SWEEP_HALVES => 1.0 - 0.1 * index as f32,
70        _ => 0.6 - 0.1 * ((index - FIRST_SWEEP_HALVES) % 5) as f32,
71    }
72}
73
74/// Residuals within this share of the least count as tied in [`fit_recorded`], and the
75/// shortest such delay wins, so rounding doesn't pick between near-equal delays (a 25 ms delay
76/// fit at 6 or 7 ticks, #516). Wider favors delays too short, which design too hot a loop: on
77/// QuadCopterX in RealFlight, 5% took 1 tick in 6 of 67 fits against 1 at 1%, and in run 35 a
78/// 1-tick pick at 2.2% over the least designed roll rate P 1.79, which rang and failed its
79/// stage (#529). [`fit_integrated`] takes the least alone: gyro noise fills its residual, every
80/// delay sits within 0.05% of the least, and any tie share took the shortest (#603).
81const TIE_SHARE: f32 = 0.01;
82
83/// Configures an [`IdentifyProbe`].
84///
85/// The amplitude is in the probed loop's setpoint units (rad/s on a rate loop), so there is no
86/// `Default`; [`COPTER_IDENTIFY`](crate::tuning::autotune::COPTER_IDENTIFY) is the copter's.
87#[derive(Clone, Copy, Debug, PartialEq)]
88pub struct IdentifyConfig {
89    /// Height of the square wave added to the setpoint, in setpoint units. Non-zero and
90    /// finite: larger moves the vehicle further and lifts the response over noise.
91    pub amplitude: f32,
92    /// How long the axis is excited and recorded, in s. Positive and finite.
93    pub duration_s: f32,
94    /// Time constant of the washout taken off the square wave, in s (PX4: 0.2 s): each edge
95    /// becomes a pulse that decays, so the setpoint offset averages near zero. Positive and
96    /// finite.
97    pub washout_tc_s: f32,
98    /// How an [`IdentifyProbe`] goes on exciting a window that reads noisy at `duration_s`;
99    /// `None` fits it as it stands. A [`WingIdentifyProbe`](crate::tuning::WingIdentifyProbe)
100    /// doesn't extend.
101    pub noisy: Option<IdentifyExtension>,
102}
103
104/// More excitation for a window gyro noise fills: an axis whose noise hides its delay shows it
105/// over a longer window at a larger amplitude.
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct IdentifyExtension {
108    /// Height of the square wave from `duration_s` on, in setpoint units. Non-zero and finite.
109    pub amplitude: f32,
110    /// The window's whole length once extended, in s. Finite and at least the config's
111    /// `duration_s`; the probe records 8.2 s at 250 Hz and fits the first ticks of a longer one.
112    pub duration_s: f32,
113}
114
115impl IdentifyConfig {
116    /// Checks every field's stated requirement.
117    ///
118    /// # Examples
119    ///
120    /// ```
121    /// use stable_flight::tuning::autotune::COPTER_IDENTIFY;
122    /// use stable_flight::tuning::IdentifyConfig;
123    ///
124    /// assert!(COPTER_IDENTIFY.validate().is_ok());
125    /// let bad = IdentifyConfig { duration_s: 0.0, ..COPTER_IDENTIFY };
126    /// assert!(bad.validate().is_err());
127    /// ```
128    pub fn validate(&self) -> Result<(), InvalidConfig> {
129        check(
130            "amplitude",
131            non_zero_finite(self.amplitude),
132            "non-zero and finite",
133        )?;
134        check_positive("duration_s", self.duration_s)?;
135        check_positive("washout_tc_s", self.washout_tc_s)?;
136        let Some(noisy) = self.noisy else {
137            return Ok(());
138        };
139        check(
140            "noisy.amplitude",
141            non_zero_finite(noisy.amplitude),
142            "non-zero and finite",
143        )?;
144        check(
145            "noisy.duration_s",
146            noisy.duration_s.is_finite() && noisy.duration_s >= self.duration_s,
147            "finite and at least duration_s",
148        )
149    }
150}
151
152fn non_zero_finite(value: f32) -> bool {
153    value != 0.0 && value.is_finite()
154}
155
156/// A rate axis's response to its moment command, fitted in flight: the body rate one tick on
157/// from the last two rates and three moments, `delay_ticks` back.
158///
159/// `y[k] = r₁·y[k−1] + r₂·y[k−2] + m₀·u[k−d] + m₁·u[k−d−1] + m₂·u[k−d−2]`, with `y` the body
160/// rate in rad/s, `u` the normalized moment, `r` the [`rate_weights`](Self::rate_weights), `m`
161/// the [`moment_weights`](Self::moment_weights), and `d` the delay. A body that integrates its
162/// moment through one motor lag fits it with `r₁ = 1 + p`, `r₂ = −p`, `p` the lag's pole: the
163/// form [`IdentifyProbe`] fits, its moment on one weight or, half a tick later, two equal ones.
164#[derive(Clone, Copy, Debug, PartialEq)]
165pub struct RateModel {
166    /// Weights of the last two body rates, `y[k−1]` and `y[k−2]`.
167    pub rate_weights: [f32; 2],
168    /// Weights of the moments `u[k−d]`, `u[k−d−1]`, and `u[k−d−2]`.
169    pub moment_weights: [f32; 3],
170    /// Ticks from a moment command to its first effect on the rate, at least 1.
171    pub delay_ticks: usize,
172    /// The tick the model steps at, in s: the mean `dt` it was fitted over.
173    pub dt_s: f32,
174}
175
176impl RateModel {
177    /// The motor lag's time constant, in s, from its pole `p = −r₂`: `−dt / ln p` for a pole
178    /// in `(0, 1)`. A pole at or below 0 is a lag under a tick, which the delay absorbs, so 0
179    /// (#563). `None` for a pole at or past 1, which grows rather than lags.
180    ///
181    /// # Examples
182    ///
183    /// ```
184    /// use stable_flight::tuning::RateModel;
185    ///
186    /// // A 30 ms lag at 250 Hz: p = e^(−0.004/0.03).
187    /// let p = (-0.004f32 / 0.03).exp();
188    /// let model = RateModel {
189    ///     rate_weights: [1.0 + p, -p],
190    ///     moment_weights: [0.1, 0.0, 0.0],
191    ///     delay_ticks: 1,
192    ///     dt_s: 0.004,
193    /// };
194    /// assert!((model.lag_s().unwrap() - 0.03).abs() < 1e-5);
195    /// ```
196    pub fn lag_s(&self) -> Option<f32> {
197        let pole = -self.rate_weights[1];
198        if pole >= 1.0 || pole.is_nan() {
199            return None;
200        }
201        Some(if pole > 0.0 {
202            -self.dt_s / libm::logf(pole)
203        } else {
204            0.0
205        })
206    }
207
208    /// The model's frequency response at `w_radps`: body rate per unit moment, delay included,
209    /// `(m₀ + m₁·z⁻¹ + m₂·z⁻²)·z⁻ᵈ / (1 − r₁·z⁻¹ − r₂·z⁻²)` at `z⁻¹ = e^(−jω·dt)`. Its phase
210    /// starts near −90° (the body integrates its moment) and falls with the lag and the delay.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use stable_flight::tuning::RateModel;
216    ///
217    /// // An integrator alone, one tick of delay: about 1/(jω) per unit gain.
218    /// let model = RateModel {
219    ///     rate_weights: [1.0, 0.0],
220    ///     moment_weights: [0.004, 0.0, 0.0],
221    ///     delay_ticks: 1,
222    ///     dt_s: 0.004,
223    /// };
224    /// let response = model.response(1.0);
225    /// assert!((response.norm_sqr() - 1.0).abs() < 0.02);
226    /// ```
227    pub fn response(&self, w_radps: f32) -> Complex<f32> {
228        let z1 = unit_delay(w_radps, self.dt_s);
229        let [m0, m1, m2] = self.moment_weights;
230        let [r1, r2] = self.rate_weights;
231        let one = Complex::new(1.0, 0.0);
232        let numerator = (one * m0 + z1 * m1 + z1 * z1 * m2) * z1.powu(self.delay_ticks as u32);
233        numerator / (one - z1 * r1 - z1 * z1 * r2)
234    }
235
236    /// The axis's angular acceleration per unit moment once the lag has settled, in rad/s²:
237    /// the moments' total weight over `(1 − p)·dt`, a pole at or below 0 taken as 0, as
238    /// [`lag_s`](Self::lag_s) takes it. `None` without a lag.
239    pub fn accel_radps2(&self) -> Option<f32> {
240        self.lag_s()?;
241        let pole = (-self.rate_weights[1]).max(0.0);
242        Some(self.moment_effect() / ((1.0 - pole) * self.dt_s))
243    }
244
245    /// The moments' total weight: its sign is the sign of the axis's response to a held moment
246    /// (`accel_radps2` divides it by a positive `(1 − p)·dt`, and the design holds a pole past
247    /// 1 at 1). Negative, the model pushes the axis against the moment commanded.
248    pub(crate) fn moment_effect(&self) -> f32 {
249        self.moment_weights.iter().sum()
250    }
251}
252
253/// `z⁻¹ = e^(−jω·dt)`: one tick's delay at `w_radps`.
254pub(crate) fn unit_delay(w_radps: f32, dt_s: f32) -> Complex<f32> {
255    let angle = -w_radps * dt_s;
256    Complex::new(libm::cosf(angle), libm::sinf(angle))
257}
258
259/// Why an [`IdentifyProbe`] gave up.
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261#[non_exhaustive]
262pub enum IdentifyAbort {
263    /// The fit couldn't be solved: the window was too short, or the excitation didn't move the
264    /// moment enough to tell its terms apart.
265    Unexcited,
266    /// Most of the window's moments sat at the rate loop's limit, and the least squares left
267    /// it noisy: a clipped moment isn't the one the airframe felt, so the integrated fit can't
268    /// read it, and the least squares reads the noise as the airframe. Lower gains unclip it.
269    Saturated,
270}
271
272/// Where an [`IdentifyProbe`] stands.
273#[derive(Clone, Copy, Debug, PartialEq)]
274pub enum IdentifyStatus {
275    /// Exciting and recording.
276    Running {
277        /// Time since the excitation began, in s.
278        elapsed_s: f32,
279    },
280    /// The fitted model.
281    Done(RateModel),
282    /// Gave up.
283    Aborted(IdentifyAbort),
284}
285
286/// Excites one loop with a square wave on its setpoint while recording its axis's body rate and
287/// moment command, then fits a [`RateModel`] to them.
288///
289/// Each tick the host hands it the axis's body rate and the moment it commanded on the last
290/// tick; the probe returns the offset to add to the loop's setpoint. Every loop stays closed, so
291/// the fit sees the airframe through its own controllers.
292///
293/// The fit asks how the moment commanded, through a motor lag and a delay, accelerates the
294/// axis. It first fits the rate's change per tick by least squares to the last two rates and
295/// the recorded moments at each delay from 1 to [`MAX_DELAY_TICKS`], keeping the delay with
296/// the least residual (the shortest of a near-tie) among those whose moment pushes the axis
297/// the way it was pushed (among all when none does). That is exact without noise.
298///
299/// In closed loop, though, the gyro noise is in the measured rate, and the moment carries the
300/// controller's answer to it, so that fit reads the noise as part of the airframe. When it
301/// leaves more than 0.017 rad/s of the rate's change per tick unexplained (RMS), the window is
302/// noisy: the probe goes on exciting it to the config's [`noisy`](IdentifyConfig::noisy)
303/// length and amplitude, then fits it another way. It filters the recorded moment through each
304/// lag on a grid and each delay, half ticks included, and fits the rate to it (a gain and a
305/// constant for the trim), with both sides integrated: the measured rate only the target, so
306/// the noise in it doesn't bend the airframe's terms, and the integration keeps most of the
307/// target's noise out of the moments it's fitted to (a
308/// [leaky integrator](https://github.com/wboayue/stable-flight/blob/main/docs/glossary.md)).
309/// Gyro noise still fills that fit's residual, so the delay with the least residual wins
310/// outright. A noisy window whose moments mostly sit at
311/// the rate loop's limit (a start that rings) aborts, as no fit reads a clipped moment
312/// through noise.
313///
314/// The probe records the window (26 KB) and fits it on the tick the excitation ends. The
315/// least squares costs about 0.1 ms there on a desktop, the integrated fit about 11 ms (128
316/// lags × 20 delays over an 8 s window), so a noisy window's last tick runs long. A non-finite
317/// rate or moment is recorded as the last finite one for the integrated fit; the least squares
318/// skips that tick and the next `MAX_DELAY_TICKS + 2` while its history refills.
319///
320/// # Examples
321///
322/// ```
323/// use stable_flight::tuning::autotune::COPTER_IDENTIFY;
324/// use stable_flight::tuning::{IdentifyProbe, IdentifyStatus};
325///
326/// let mut probe = IdentifyProbe::new(COPTER_IDENTIFY);
327/// // The square wave starts high: the first tick's offset is the step less its washout.
328/// let offset = probe.step(0.004, 0.0, 0.0);
329/// assert!(offset > 0.0 && offset <= COPTER_IDENTIFY.amplitude);
330/// assert!(matches!(probe.status(), IdentifyStatus::Running { .. }));
331/// ```
332#[derive(Clone, Debug, PartialEq)]
333pub struct IdentifyProbe {
334    duration_s: f32,
335    /// The extension still to come; `None` once taken or when there's none.
336    noisy: Option<IdentifyExtension>,
337    status: IdentifyStatus,
338    sweep: SquareSweep,
339    window: Window,
340}
341
342impl IdentifyProbe {
343    /// A probe ready to run.
344    ///
345    /// # Panics
346    ///
347    /// If `config` is invalid ([`IdentifyConfig::validate`]).
348    pub fn new(config: IdentifyConfig) -> Self {
349        if let Err(error) = config.validate() {
350            panic!("invalid IdentifyConfig: {error}");
351        }
352        IdentifyProbe {
353            duration_s: config.duration_s,
354            noisy: config.noisy,
355            status: IdentifyStatus::Running { elapsed_s: 0.0 },
356            sweep: SquareSweep::new(config.amplitude, config.washout_tc_s),
357            window: Window::new(),
358        }
359    }
360
361    /// Advances the probe by `dt` seconds with the axis's body rate this tick (rad/s) and its
362    /// moment command on the last tick, and returns the offset to add to the loop's setpoint
363    /// (0 once it has finished). Fits the model on the tick the excitation ends, past the
364    /// config's `duration_s` when the window reads noisy there.
365    ///
366    /// # Panics
367    ///
368    /// If `dt` is not positive and finite.
369    pub fn step(&mut self, dt: f32, rate_radps: f32, last_moment: f32) -> f32 {
370        assert_dt(dt);
371        let IdentifyStatus::Running { elapsed_s } = self.status else {
372            return 0.0;
373        };
374        let elapsed_s = elapsed_s + dt;
375        let offset = self.sweep.next(dt, elapsed_s);
376        self.window.record(dt, rate_radps, last_moment, offset);
377        self.status = IdentifyStatus::Running { elapsed_s };
378        if elapsed_s < self.duration_s {
379            return offset;
380        }
381        let fit = classify(&self.window);
382        // A noisy window takes the extension, once, before it's fitted.
383        if let (Some(noisy), Ok(Fit::Integrated)) = (self.noisy.take(), fit) {
384            self.duration_s = noisy.duration_s;
385            self.sweep.amplitude = noisy.amplitude;
386            if elapsed_s < self.duration_s {
387                return offset;
388            }
389        }
390        self.status = match fit_classified(&self.window, fit) {
391            Ok(model) => IdentifyStatus::Done(model),
392            Err(abort) => IdentifyStatus::Aborted(abort),
393        };
394        offset
395    }
396
397    /// Where the probe stands.
398    pub fn status(&self) -> IdentifyStatus {
399        self.status
400    }
401}
402
403/// PX4's shrinking square wave ([`half_period_s`]), less its washout: each edge a pulse that
404/// decays over the washout's time constant.
405#[derive(Clone, Copy, Debug, PartialEq)]
406pub(super) struct SquareSweep {
407    amplitude: f32,
408    washout_tc_s: f32,
409    /// When the next edge falls, in s since the start, and its index.
410    next_edge_s: f32,
411    edge: usize,
412    /// Whether the wave is at its amplitude (else 0).
413    high: bool,
414    /// The wave through a low-pass at the washout's time constant, in setpoint units.
415    washout: f32,
416}
417
418impl SquareSweep {
419    pub(super) fn new(amplitude: f32, washout_tc_s: f32) -> Self {
420        SquareSweep {
421            amplitude,
422            washout_tc_s,
423            next_edge_s: half_period_s(0),
424            edge: 0,
425            high: true,
426            washout: 0.0,
427        }
428    }
429
430    /// The offset at `elapsed_s`, `dt` after the last call.
431    pub(super) fn next(&mut self, dt: f32, elapsed_s: f32) -> f32 {
432        while elapsed_s >= self.next_edge_s {
433            self.edge += 1;
434            self.next_edge_s += half_period_s(self.edge);
435            self.high = !self.high;
436        }
437        let square = if self.high { self.amplitude } else { 0.0 };
438        self.washout = lagged(self.washout, square, dt, self.washout_tc_s);
439        square - self.washout
440    }
441}
442
443/// The recorded window: each tick's body rate, the moment commanded on the tick before, and
444/// the excitation offset returned for the tick.
445#[derive(Clone, Debug, PartialEq)]
446struct Window {
447    rates_radps: [f32; WINDOW_CAPACITY],
448    moments: [f32; WINDOW_CAPACITY],
449    offsets: [f32; WINDOW_CAPACITY],
450    /// Ticks whose rate or moment wasn't finite, recorded as the last finite one.
451    held: [bool; WINDOW_CAPACITY],
452    len: usize,
453    /// Sum of the recorded ticks' `dt`, in s.
454    duration_s: f32,
455}
456
457impl Window {
458    fn new() -> Self {
459        Window {
460            rates_radps: [0.0; WINDOW_CAPACITY],
461            moments: [0.0; WINDOW_CAPACITY],
462            offsets: [0.0; WINDOW_CAPACITY],
463            held: [false; WINDOW_CAPACITY],
464            len: 0,
465            duration_s: 0.0,
466        }
467    }
468
469    /// Records a tick, a non-finite rate or moment as the last finite one (0 before any);
470    /// past [`WINDOW_CAPACITY`] ticks, records nothing.
471    fn record(&mut self, dt: f32, rate_radps: f32, last_moment: f32, offset: f32) {
472        let index = self.len;
473        if index == WINDOW_CAPACITY {
474            return;
475        }
476        let held = |value: f32, values: &[f32; WINDOW_CAPACITY]| {
477            if value.is_finite() {
478                value
479            } else {
480                index.checked_sub(1).map_or(0.0, |last| values[last])
481            }
482        };
483        self.rates_radps[index] = held(rate_radps, &self.rates_radps);
484        self.moments[index] = held(last_moment, &self.moments);
485        self.offsets[index] = offset;
486        self.held[index] = !(rate_radps.is_finite() && last_moment.is_finite());
487        self.len += 1;
488        self.duration_s += dt;
489    }
490}
491
492/// The [`RateModel`] fitted to `window`, by the fit [`classify`] picks.
493#[cfg(test)]
494fn fit_window(window: &Window) -> Result<RateModel, IdentifyAbort> {
495    fit_classified(window, classify(window))
496}
497
498/// The [`RateModel`] fitted to `window` by `fit`, the fit [`classify`] picked for it.
499fn fit_classified(
500    window: &Window,
501    fit: Result<Fit, IdentifyAbort>,
502) -> Result<RateModel, IdentifyAbort> {
503    match fit? {
504        Fit::Recorded(model) => Ok(model),
505        Fit::Integrated => fit_integrated(window).ok_or(IdentifyAbort::Unexcited),
506    }
507}
508
509/// The fit a window takes.
510#[derive(Clone, Copy, Debug, PartialEq)]
511enum Fit {
512    /// Quiet: [`fit_recorded`]'s model.
513    Recorded(RateModel),
514    /// Noisy: [`fit_integrated`].
515    Integrated,
516}
517
518/// By least squares on the recorded moments ([`fit_recorded`]), unless that fit leaves more
519/// than [`NOISY_RESIDUAL_RADPS`] unexplained, when [`fit_integrated`] fits it instead, or the
520/// window aborts as saturated if more than [`SATURATED_SHARE`] of its moments sit at the rate
521/// loop's limit. Unexcited when the least squares doesn't solve.
522fn classify(window: &Window) -> Result<Fit, IdentifyAbort> {
523    let recorded = fit_recorded(window).ok_or(IdentifyAbort::Unexcited)?;
524    if recorded.residual_radps <= NOISY_RESIDUAL_RADPS {
525        return Ok(Fit::Recorded(recorded.model));
526    }
527    let moments = &window.moments[..window.len];
528    let saturated = moments
529        .iter()
530        .filter(|moment| moment.abs() >= SATURATED_MOMENT)
531        .count();
532    if saturated as f32 > SATURATED_SHARE * window.len as f32 {
533        return Err(IdentifyAbort::Saturated);
534    }
535    Ok(Fit::Integrated)
536}
537
538/// The [`RateModel`] fitted to the recorded moments through each lag and delay, both sides
539/// integrated ([`IdentifyProbe`] says how), at the delay with the least residual among those
540/// pushing the right way ([`delay_to_fit`]); `None` when the window is too short to fit any
541/// delay or no delay solves.
542fn fit_integrated(window: &Window) -> Option<RateModel> {
543    let len = window.len;
544    let dt_s = window.duration_s / len.max(1) as f32;
545    // The first tick every delay's two moment terms and the rate's last tick reach.
546    let first = MAX_DELAY_TICKS + 1;
547    if len <= first + 1 {
548        return None;
549    }
550    let integrator = Integrator::new(dt_s);
551    let mut best: [Option<LagFit>; DELAY_STEPS] = [None; DELAY_STEPS];
552    let mut accel = [0.0f32; WINDOW_CAPACITY];
553    let mut previous_pole = 0.0;
554    let mut poles = lag_poles(dt_s).peekable();
555    while let Some(pole) = poles.next() {
556        lag_through(&window.moments, pole, len, &mut accel);
557        let next_pole = poles.peek().copied().unwrap_or(pole);
558        for (step, best) in best.iter_mut().enumerate() {
559            let fit = fit_gain(window, &accel, Delay::at(step), first, integrator);
560            if fit.is_some_and(|fit| best.is_none_or(|kept| fit.residual < kept.residual)) {
561                *best = fit.map(|fit| LagFit {
562                    pole,
563                    bracket: [previous_pole, next_pole],
564                    ..fit
565                });
566            }
567        }
568        previous_pole = pole;
569    }
570    let effects = best.map(|fit| fit.map(|fit| (fit.gain, fit.residual)));
571    let step = delay_to_fit(&effects, 0.0)? - 1;
572    let delay = Delay::at(step);
573    let grid_fit = best[step]?;
574    let LagFit { pole, gain, .. } = refine(window, delay, grid_fit, first, integrator, &mut accel);
575    let [now, next] = delay.split().map(|share| share * gain * (1.0 - pole));
576    Some(RateModel {
577        rate_weights: [1.0 + pole, -pole],
578        moment_weights: [now, next, 0.0],
579        delay_ticks: delay.ticks,
580        dt_s,
581    })
582}
583
584/// `moments` through a lag of pole `pole` into `accel`, over the first `len` ticks:
585/// `a[k] = p·a[k−1] + (1 − p)·u[k]`.
586fn lag_through(
587    moments: &[f32; WINDOW_CAPACITY],
588    pole: f32,
589    len: usize,
590    accel: &mut [f32; WINDOW_CAPACITY],
591) {
592    let mut lagged = 0.0;
593    for (accel, moment) in accel.iter_mut().zip(moments).take(len) {
594        lagged = pole * lagged + (1.0 - pole) * moment;
595        *accel = lagged;
596    }
597}
598
599/// Golden-section steps that refine the grid's best lag between its neighbors: the bracket
600/// shrinks to 0.618¹² ≈ 0.3% of a 10% step, and a grid point alone sits up to 2.5% off, past
601/// the lag a test can hold (a 31 ms lag read 31.9 between grid points 30.4 and 31.9, #551).
602const REFINE_STEPS: usize = 12;
603
604/// `grid_fit` at `delay`, its pole refined by golden section within its bracket on the
605/// residual; the grid's own fit if no refined pole beats it. `accel` is scratch for each
606/// pole's lagged moment.
607fn refine(
608    window: &Window,
609    delay: Delay,
610    grid_fit: LagFit,
611    first: usize,
612    integrator: Integrator,
613    accel: &mut [f32; WINDOW_CAPACITY],
614) -> LagFit {
615    const GOLDEN: f32 = 0.618_034;
616    let mut fit_at = |pole: f32| {
617        lag_through(&window.moments, pole, window.len, accel);
618        fit_gain(window, accel, delay, first, integrator).map(|fit| LagFit { pole, ..fit })
619    };
620    let [mut low, mut high] = grid_fit.bracket;
621    let mut best = grid_fit;
622    for _ in 0..REFINE_STEPS {
623        let left = high - GOLDEN * (high - low);
624        let right = low + GOLDEN * (high - low);
625        let (Some(left_fit), Some(right_fit)) = (fit_at(left), fit_at(right)) else {
626            break;
627        };
628        let kept = if left_fit.residual < right_fit.residual {
629            high = right;
630            left_fit
631        } else {
632            low = left;
633            right_fit
634        };
635        if kept.residual < best.residual {
636            best = kept;
637        }
638    }
639    best
640}
641
642/// The lag grid's poles at ticks of `dt_s`: a lag of 0 (pole 0), then `e^(−dt/τ)` for each
643/// lag `τ` from [`MIN_LAG_S`] to [`MAX_LAG_S`] by [`LAG_RATIO`].
644fn lag_poles(dt_s: f32) -> impl Iterator<Item = f32> {
645    let lags_s = core::iter::successors(Some(MIN_LAG_S), |lag_s| Some(lag_s * LAG_RATIO))
646        .take_while(|lag_s| *lag_s <= MAX_LAG_S);
647    core::iter::once(0.0).chain(lags_s.map(move |lag_s| libm::expf(-dt_s / lag_s)))
648}
649
650/// Rate change per tick fitted to the last two rates and three recorded moments
651/// (`y[k] − y[k−1]` on `y[k−1]`, `y[k−1] − y[k−2]`, `u[k−d]`, `u[k−d−1]`, `u[k−d−2]`, and a
652/// constant) at each delay, by least squares, at the delay [`delay_to_fit`] picks; `None` when
653/// no delay's sums solve. Exact on a clean window, saturated or not; under gyro noise it reads
654/// every lag as 0, as the measured rate is among its terms (#551). Its rate terms are the
655/// change and the difference rather than the two rates: at 250 Hz the last two rates are
656/// nearly equal, and fitting them side by side loses the lag in `f32` (#516).
657fn fit_recorded(window: &Window) -> Option<RecordedFit> {
658    let dt_s = window.duration_s / window.len.max(1) as f32;
659    let mut fits = DelayFits::new();
660    for tick in 0..window.len {
661        // A held tick goes in as not finite, which restarts the history past it.
662        let rate_radps = if window.held[tick] {
663            f32::NAN
664        } else {
665            window.rates_radps[tick]
666        };
667        fits.record(dt_s, rate_radps, window.moments[tick]);
668    }
669    fits.solve()
670}
671
672/// [`fit_recorded`]'s model, and how much of the rate's change per tick it leaves unexplained.
673#[derive(Clone, Copy, Debug, PartialEq)]
674struct RecordedFit {
675    model: RateModel,
676    /// RMS of the residual per tick, in rad/s.
677    residual_radps: f32,
678}
679
680/// Moments [`fit_recorded`] keeps: the longest delay's oldest term, `u[k − d − 2]`.
681const HISTORY: usize = MAX_DELAY_TICKS + 2;
682
683/// Terms in [`fit_recorded`]: two rates, three moments, a constant.
684const TERMS: usize = 6;
685
686/// Each delay's least-squares sums for [`fit_recorded`], fed one tick at a time, and their
687/// solution.
688#[derive(Clone, Debug, PartialEq)]
689struct DelayFits {
690    /// The last two body rates, `y[k−1]` then `y[k−2]`, in rad/s.
691    rates_radps: [f32; 2],
692    /// The moments, newest first: `moments[0]` is `u[k−1]`.
693    moments: [f32; HISTORY],
694    /// Consecutive finite ticks recorded, up to [`HISTORY`].
695    filled: usize,
696    /// Each delay's sums, delay 1 first.
697    sums: [Sums; MAX_DELAY_TICKS],
698    /// Ticks the sums hold, and their total `dt`, in s.
699    rows: usize,
700    rows_dt_s: f32,
701}
702
703impl DelayFits {
704    fn new() -> Self {
705        DelayFits {
706            rates_radps: [0.0; 2],
707            moments: [0.0; HISTORY],
708            filled: 0,
709            sums: [Sums::default(); MAX_DELAY_TICKS],
710            rows: 0,
711            rows_dt_s: 0.0,
712        }
713    }
714
715    /// Adds this tick to every delay's sums once the history is full, then shifts the history;
716    /// a non-finite tick empties it instead.
717    fn record(&mut self, dt: f32, rate_radps: f32, last_moment: f32) {
718        if !(rate_radps.is_finite() && last_moment.is_finite()) {
719            self.filled = 0;
720            return;
721        }
722        self.moments.rotate_right(1);
723        self.moments[0] = last_moment;
724        self.filled = (self.filled + 1).min(HISTORY);
725        if self.filled == HISTORY {
726            let [previous, before] = self.rates_radps;
727            let target = rate_radps - previous;
728            for (index, sums) in self.sums.iter_mut().enumerate() {
729                // Delay d = index + 1: u[k − d − j] is moments[d − 1 + j].
730                let regressors = SVector::<f32, TERMS>::from([
731                    previous,
732                    previous - before,
733                    self.moments[index],
734                    self.moments[index + 1],
735                    self.moments[index + 2],
736                    1.0,
737                ]);
738                sums.add(&regressors, target);
739            }
740            self.rows += 1;
741            self.rows_dt_s += dt;
742        }
743        self.rates_radps = [rate_radps, self.rates_radps[0]];
744    }
745
746    /// The fit at the delay [`delay_to_fit`] picks; `None` when no delay's sums solve.
747    fn solve(&self) -> Option<RecordedFit> {
748        let dt_s = self.rows_dt_s / self.rows.max(1) as f32;
749        let fits: [Option<(RateModel, f32)>; MAX_DELAY_TICKS] = core::array::from_fn(|index| {
750            let (solution, residual) = self.sums[index].solve()?;
751            Some((model_at(index + 1, &solution, dt_s), residual))
752        });
753        let effects =
754            fits.map(|fit| fit.map(|(model, residual)| (model.moment_effect(), residual)));
755        let delay_ticks = delay_to_fit(&effects, TIE_SHARE)?;
756        let (model, residual) = fits[delay_ticks - 1]?;
757        Some(RecordedFit {
758            model,
759            residual_radps: libm::sqrtf(residual / self.rows.max(1) as f32),
760        })
761    }
762}
763
764/// The model a delay's least-squares `solution` gives, at `delay_ticks` and ticks of `dt_s`.
765fn model_at(delay_ticks: usize, solution: &SVector<f32, TERMS>, dt_s: f32) -> RateModel {
766    // Δy[k] = c₀·y[k−1] + c₁·(y[k−1] − y[k−2]) + …, so y[k] = (1 + c₀ + c₁)·y[k−1] − c₁·y[k−2] + ….
767    let (change, difference) = (solution[0], solution[1]);
768    RateModel {
769        rate_weights: [1.0 + change + difference, -difference],
770        moment_weights: [solution[2], solution[3], solution[4]],
771        delay_ticks,
772        dt_s,
773    }
774}
775
776/// The least-squares sums at one delay. `normal` keeps the full symmetric matrix (21 entries
777/// would do) for a plain `φ·φᵀ` and nalgebra's solve; halving it saves about 0.6 KB.
778#[derive(Clone, Copy, Debug, PartialEq)]
779struct Sums {
780    /// `Σ φ·φᵀ` over the regressors.
781    normal: SMatrix<f32, TERMS, TERMS>,
782    /// `Σ φ·t` against the targets.
783    projected: SVector<f32, TERMS>,
784    /// `Σ t²`.
785    target_squared: f32,
786}
787
788impl Default for Sums {
789    fn default() -> Self {
790        Sums {
791            normal: SMatrix::zeros(),
792            projected: SVector::zeros(),
793            target_squared: 0.0,
794        }
795    }
796}
797
798impl Sums {
799    fn add(&mut self, regressors: &SVector<f32, TERMS>, target: f32) {
800        self.normal += regressors * regressors.transpose();
801        self.projected += regressors * target;
802        self.target_squared += target * target;
803    }
804
805    /// The least-squares solution and its residual `Σt² − θ·Σφt` (at least 0); `None` when
806    /// the sums don't factor or solve to a non-finite value.
807    fn solve(&self) -> Option<(SVector<f32, TERMS>, f32)> {
808        let solution = self.normal.cholesky()?.solve(&self.projected);
809        let residual = (self.target_squared - solution.dot(&self.projected)).max(0.0);
810        let finite = solution.iter().all(|x| x.is_finite()) && residual.is_finite();
811        finite.then_some((solution, residual))
812    }
813}
814
815/// Delays the fit tries: each whole tick from 1 to [`MAX_DELAY_TICKS`], and each half tick
816/// past it.
817const DELAY_STEPS: usize = 2 * MAX_DELAY_TICKS;
818
819/// A delay in half ticks: `ticks`, plus half a tick when `half`, the moment then felt half on
820/// each of two ticks. The zero-order hold leaves a moment's first tick partly felt, and with
821/// whole ticks alone a 20 ms lag read 24 ms at 1 tick, or right at 2 (#551). A free weight on
822/// each tick instead fitted noise, opposite in sign.
823#[derive(Clone, Copy, Debug, PartialEq)]
824struct Delay {
825    ticks: usize,
826    half: bool,
827}
828
829impl Delay {
830    /// The `step`-th delay, shortest first: 1, 1½, 2, 2½, … ticks.
831    fn at(step: usize) -> Self {
832        Delay {
833            ticks: step / 2 + 1,
834            half: step % 2 == 1,
835        }
836    }
837
838    /// The share of the moment felt `ticks` back and one tick more.
839    fn split(self) -> [f32; 2] {
840        if self.half { [0.5, 0.5] } else { [1.0, 0.0] }
841    }
842}
843
844/// One lag and delay's least squares: the gain from the lagged moment to the rate's change per
845/// tick (positive pushes the axis the way the moment does), and the residual left. `pole` and
846/// `bracket` are filled in by the caller.
847#[derive(Clone, Copy, Debug, PartialEq)]
848struct LagFit {
849    pole: f32,
850    /// The neighboring grid poles, which [`refine`] searches between.
851    bracket: [f32; 2],
852    gain: f32,
853    residual: f32,
854}
855
856/// A leaky integrator, `f[k] = c·f[k−1] + v[k]`, at [`INTEGRATION_TC_S`]: `c = e^(−dt/τ)`.
857#[derive(Clone, Copy, Debug, PartialEq)]
858struct Integrator {
859    carry: f64,
860}
861
862impl Integrator {
863    fn new(dt_s: f32) -> Self {
864        Integrator {
865            carry: f64::from(libm::expf(-dt_s / INTEGRATION_TC_S)),
866        }
867    }
868}
869
870/// Fits `y[k] − y[k−1] ≈ gain·x[k] + constant`, both sides through `integrator`, over ticks
871/// `first..` of the window by least squares, `x` the lagged moment at `delay` (`a[k − d + 1]`,
872/// or its mean with `a[k − d]` at a half tick); `None` when it doesn't vary. Integrated, the
873/// constant is a ramp, so it's a regressor like the moment. Sums in `f64`: the residual cancels
874/// to a small share of the target's, and delays differ by a smaller one still.
875fn fit_gain(
876    window: &Window,
877    accel: &[f32; WINDOW_CAPACITY],
878    delay: Delay,
879    first: usize,
880    integrator: Integrator,
881) -> Option<LagFit> {
882    let [now, next] = delay.split().map(f64::from);
883    let carry = integrator.carry;
884    let (mut moment, mut constant, mut target) = (0.0f64, 0.0f64, 0.0f64);
885    let (mut smm, mut smc, mut scc, mut smt, mut sct, mut stt) = (0.0f64, 0.0, 0.0, 0.0, 0.0, 0.0);
886    for tick in first..window.len {
887        let felt = tick + 1 - delay.ticks;
888        let x = now * f64::from(accel[felt]) + next * f64::from(accel[felt - 1]);
889        let change = f64::from(window.rates_radps[tick] - window.rates_radps[tick - 1]);
890        moment = carry * moment + x;
891        constant = carry * constant + 1.0;
892        target = carry * target + change;
893        smm += moment * moment;
894        smc += moment * constant;
895        scc += constant * constant;
896        smt += moment * target;
897        sct += constant * target;
898        stt += target * target;
899    }
900    let det = smm * scc - smc * smc;
901    // A lagged moment that doesn't vary apart from the constant (or a NaN) leaves the gain
902    // and the constant unsolved.
903    let varies = det > f64::EPSILON * smm * scc;
904    if !varies {
905        return None;
906    }
907    let gain = (smt * scc - smc * sct) / det;
908    let trim = (smm * sct - smc * smt) / det;
909    let residual = (stt - gain * smt - trim * sct).max(0.0);
910    Some(LagFit {
911        pole: 0.0,
912        bracket: [0.0; 2],
913        gain: gain as f32,
914        residual: residual as f32,
915    })
916}
917
918/// The delay to fit, as its index in `fits` + 1 (shortest first, at most [`DELAY_STEPS`]), from
919/// each delay's moment effect and residual: [`shortest_tied`] at `tie_share` among those with a
920/// positive moment effect, or among all when none has one (a reversed axis, which the design
921/// rejects as such). A negative effect pushes the axis against the moment commanded, which no
922/// design can use, and in flight it comes from noise favoring a wrong delay (#529). A pushing
923/// delay wins however far its residual is from a wrong-way least: on QuadCopterX in
924/// RealFlight the 7 fits it decided sat 1–9% above it, 5 read 37–63 rad/s² (the axis's
925/// healthy fits read 30–70), and the design rejects the other 2 (0 and 8). `None` when no
926/// delay solved.
927fn delay_to_fit(fits: &[Option<(f32, f32)>], tie_share: f32) -> Option<usize> {
928    let fit_at = |index: usize| fits.get(index).copied().flatten();
929    let pushing: [Option<f32>; DELAY_STEPS] = core::array::from_fn(|index| {
930        fit_at(index)
931            .filter(|(effect, _)| *effect > 0.0)
932            .map(|(_, residual)| residual)
933    });
934    let all: [Option<f32>; DELAY_STEPS] =
935        core::array::from_fn(|index| fit_at(index).map(|(_, residual)| residual));
936    shortest_tied(&pushing, tie_share).or_else(|| shortest_tied(&all, tie_share))
937}
938
939/// The shortest delay, as its index + 1, whose residual is within `tie_share` of the least;
940/// `None` when no delay solved.
941fn shortest_tied(residuals: &[Option<f32>], tie_share: f32) -> Option<usize> {
942    let least = residuals.iter().flatten().copied().reduce(f32::min)?;
943    let tied = least + tie_share * least;
944    residuals
945        .iter()
946        .position(|residual| residual.is_some_and(|r| r <= tied))
947        .map(|index| index + 1)
948}