stable_flight/tuning/identify.rs
1//! Closed-loop identification of a rate axis: see [`IdentifyProbe`].
2//!
3//! Follows the excitation and model PX4's autotune flies (`mc_autotune_attitude_control`'s
4//! `getIdentificationSignal`, added to the rate setpoint by `mc_att_control`; `ArxRls` in
5//! `system_identification`), described, not copied: a washed-out square wave whose
6//! half-periods shrink, and a second-order model with a delay.
7//! PX4 fits it by recursive least squares; this probe accumulates the least-squares sums
8//! instead and solves once at the end, in a form that holds its precision in `f32` (#516).
9
10use nalgebra::{Complex, SMatrix, SVector};
11
12use crate::controllers::{InvalidConfig, check, check_positive};
13use crate::math::{assert_dt, lagged};
14
15#[cfg(test)]
16mod tests;
17
18/// Longest delay the fit tries, in ticks: 40 ms at 250 Hz, past the sim's 25 ms actuator delay
19/// (7 ticks with the hold).
20pub const MAX_DELAY_TICKS: usize = 10;
21
22/// Moments kept: the longest delay's oldest term, `u[k − d − 2]`.
23const HISTORY: usize = MAX_DELAY_TICKS + 2;
24
25/// Terms in the fit: two rates, three moments, a constant.
26const TERMS: usize = 6;
27
28/// The square wave's half-periods, in s: 1.0 down to 0.2 by 0.1, then 0.6 down to 0.2,
29/// repeating (PX4's sweep, `getIdentificationSignal`).
30fn half_period_s(index: usize) -> f32 {
31 // The first sweep's nine halves, 1.0 down to 0.2 s; then sweeps of five, 0.6 down to 0.2.
32 const FIRST_SWEEP_HALVES: usize = 9;
33 match index {
34 0..FIRST_SWEEP_HALVES => 1.0 - 0.1 * index as f32,
35 _ => 0.6 - 0.1 * ((index - FIRST_SWEEP_HALVES) % 5) as f32,
36 }
37}
38
39/// Residuals within this share of the least count as tied, and the shortest such delay wins:
40/// `f32` cancellation in `Σt² − θ·Σφt` would otherwise pick between near-equal delays on
41/// rounding (a 25 ms delay fit at 6 or 7 ticks, #516). Wider favors delays too short, which
42/// design too hot a loop: on QuadCopterX in RealFlight, 5% took 1 tick in 6 of 67 fits
43/// against 1 at 1%, and in run 35 a 1-tick pick at 2.2% over the least designed roll rate
44/// P 1.79, which rang and failed its stage (#529).
45const TIE_SHARE: f32 = 0.01;
46
47/// Configures an [`IdentifyProbe`].
48///
49/// The amplitude is in the probed loop's setpoint units (rad/s on a rate loop), so there is no
50/// `Default`; [`COPTER_IDENTIFY`](crate::tuning::autotune::COPTER_IDENTIFY) is the copter's.
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct IdentifyConfig {
53 /// Height of the square wave added to the setpoint, in setpoint units. Non-zero and
54 /// finite: larger moves the vehicle further and lifts the response over noise.
55 pub amplitude: f32,
56 /// How long the axis is excited and recorded, in s. Positive and finite.
57 pub duration_s: f32,
58 /// Time constant of the washout taken off the square wave, in s (PX4: 0.2 s): each edge
59 /// becomes a pulse that decays, so the setpoint offset averages near zero. Positive and
60 /// finite.
61 pub washout_tc_s: f32,
62}
63
64impl IdentifyConfig {
65 /// Checks every field's stated requirement.
66 ///
67 /// # Examples
68 ///
69 /// ```
70 /// use stable_flight::tuning::autotune::COPTER_IDENTIFY;
71 /// use stable_flight::tuning::IdentifyConfig;
72 ///
73 /// assert!(COPTER_IDENTIFY.validate().is_ok());
74 /// let bad = IdentifyConfig { duration_s: 0.0, ..COPTER_IDENTIFY };
75 /// assert!(bad.validate().is_err());
76 /// ```
77 pub fn validate(&self) -> Result<(), InvalidConfig> {
78 check(
79 "amplitude",
80 self.amplitude != 0.0 && self.amplitude.is_finite(),
81 "non-zero and finite",
82 )?;
83 check_positive("duration_s", self.duration_s)?;
84 check_positive("washout_tc_s", self.washout_tc_s)
85 }
86}
87
88/// A rate axis's response to its moment command, fitted in flight: the body rate one tick on
89/// from the last two rates and three moments, `delay_ticks` back.
90///
91/// `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
92/// rate in rad/s, `u` the normalized moment, `r` the [`rate_weights`](Self::rate_weights), `m`
93/// the [`moment_weights`](Self::moment_weights), and `d` the delay. A body that integrates its
94/// moment through one motor lag fits it with `r₁ = 1 + p`, `r₂ = −p`, `p` the lag's pole.
95#[derive(Clone, Copy, Debug, PartialEq)]
96pub struct RateModel {
97 /// Weights of the last two body rates, `y[k−1]` and `y[k−2]`.
98 pub rate_weights: [f32; 2],
99 /// Weights of the moments `u[k−d]`, `u[k−d−1]`, and `u[k−d−2]`.
100 pub moment_weights: [f32; 3],
101 /// Ticks from a moment command to its first effect on the rate, at least 1.
102 pub delay_ticks: usize,
103 /// The tick the model steps at, in s: the mean `dt` it was fitted over.
104 pub dt_s: f32,
105}
106
107impl RateModel {
108 /// The motor lag's time constant, in s, from its pole `p = −r₂`: `−dt / ln p` for a pole
109 /// in `(0, 1)`. A pole at or below 0 is a lag under a tick, which the delay absorbs, so 0
110 /// (#563). `None` for a pole at or past 1, which grows rather than lags.
111 ///
112 /// # Examples
113 ///
114 /// ```
115 /// use stable_flight::tuning::RateModel;
116 ///
117 /// // A 30 ms lag at 250 Hz: p = e^(−0.004/0.03).
118 /// let p = (-0.004f32 / 0.03).exp();
119 /// let model = RateModel {
120 /// rate_weights: [1.0 + p, -p],
121 /// moment_weights: [0.1, 0.0, 0.0],
122 /// delay_ticks: 1,
123 /// dt_s: 0.004,
124 /// };
125 /// assert!((model.lag_s().unwrap() - 0.03).abs() < 1e-5);
126 /// ```
127 pub fn lag_s(&self) -> Option<f32> {
128 let pole = -self.rate_weights[1];
129 if pole >= 1.0 || pole.is_nan() {
130 return None;
131 }
132 Some(if pole > 0.0 {
133 -self.dt_s / libm::logf(pole)
134 } else {
135 0.0
136 })
137 }
138
139 /// The model's frequency response at `w_radps`: body rate per unit moment, delay included,
140 /// `(m₀ + m₁·z⁻¹ + m₂·z⁻²)·z⁻ᵈ / (1 − r₁·z⁻¹ − r₂·z⁻²)` at `z⁻¹ = e^(−jω·dt)`. Its phase
141 /// starts near −90° (the body integrates its moment) and falls with the lag and the delay.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// use stable_flight::tuning::RateModel;
147 ///
148 /// // An integrator alone, one tick of delay: about 1/(jω) per unit gain.
149 /// let model = RateModel {
150 /// rate_weights: [1.0, 0.0],
151 /// moment_weights: [0.004, 0.0, 0.0],
152 /// delay_ticks: 1,
153 /// dt_s: 0.004,
154 /// };
155 /// let response = model.response(1.0);
156 /// assert!((response.norm_sqr() - 1.0).abs() < 0.02);
157 /// ```
158 pub fn response(&self, w_radps: f32) -> Complex<f32> {
159 let z1 = unit_delay(w_radps, self.dt_s);
160 let [m0, m1, m2] = self.moment_weights;
161 let [r1, r2] = self.rate_weights;
162 let one = Complex::new(1.0, 0.0);
163 let numerator = (one * m0 + z1 * m1 + z1 * z1 * m2) * z1.powu(self.delay_ticks as u32);
164 numerator / (one - z1 * r1 - z1 * z1 * r2)
165 }
166
167 /// The axis's angular acceleration per unit moment once the lag has settled, in rad/s²:
168 /// the moments' total weight over `(1 − p)·dt`, a pole at or below 0 taken as 0, as
169 /// [`lag_s`](Self::lag_s) takes it. `None` without a lag.
170 pub fn accel_radps2(&self) -> Option<f32> {
171 self.lag_s()?;
172 let pole = (-self.rate_weights[1]).max(0.0);
173 Some(self.moment_effect() / ((1.0 - pole) * self.dt_s))
174 }
175
176 /// The moments' total weight: its sign is the sign of the axis's response to a held moment
177 /// (`accel_radps2` divides it by a positive `(1 − p)·dt`, and the design holds a pole past
178 /// 1 at 1). Negative, the model pushes the axis against the moment commanded.
179 pub(crate) fn moment_effect(&self) -> f32 {
180 self.moment_weights.iter().sum()
181 }
182}
183
184/// `z⁻¹ = e^(−jω·dt)`: one tick's delay at `w_radps`.
185pub(crate) fn unit_delay(w_radps: f32, dt_s: f32) -> Complex<f32> {
186 let angle = -w_radps * dt_s;
187 Complex::new(libm::cosf(angle), libm::sinf(angle))
188}
189
190/// Why an [`IdentifyProbe`] gave up.
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub enum IdentifyAbort {
193 /// No delay's fit could be solved: the axis didn't move enough to tell its terms apart.
194 Unexcited,
195}
196
197/// Where an [`IdentifyProbe`] stands.
198#[derive(Clone, Copy, Debug, PartialEq)]
199pub enum IdentifyStatus {
200 /// Exciting and recording.
201 Running {
202 /// Time since the excitation began, in s.
203 elapsed_s: f32,
204 },
205 /// The fitted model.
206 Done(RateModel),
207 /// Gave up.
208 Aborted(IdentifyAbort),
209}
210
211/// Excites one loop with a square wave on its setpoint while recording its axis's body rate and
212/// moment command, then fits a [`RateModel`] to them.
213///
214/// Each tick the host hands it the axis's body rate and the moment it commanded on the last
215/// tick; the probe returns the offset to add to the loop's setpoint. Every loop stays closed, so
216/// the fit sees the airframe through its own controllers. It fits each delay from 1 to
217/// [`MAX_DELAY_TICKS`] on the same ticks and keeps the one with the least residual (the
218/// shortest of a near-tie) among those whose moment pushes the axis the way it was pushed (among
219/// all when none does): a fit with a negative moment effect can't be designed from.
220///
221/// The fit takes the rate's change `y[k] − y[k−1]` as its target and `y[k−1]`, `y[k−1] −
222/// y[k−2]` as its rate terms: at 250 Hz the last two rates are nearly equal, and fitting them
223/// side by side loses the lag in `f32` (#516). It keeps only the sums of each delay's least
224/// squares (about 1.7 KB), not the record, and solves them when the excitation ends. A
225/// constant term takes up the trim moment. A non-finite rate or moment drops that tick and the
226/// next `MAX_DELAY_TICKS + 2` ticks while the history refills.
227///
228/// # Examples
229///
230/// ```
231/// use stable_flight::tuning::autotune::COPTER_IDENTIFY;
232/// use stable_flight::tuning::{IdentifyProbe, IdentifyStatus};
233///
234/// let mut probe = IdentifyProbe::new(COPTER_IDENTIFY);
235/// // The square wave starts high: the first tick's offset is the step less its washout.
236/// let offset = probe.step(0.004, 0.0, 0.0);
237/// assert!(offset > 0.0 && offset <= COPTER_IDENTIFY.amplitude);
238/// assert!(matches!(probe.status(), IdentifyStatus::Running { .. }));
239/// ```
240#[derive(Clone, Debug, PartialEq)]
241pub struct IdentifyProbe {
242 duration_s: f32,
243 status: IdentifyStatus,
244 sweep: SquareSweep,
245 fits: DelayFits,
246}
247
248impl IdentifyProbe {
249 /// A probe ready to run.
250 ///
251 /// # Panics
252 ///
253 /// If `config` is invalid ([`IdentifyConfig::validate`]).
254 pub fn new(config: IdentifyConfig) -> Self {
255 if let Err(error) = config.validate() {
256 panic!("invalid IdentifyConfig: {error}");
257 }
258 IdentifyProbe {
259 duration_s: config.duration_s,
260 status: IdentifyStatus::Running { elapsed_s: 0.0 },
261 sweep: SquareSweep::new(config.amplitude, config.washout_tc_s),
262 fits: DelayFits::new(),
263 }
264 }
265
266 /// Advances the probe by `dt` seconds with the axis's body rate this tick (rad/s) and its
267 /// moment command on the last tick, and returns the offset to add to the loop's setpoint
268 /// (0 once it has finished). Fits the model on the tick the excitation ends.
269 ///
270 /// # Panics
271 ///
272 /// If `dt` is not positive and finite.
273 pub fn step(&mut self, dt: f32, rate_radps: f32, last_moment: f32) -> f32 {
274 assert_dt(dt);
275 let IdentifyStatus::Running { elapsed_s } = self.status else {
276 return 0.0;
277 };
278 self.fits.record(dt, rate_radps, last_moment);
279 let elapsed_s = elapsed_s + dt;
280 let offset = self.sweep.next(dt, elapsed_s);
281 self.status = if elapsed_s < self.duration_s {
282 IdentifyStatus::Running { elapsed_s }
283 } else {
284 match self.fits.solve() {
285 Some(model) => IdentifyStatus::Done(model),
286 None => IdentifyStatus::Aborted(IdentifyAbort::Unexcited),
287 }
288 };
289 offset
290 }
291
292 /// Where the probe stands.
293 pub fn status(&self) -> IdentifyStatus {
294 self.status
295 }
296}
297
298/// PX4's shrinking square wave ([`half_period_s`]), less its washout: each edge a pulse that
299/// decays over the washout's time constant.
300#[derive(Clone, Copy, Debug, PartialEq)]
301struct SquareSweep {
302 amplitude: f32,
303 washout_tc_s: f32,
304 /// When the next edge falls, in s since the start, and its index.
305 next_edge_s: f32,
306 edge: usize,
307 /// Whether the wave is at its amplitude (else 0).
308 high: bool,
309 /// The wave through a low-pass at the washout's time constant, in setpoint units.
310 washout: f32,
311}
312
313impl SquareSweep {
314 fn new(amplitude: f32, washout_tc_s: f32) -> Self {
315 SquareSweep {
316 amplitude,
317 washout_tc_s,
318 next_edge_s: half_period_s(0),
319 edge: 0,
320 high: true,
321 washout: 0.0,
322 }
323 }
324
325 /// The offset at `elapsed_s`, `dt` after the last call.
326 fn next(&mut self, dt: f32, elapsed_s: f32) -> f32 {
327 while elapsed_s >= self.next_edge_s {
328 self.edge += 1;
329 self.next_edge_s += half_period_s(self.edge);
330 self.high = !self.high;
331 }
332 let square = if self.high { self.amplitude } else { 0.0 };
333 self.washout = lagged(self.washout, square, dt, self.washout_tc_s);
334 square - self.washout
335 }
336}
337
338/// Each delay's least-squares sums, fed one tick at a time, and their solution.
339#[derive(Clone, Debug, PartialEq)]
340struct DelayFits {
341 /// The last two body rates, `y[k−1]` then `y[k−2]`, in rad/s.
342 rates_radps: [f32; 2],
343 /// The moments, newest first: `moments[0]` is `u[k−1]`.
344 moments: [f32; HISTORY],
345 /// Consecutive finite ticks recorded, up to [`HISTORY`].
346 filled: usize,
347 /// Each delay's sums, delay 1 first.
348 sums: [Sums; MAX_DELAY_TICKS],
349 /// Ticks the sums hold, and their total `dt`, in s.
350 rows: usize,
351 rows_dt_s: f32,
352}
353
354impl DelayFits {
355 fn new() -> Self {
356 DelayFits {
357 rates_radps: [0.0; 2],
358 moments: [0.0; HISTORY],
359 filled: 0,
360 sums: [Sums::default(); MAX_DELAY_TICKS],
361 rows: 0,
362 rows_dt_s: 0.0,
363 }
364 }
365
366 /// Adds this tick to every delay's sums once the history is full, then shifts the history;
367 /// a non-finite tick empties it instead.
368 fn record(&mut self, dt: f32, rate_radps: f32, last_moment: f32) {
369 if !(rate_radps.is_finite() && last_moment.is_finite()) {
370 self.filled = 0;
371 return;
372 }
373 self.moments.rotate_right(1);
374 self.moments[0] = last_moment;
375 self.filled = (self.filled + 1).min(HISTORY);
376 if self.filled == HISTORY {
377 let [previous, before] = self.rates_radps;
378 let target = rate_radps - previous;
379 for (index, sums) in self.sums.iter_mut().enumerate() {
380 // Delay d = index + 1: u[k − d − j] is moments[d − 1 + j].
381 let regressors = SVector::<f32, TERMS>::from([
382 previous,
383 previous - before,
384 self.moments[index],
385 self.moments[index + 1],
386 self.moments[index + 2],
387 1.0,
388 ]);
389 sums.add(®ressors, target);
390 }
391 self.rows += 1;
392 self.rows_dt_s += dt;
393 }
394 self.rates_radps = [rate_radps, self.rates_radps[0]];
395 }
396
397 /// The model at the delay [`delay_to_fit`] picks; `None` when no delay's sums solve.
398 fn solve(&self) -> Option<RateModel> {
399 let dt_s = self.rows_dt_s / self.rows.max(1) as f32;
400 let fits: [Option<(RateModel, f32)>; MAX_DELAY_TICKS] = core::array::from_fn(|index| {
401 let (solution, residual) = self.sums[index].solve()?;
402 Some((model_at(index + 1, &solution, dt_s), residual))
403 });
404 let effects =
405 fits.map(|fit| fit.map(|(model, residual)| (model.moment_effect(), residual)));
406 let delay_ticks = delay_to_fit(&effects)?;
407 fits[delay_ticks - 1].map(|(model, _)| model)
408 }
409}
410
411/// The model a delay's least-squares `solution` gives, at `delay_ticks` and ticks of `dt_s`.
412fn model_at(delay_ticks: usize, solution: &SVector<f32, TERMS>, dt_s: f32) -> RateModel {
413 // Δ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] + ….
414 let (change, difference) = (solution[0], solution[1]);
415 RateModel {
416 rate_weights: [1.0 + change + difference, -difference],
417 moment_weights: [solution[2], solution[3], solution[4]],
418 delay_ticks,
419 dt_s,
420 }
421}
422
423/// The least-squares sums at one delay. `normal` keeps the full symmetric matrix (21 entries
424/// would do) for a plain `φ·φᵀ` and nalgebra's solve; halving it saves about 0.6 KB.
425#[derive(Clone, Copy, Debug, PartialEq)]
426struct Sums {
427 /// `Σ φ·φᵀ` over the regressors.
428 normal: SMatrix<f32, TERMS, TERMS>,
429 /// `Σ φ·t` against the targets.
430 projected: SVector<f32, TERMS>,
431 /// `Σ t²`.
432 target_squared: f32,
433}
434
435impl Default for Sums {
436 fn default() -> Self {
437 Sums {
438 normal: SMatrix::zeros(),
439 projected: SVector::zeros(),
440 target_squared: 0.0,
441 }
442 }
443}
444
445impl Sums {
446 fn add(&mut self, regressors: &SVector<f32, TERMS>, target: f32) {
447 self.normal += regressors * regressors.transpose();
448 self.projected += regressors * target;
449 self.target_squared += target * target;
450 }
451
452 /// The least-squares solution and its residual `Σt² − θ·Σφt` (at least 0); `None` when
453 /// the sums don't factor or solve to a non-finite value.
454 fn solve(&self) -> Option<(SVector<f32, TERMS>, f32)> {
455 let solution = self.normal.cholesky()?.solve(&self.projected);
456 let residual = (self.target_squared - solution.dot(&self.projected)).max(0.0);
457 let finite = solution.iter().all(|x| x.is_finite()) && residual.is_finite();
458 finite.then_some((solution, residual))
459 }
460}
461
462/// The delay, in ticks (index + 1), to fit from each delay's moment effect (the sum of its
463/// moment weights) and residual: [`shortest_tied`] among those with a positive moment effect,
464/// or among all when none has one (a reversed axis, which the design rejects as such). A
465/// negative effect pushes the axis against the moment commanded, which no design can use, and
466/// in flight it comes from noise favoring a wrong delay (#529). A pushing delay wins however
467/// far its residual is from a wrong-way least: on QuadCopterX in RealFlight the 7 fits it
468/// decided sat 1–9% above it, 5 read 37–63 rad/s² (the axis's healthy fits read 30–70), and
469/// the design rejects the other 2 (0 and 8) as it did before. `None` when no delay solved.
470fn delay_to_fit(fits: &[Option<(f32, f32)>]) -> Option<usize> {
471 let fit_at = |index: usize| fits.get(index).copied().flatten();
472 let pushing: [Option<f32>; MAX_DELAY_TICKS] = core::array::from_fn(|index| {
473 fit_at(index)
474 .filter(|(effect, _)| *effect > 0.0)
475 .map(|(_, residual)| residual)
476 });
477 let all: [Option<f32>; MAX_DELAY_TICKS] =
478 core::array::from_fn(|index| fit_at(index).map(|(_, residual)| residual));
479 shortest_tied(&pushing).or_else(|| shortest_tied(&all))
480}
481
482/// The shortest delay, in ticks (index + 1), whose residual is within [`TIE_SHARE`] of the
483/// least; `None` when no delay solved.
484fn shortest_tied(residuals: &[Option<f32>]) -> Option<usize> {
485 let least = residuals.iter().flatten().copied().reduce(f32::min)?;
486 let tied = least + TIE_SHARE * least;
487 residuals
488 .iter()
489 .position(|residual| residual.is_some_and(|r| r <= tied))
490 .map(|index| index + 1)
491}