Skip to main content

stable_flight/tuning/
wing.rs

1//! Closed-loop identification of a wing's roll or pitch axis: see [`WingIdentifyProbe`].
2
3use nalgebra::{SMatrix, SVector};
4
5use super::identify::SquareSweep;
6use super::{IdentifyAbort, IdentifyConfig};
7use crate::math::assert_dt;
8
9pub mod design;
10#[cfg(test)]
11mod tests;
12
13/// Ticks per recorded sample: every second tick, 8 ms at 250 Hz. A wing's loops answer over
14/// tenths of a second, and the surfaces' lags on the sim's planes fit at 0–0.1 s (#533).
15const DECIMATION: usize = 2;
16
17/// Samples the probe records: 6 s at 250 Hz, the window the sweep fitted (#533). A longer
18/// excitation fits its first `WINDOW_CAPACITY` samples.
19const WINDOW_CAPACITY: usize = 750;
20
21/// The surface lags the fit tries, in s, up to the Alia 250's 0.17 s motors with room.
22const LAGS_S: [f32; 12] = [
23    0.0, 0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.14, 0.17, 0.2, 0.25, 0.3,
24];
25
26/// Longest delay the fit tries, in samples: 40 ms, past the sim's 25 ms actuator delay.
27const MAX_DELAY_SAMPLES: usize = 5;
28
29/// Terms of the fit: angle of attack, rate, lagged moment, and a constant for the trim.
30const TERMS: usize = 4;
31
32/// An angle of attack that varies by less than this over the window, in rad, isn't fitted:
33/// a roll axis, whose host reports none.
34const MIN_ALPHA_SPREAD_RAD: f32 = 1e-4;
35
36/// A wing axis's response to its moment command, fitted in flight: how the moment, through the
37/// surfaces' lag and a delay, accelerates the axis against its damping and, in pitch, the
38/// wing's stiffness in angle of attack.
39///
40/// `rate′ = −stiffness·α − damping·rate + control·surface`, with `rate` the body rate in rad/s,
41/// `α` the angle of attack off its trim in rad, and `surface` the normalized moment command
42/// through a first-order lag of `lag_s`, `delay_s` late. A stable wing has positive stiffness
43/// and damping. In pitch the flight path turns with angle of attack, `γ′ = path_turn·α`, so a
44/// held pitch settles back to the trim angle of attack over `1 / path_turn` seconds.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct WingModel {
47    /// Pitch acceleration per rad of angle of attack, nose down for a positive one, in 1/s²; 0
48    /// on a roll axis.
49    pub stiffness_per_s2: f32,
50    /// Rate acceleration per rad/s of body rate, against the rate, in 1/s.
51    pub damping_per_s: f32,
52    /// Rate acceleration per unit moment at full surface, in rad/s².
53    pub control_radps2: f32,
54    /// The surfaces' first-order lag, in s.
55    pub lag_s: f32,
56    /// Time from a moment command to its first effect, in s.
57    pub delay_s: f32,
58    /// The flight path's turn per rad of angle of attack (lift over mass and speed), in 1/s; 0
59    /// on a roll axis.
60    pub path_turn_per_s: f32,
61    /// The moment that holds the axis in trim: the window's mean moment command (the square
62    /// wave, washed out, averages near 0). Normalized.
63    pub trim_moment: f32,
64}
65
66impl WingModel {
67    /// The moment per rad/s of body rate that holds a rate against the damping: the rate
68    /// loop's feedforward, `damping / control`.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use stable_flight::tuning::WingModel;
74    ///
75    /// let model = WingModel {
76    ///     stiffness_per_s2: 0.0,
77    ///     damping_per_s: 7.0,
78    ///     control_radps2: 14.0,
79    ///     lag_s: 0.0,
80    ///     delay_s: 0.0,
81    ///     path_turn_per_s: 0.0,
82    ///     trim_moment: 0.0,
83    /// };
84    /// assert_eq!(model.feedforward(), 0.5);
85    /// ```
86    pub fn feedforward(&self) -> f32 {
87        self.damping_per_s / self.control_radps2
88    }
89}
90
91/// Where a [`WingIdentifyProbe`] stands.
92#[derive(Clone, Copy, Debug, PartialEq)]
93pub enum WingStatus {
94    /// Exciting and recording.
95    Running {
96        /// Time since the excitation began, in s.
97        elapsed_s: f32,
98    },
99    /// The fitted model.
100    Done(WingModel),
101    /// Gave up.
102    Aborted(IdentifyAbort),
103}
104
105/// Excites a wing's rate loop with the square wave an [`IdentifyProbe`](super::IdentifyProbe)
106/// flies while recording its axis's body rate, moment command, and angle of attack, then fits
107/// a [`WingModel`] to them.
108///
109/// Each tick the host hands it the axis's body rate, the moment it commanded on the last tick,
110/// and the angle of attack (0 on a roll axis); the probe returns the offset to add to the rate
111/// setpoint. Every loop stays closed.
112///
113/// The fit is least squares on every second tick: the rate's change against the angle of
114/// attack, the rate, the moment through each surface lag in a grid from 0 to 0.3 s and each
115/// delay up to 40 ms, and a constant for the trim, keeping the lag and delay that leave the
116/// least residual. The flight path's turn is fitted apart: the climb angle (pitch less angle of
117/// attack) changes at `rate − α′`, regressed on α. A wing's pitch damping and stiffness both
118/// change the moment a held rate needs, so a fit on rate and moment alone misreads the
119/// feedforward (0.53 against the Alia 250's 0.907 on the sim, #533).
120///
121/// The window holds 750 samples (9 KB) and is fitted on the tick the excitation ends: 12 lags
122/// × 6 delays over it, about 0.2 ms on a desktop, so that tick runs long. A non-finite rate,
123/// moment, or angle of attack is recorded as the last finite one.
124///
125/// # Examples
126///
127/// ```
128/// use stable_flight::tuning::{IdentifyConfig, WingIdentifyProbe, WingStatus};
129///
130/// let config = IdentifyConfig { amplitude: 0.3, duration_s: 6.0, washout_tc_s: 0.2, noisy: None };
131/// let mut probe = WingIdentifyProbe::new(config);
132/// let offset = probe.step(0.004, 0.0, 0.0, 0.0);
133/// assert!(offset > 0.0 && offset <= config.amplitude);
134/// assert!(matches!(probe.status(), WingStatus::Running { .. }));
135/// ```
136#[derive(Clone, Debug, PartialEq)]
137pub struct WingIdentifyProbe {
138    duration_s: f32,
139    status: WingStatus,
140    sweep: SquareSweep,
141    window: Window,
142}
143
144impl WingIdentifyProbe {
145    /// A probe ready to run.
146    ///
147    /// # Panics
148    ///
149    /// If `config` is invalid ([`IdentifyConfig::validate`]).
150    pub fn new(config: IdentifyConfig) -> Self {
151        if let Err(error) = config.validate() {
152            panic!("invalid IdentifyConfig: {error}");
153        }
154        Self {
155            duration_s: config.duration_s,
156            status: WingStatus::Running { elapsed_s: 0.0 },
157            sweep: SquareSweep::new(config.amplitude, config.washout_tc_s),
158            window: Window::new(),
159        }
160    }
161
162    /// Advances the probe by `dt` seconds with the axis's body rate this tick (rad/s), its
163    /// moment command on the last tick, and the angle of attack (rad), and returns the offset
164    /// to add to the rate setpoint (0 once it has finished). Fits the model on the tick the
165    /// excitation ends.
166    ///
167    /// # Panics
168    ///
169    /// If `dt` is not positive and finite.
170    pub fn step(&mut self, dt: f32, rate_radps: f32, last_moment: f32, alpha_rad: f32) -> f32 {
171        assert_dt(dt);
172        let WingStatus::Running { elapsed_s } = self.status else {
173            return 0.0;
174        };
175        let elapsed_s = elapsed_s + dt;
176        let offset = self.sweep.next(dt, elapsed_s);
177        self.window.record(dt, rate_radps, last_moment, alpha_rad);
178        self.status = if elapsed_s < self.duration_s {
179            WingStatus::Running { elapsed_s }
180        } else {
181            match fit(&self.window) {
182                Some(model) => WingStatus::Done(model),
183                None => WingStatus::Aborted(IdentifyAbort::Unexcited),
184            }
185        };
186        offset
187    }
188
189    /// Where the probe stands.
190    pub fn status(&self) -> WingStatus {
191        self.status
192    }
193}
194
195/// The recorded window: every [`DECIMATION`]th tick's body rate and angle of attack, and the
196/// mean of the moments that moved the rate there from the last sample (the last
197/// [`DECIMATION`] ticks' last moments).
198#[derive(Clone, Debug, PartialEq)]
199struct Window {
200    rates_radps: [f32; WINDOW_CAPACITY],
201    moments: [f32; WINDOW_CAPACITY],
202    alphas_rad: [f32; WINDOW_CAPACITY],
203    len: usize,
204    /// Ticks seen, recorded or not.
205    ticks: usize,
206    /// Sum of every tick's `dt` up to the last sample, in s.
207    duration_s: f32,
208    /// The last finite rate, moment, and angle of attack, which stand in for a non-finite one.
209    last: [f32; 3],
210    /// The moments since the last sample, summed.
211    moment_sum: f32,
212}
213
214impl Window {
215    fn new() -> Self {
216        Self {
217            rates_radps: [0.0; WINDOW_CAPACITY],
218            moments: [0.0; WINDOW_CAPACITY],
219            alphas_rad: [0.0; WINDOW_CAPACITY],
220            len: 0,
221            ticks: 0,
222            duration_s: 0.0,
223            last: [0.0; 3],
224            moment_sum: 0.0,
225        }
226    }
227
228    /// Notes a tick, recording every [`DECIMATION`]th; past [`WINDOW_CAPACITY`] samples,
229    /// records nothing.
230    fn record(&mut self, dt: f32, rate_radps: f32, last_moment: f32, alpha_rad: f32) {
231        if self.len == WINDOW_CAPACITY {
232            return;
233        }
234        for (last, value) in self
235            .last
236            .iter_mut()
237            .zip([rate_radps, last_moment, alpha_rad])
238        {
239            if value.is_finite() {
240                *last = value;
241            }
242        }
243        self.duration_s += dt;
244        self.ticks += 1;
245        let [rate_radps, moment, alpha_rad] = self.last;
246        self.moment_sum += moment;
247        if !self.ticks.is_multiple_of(DECIMATION) {
248            return;
249        }
250        self.rates_radps[self.len] = rate_radps;
251        self.moments[self.len] = self.moment_sum / DECIMATION as f32;
252        self.alphas_rad[self.len] = alpha_rad;
253        self.moment_sum = 0.0;
254        self.len += 1;
255    }
256
257    /// The time between samples, in s.
258    fn sample_s(&self) -> f32 {
259        self.duration_s / self.ticks.max(1) as f32 * DECIMATION as f32
260    }
261
262    /// Whether the angle of attack varied enough to fit the wing's stiffness on.
263    fn has_alpha(&self) -> bool {
264        let alphas = &self.alphas_rad[..self.len];
265        let (low, high) = alphas
266            .iter()
267            .fold((f32::INFINITY, f32::NEG_INFINITY), |(low, high), &alpha| {
268                (low.min(alpha), high.max(alpha))
269            });
270        high - low > MIN_ALPHA_SPREAD_RAD
271    }
272}
273
274/// One lag and delay's least squares: the terms and the RMS residual of the rate's change, in
275/// rad/s².
276struct Fit {
277    terms: SVector<f64, TERMS>,
278    residual: f64,
279}
280
281/// The [`WingModel`] fitted to `window` (see [`WingIdentifyProbe`]); `None` when no lag and
282/// delay solve.
283fn fit(window: &Window) -> Option<WingModel> {
284    let sample_s = window.sample_s();
285    let with_alpha = window.has_alpha();
286    let mut best: Option<(Fit, f32, usize)> = None;
287    let mut surface = [0.0f32; WINDOW_CAPACITY];
288    for lag_s in LAGS_S {
289        lag_through(window, lag_s, sample_s, &mut surface);
290        for delay in 0..=MAX_DELAY_SAMPLES {
291            let Some(fit) = fit_at(window, &surface, delay, sample_s, with_alpha) else {
292                continue;
293            };
294            if best
295                .as_ref()
296                .is_none_or(|(kept, ..)| fit.residual < kept.residual)
297            {
298                best = Some((fit, lag_s, delay));
299            }
300        }
301    }
302    let (fit, lag_s, delay) = best?;
303    let moments = &window.moments[..window.len];
304    let trim_moment = moments.iter().sum::<f32>() / moments.len() as f32;
305    let path_turn_per_s = if with_alpha {
306        fit_path_turn(window, sample_s)?
307    } else {
308        0.0
309    };
310    Some(WingModel {
311        stiffness_per_s2: -fit.terms[0] as f32,
312        damping_per_s: -fit.terms[1] as f32,
313        control_radps2: fit.terms[2] as f32,
314        lag_s,
315        delay_s: delay as f32 * sample_s,
316        path_turn_per_s,
317        trim_moment,
318    })
319}
320
321/// The window's moments through a first-order lag of `lag_s` into `surface`, starting at the
322/// first moment.
323fn lag_through(window: &Window, lag_s: f32, sample_s: f32, surface: &mut [f32; WINDOW_CAPACITY]) {
324    let share = sample_s / (sample_s + lag_s);
325    let mut lagged = window.moments[0];
326    for (out, &moment) in surface.iter_mut().zip(&window.moments[..window.len]) {
327        lagged += share * (moment - lagged);
328        *out = lagged;
329    }
330}
331
332/// The least squares of the rate's change per second from sample `k − 1` to `k` on the angle
333/// of attack (when `with_alpha`) and the rate between them, `surface` `delay` samples before
334/// `k` (the moments that moved the rate), and a constant. `None` when it doesn't solve or the
335/// window is too short.
336fn fit_at(
337    window: &Window,
338    surface: &[f32; WINDOW_CAPACITY],
339    delay: usize,
340    sample_s: f32,
341    with_alpha: bool,
342) -> Option<Fit> {
343    let len = window.len;
344    if len < delay + TERMS + 2 {
345        return None;
346    }
347    let between = |values: &[f32; WINDOW_CAPACITY], k: usize| 0.5 * (values[k] + values[k - 1]);
348    let regressors = |k: usize| {
349        let alpha = if with_alpha {
350            between(&window.alphas_rad, k)
351        } else {
352            0.0
353        };
354        SVector::<f64, TERMS>::new(
355            f64::from(alpha),
356            f64::from(between(&window.rates_radps, k)),
357            f64::from(surface[k - delay]),
358            1.0,
359        )
360    };
361    let accel =
362        |k: usize| f64::from((window.rates_radps[k] - window.rates_radps[k - 1]) / sample_s);
363    let first = delay + 1;
364    let mut normal = SMatrix::<f64, TERMS, TERMS>::zeros();
365    let mut moment = SVector::<f64, TERMS>::zeros();
366    let mut accel_squares = 0.0f64;
367    for k in first..len {
368        let (x, y) = (regressors(k), accel(k));
369        normal += x * x.transpose();
370        moment += x * y;
371        accel_squares += y * y;
372    }
373    if !with_alpha {
374        // No stiffness term: its row and column are empty, so pin its weight to 0.
375        normal[(0, 0)] = 1.0;
376    }
377    let terms = normal.lu().solve(&moment)?;
378    // The least squares' residual without a second pass: Σ(y − x·θ)² = Σy² − θ·Σxy at the
379    // solution, θ the terms. Rounding can take it a hair below 0.
380    let sum_squares = (accel_squares - terms.dot(&moment)).max(0.0);
381    let count = (len - first) as f64;
382    terms.iter().all(|term| term.is_finite()).then(|| Fit {
383        terms,
384        residual: libm::sqrt(sum_squares / count),
385    })
386}
387
388/// The flight path's turn per rad of angle of attack, in 1/s: the climb angle changes at
389/// `rate − α′`, regressed on α with a constant, each between two samples. `None` when α
390/// doesn't vary.
391fn fit_path_turn(window: &Window, sample_s: f32) -> Option<f32> {
392    let (mut sxx, mut sx, mut sxy, mut sy, mut n) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 0.0f64);
393    for k in 1..window.len {
394        let (alphas, rates) = (&window.alphas_rad, &window.rates_radps);
395        let alpha = f64::from(0.5 * (alphas[k] + alphas[k - 1]));
396        let alpha_rate = (alphas[k] - alphas[k - 1]) / sample_s;
397        let path_rate = f64::from(0.5 * (rates[k] + rates[k - 1]) - alpha_rate);
398        sxx += alpha * alpha;
399        sx += alpha;
400        sxy += alpha * path_rate;
401        sy += path_rate;
402        n += 1.0;
403    }
404    let spread = n * sxx - sx * sx;
405    (spread > 0.0).then(|| ((n * sxy - sx * sy) / spread) as f32)
406}