Skip to main content

stable_flight/tuning/
step.rs

1//! Step-response measurement of a loop: see [`StepProbe`].
2
3use core::f32::consts::PI;
4
5use crate::controllers::{InvalidConfig, check, check_positive};
6use crate::math::assert_dt;
7
8#[cfg(test)]
9mod tests;
10
11/// A response this far the wrong way (as a fraction of the step), once the first tenth of the
12/// window has passed, aborts: the loop pushes away from the setpoint.
13const REVERSED: f32 = -0.5;
14/// A response this large (as a multiple of the step) aborts: the loop is running away.
15const RUNAWAY: f32 = 3.0;
16/// The fraction of the window before [`REVERSED`] counts, so a D kick or noise at the start
17/// doesn't abort.
18const REVERSED_AFTER: f32 = 0.1;
19/// Rise time runs between these fractions of the step.
20const RISE_FROM: f32 = 0.1;
21const RISE_TO: f32 = 0.9;
22
23/// Configures a [`StepProbe`].
24///
25/// The amplitude is in the loop's setpoint units (rad/s for a rate loop, rad for an angle
26/// loop), so there is no `Default`: the caller picks it per loop.
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct StepConfig {
29    /// Step size and direction, in setpoint units: the setpoint is held at the measurement at
30    /// the start plus this. Non-zero and finite.
31    pub amplitude: f32,
32    /// How long the step is held and measured, in seconds. Positive and finite: long enough to
33    /// settle (a few rise times), short enough that a held rate step doesn't tilt too far.
34    pub duration_s: f32,
35    /// Half-width of the band around the step the response must stay in to count as settled,
36    /// as a fraction of the step. In `(0, 1)`.
37    pub settle_band: f32,
38    /// Cutoff of the first-order low-pass on the measured response, in Hz; 0 turns it off.
39    /// Non-negative and finite. It delays the response a little, the same for every step it
40    /// measures.
41    pub filter_hz: f32,
42}
43
44impl StepConfig {
45    /// Checks every field's stated requirement.
46    ///
47    /// # Examples
48    ///
49    /// ```
50    /// use stable_flight::tuning::autotune::COPTER_RATE_STEP;
51    /// use stable_flight::tuning::StepConfig;
52    ///
53    /// assert!(COPTER_RATE_STEP.validate().is_ok());
54    /// let bad = StepConfig { settle_band: 1.5, ..COPTER_RATE_STEP };
55    /// assert!(bad.validate().is_err());
56    /// ```
57    pub fn validate(&self) -> Result<(), InvalidConfig> {
58        check(
59            "amplitude",
60            self.amplitude != 0.0 && self.amplitude.is_finite(),
61            "non-zero and finite",
62        )?;
63        check_positive("duration_s", self.duration_s)?;
64        check(
65            "settle_band",
66            self.settle_band > 0.0 && self.settle_band < 1.0,
67            "in (0, 1)",
68        )?;
69        check(
70            "filter_hz",
71            self.filter_hz >= 0.0 && self.filter_hz.is_finite(),
72            "non-negative and finite",
73        )
74    }
75
76    /// This step in the other direction.
77    pub fn reversed(self) -> Self {
78        Self {
79            amplitude: -self.amplitude,
80            ..self
81        }
82    }
83}
84
85/// Why a [`StepProbe`] gave up.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum StepAbort {
88    /// The response went half a step the wrong way.
89    Reversed,
90    /// The response passed three times the step.
91    Runaway,
92}
93
94/// What a step response looked like, normalized to the step: 1 is the step, whatever its
95/// size and direction.
96#[derive(Clone, Copy, Debug, Default, PartialEq)]
97pub struct StepMetrics {
98    /// The step, in setpoint units (signed).
99    pub amplitude: f32,
100    /// The largest response.
101    pub peak: f32,
102    /// When it peaked, in seconds from the step.
103    pub peak_time_s: f32,
104    /// How far the peak went past the step: `peak − 1`, or 0.
105    pub overshoot: f32,
106    /// Time from 10% to 90% of the step, in seconds; `None` if it never reached 90%.
107    pub rise_time_s: Option<f32>,
108    /// When the response entered the settle band for good, in seconds from the step; `None`
109    /// if it was outside the band at the end of the window.
110    pub settling_time_s: Option<f32>,
111    /// How far it fell back after the peak: `peak − lowest after it`.
112    pub bounce_back: f32,
113    /// The response at the end of the window.
114    pub final_value: f32,
115    /// How long the loop's output (or the loop under it) was clipped during the step, in
116    /// seconds: a clipped step measures the limit, not the loop.
117    pub saturated_s: f32,
118}
119
120/// Holds one loop's setpoint at a step and measures the response, inside the tick.
121///
122/// On its first tick the probe records the measurement `m₀` and from then on asks for the
123/// setpoint `m₀ + amplitude`, for `duration_s`. The response `(m − m₀) / amplitude` (low-passed
124/// at `filter_hz`) gives the [`StepMetrics`]. The window is fixed, so steps compare on equal
125/// terms. Plain data, no allocation; NaN measurements are skipped.
126///
127/// # Examples
128///
129/// ```
130/// use stable_flight::tuning::{StepConfig, StepProbe, StepStatus};
131///
132/// let config = StepConfig { amplitude: 1.0, duration_s: 0.1, settle_band: 0.1, filter_hz: 0.0 };
133/// let mut probe = StepProbe::new(config);
134/// // A loop that follows its setpoint after one tick.
135/// let mut measured = 0.0;
136/// while matches!(probe.status(), StepStatus::Running { .. }) {
137///     measured = probe.step(0.01, measured, false);
138/// }
139/// let StepStatus::Done(metrics) = probe.status() else { panic!() };
140/// assert_eq!(metrics.overshoot, 0.0);
141/// assert_eq!(metrics.final_value, 1.0);
142/// ```
143#[derive(Clone, Debug, PartialEq)]
144pub struct StepProbe {
145    config: StepConfig,
146    /// The filter's time constant, in s (0: no filter).
147    filter_tau_s: f32,
148    /// The measurement at the step and the setpoint held, once the first tick ran.
149    start: Option<(f32, f32)>,
150    elapsed_s: f32,
151    filtered: f32,
152    peak: f32,
153    peak_time_s: f32,
154    min_after_peak: f32,
155    rise_from_s: Option<f32>,
156    rise_to_s: Option<f32>,
157    in_band_since_s: Option<f32>,
158    saturated_s: f32,
159    result: Option<Result<StepMetrics, StepAbort>>,
160}
161
162/// Where a [`StepProbe`] stands.
163#[derive(Clone, Copy, Debug, PartialEq)]
164pub enum StepStatus {
165    /// Holding the step.
166    Running {
167        /// Time since the step, in seconds.
168        elapsed_s: f32,
169    },
170    /// The window ended.
171    Done(StepMetrics),
172    /// The response ran the wrong way or away.
173    Aborted(StepAbort),
174}
175
176impl StepProbe {
177    /// A probe ready to step.
178    ///
179    /// # Panics
180    ///
181    /// If `config` is invalid ([`StepConfig::validate`]).
182    pub fn new(config: StepConfig) -> Self {
183        if let Err(error) = config.validate() {
184            panic!("invalid StepConfig: {error}");
185        }
186        let filter_tau_s = if config.filter_hz > 0.0 {
187            1.0 / (2.0 * PI * config.filter_hz)
188        } else {
189            0.0
190        };
191        Self {
192            config,
193            filter_tau_s,
194            start: None,
195            elapsed_s: 0.0,
196            filtered: 0.0,
197            peak: 0.0,
198            peak_time_s: 0.0,
199            min_after_peak: 0.0,
200            rise_from_s: None,
201            rise_to_s: None,
202            in_band_since_s: None,
203            saturated_s: 0.0,
204            result: None,
205        }
206    }
207
208    /// Advances the probe by `dt` seconds with the loop's `measurement` and whether its output
209    /// was clipped, and returns the setpoint to hold. The first call records the starting
210    /// measurement (a NaN one is taken as 0).
211    ///
212    /// # Panics
213    ///
214    /// If `dt` is not positive and finite.
215    pub fn step(&mut self, dt: f32, measurement: f32, saturated: bool) -> f32 {
216        assert_dt(dt);
217        let (start, setpoint) = match self.start {
218            Some(start) => {
219                self.elapsed_s += dt;
220                start
221            }
222            None => {
223                let start = if measurement.is_finite() {
224                    measurement
225                } else {
226                    0.0
227                };
228                let held = (start, start + self.config.amplitude);
229                self.start = Some(held);
230                held
231            }
232        };
233        if self.result.is_some() {
234            return setpoint;
235        }
236        if saturated {
237            self.saturated_s += dt;
238        }
239        let response = (measurement - start) / self.config.amplitude;
240        if response.is_finite() {
241            self.track(dt, response);
242        }
243        if self.elapsed_s + 0.5 * dt >= self.config.duration_s && self.result.is_none() {
244            self.result = Some(Ok(self.metrics()));
245        }
246        setpoint
247    }
248
249    /// Filters one response sample and updates the metrics; aborts on a reversed or runaway
250    /// response.
251    fn track(&mut self, dt: f32, response: f32) {
252        // With no filter (τ 0) the gain is 1: the response itself.
253        self.filtered += dt / (dt + self.filter_tau_s) * (response - self.filtered);
254        let (y, t) = (self.filtered, self.elapsed_s);
255        if y > self.peak {
256            self.peak = y;
257            self.peak_time_s = t;
258            self.min_after_peak = y;
259        } else if y < self.min_after_peak {
260            self.min_after_peak = y;
261        }
262        if self.rise_from_s.is_none() && y >= RISE_FROM {
263            self.rise_from_s = Some(t);
264        }
265        if self.rise_to_s.is_none() && y >= RISE_TO {
266            self.rise_to_s = Some(t);
267        }
268        let in_band = (y - 1.0).abs() <= self.config.settle_band;
269        self.in_band_since_s = match (in_band, self.in_band_since_s) {
270            (true, Some(since)) => Some(since),
271            (true, None) => Some(t),
272            (false, _) => None,
273        };
274        if y.abs() > RUNAWAY {
275            self.result = Some(Err(StepAbort::Runaway));
276        } else if y < REVERSED && t > REVERSED_AFTER * self.config.duration_s {
277            self.result = Some(Err(StepAbort::Reversed));
278        }
279    }
280
281    fn metrics(&self) -> StepMetrics {
282        let rise_time_s = match (self.rise_from_s, self.rise_to_s) {
283            (Some(from), Some(to)) => Some(to - from),
284            _ => None,
285        };
286        StepMetrics {
287            amplitude: self.config.amplitude,
288            peak: self.peak,
289            peak_time_s: self.peak_time_s,
290            overshoot: (self.peak - 1.0).max(0.0),
291            rise_time_s,
292            settling_time_s: self.in_band_since_s,
293            bounce_back: self.peak - self.min_after_peak,
294            final_value: self.filtered,
295            saturated_s: self.saturated_s,
296        }
297    }
298
299    /// Where the probe stands.
300    pub fn status(&self) -> StepStatus {
301        match self.result {
302            None => StepStatus::Running {
303                elapsed_s: self.elapsed_s,
304            },
305            Some(Ok(metrics)) => StepStatus::Done(metrics),
306            Some(Err(abort)) => StepStatus::Aborted(abort),
307        }
308    }
309}
310
311/// Running statistics of one metric over several steps.
312#[derive(Clone, Copy, Debug, Default, PartialEq)]
313pub struct Stat {
314    /// Samples taken.
315    pub count: usize,
316    sum: f32,
317    /// The smallest sample (0 with none).
318    pub min: f32,
319    /// The largest sample (0 with none).
320    pub max: f32,
321}
322
323impl Stat {
324    /// Adds a sample.
325    pub fn add(&mut self, value: f32) {
326        if self.count == 0 {
327            self.min = value;
328            self.max = value;
329        } else {
330            self.min = self.min.min(value);
331            self.max = self.max.max(value);
332        }
333        self.count += 1;
334        self.sum += value;
335    }
336
337    /// The mean, or `None` with no samples.
338    pub fn mean(&self) -> Option<f32> {
339        (self.count > 0).then(|| self.sum / self.count as f32)
340    }
341}
342
343/// Statistics over a series of [`StepMetrics`] (e.g. alternating steps of one loop): each
344/// metric's mean and range, how many steps never rose or settled, and the overshoot per
345/// direction, whose difference shows a trim or CG offset. Plain data, no allocation.
346///
347/// # Examples
348///
349/// ```
350/// use stable_flight::tuning::{StepMetrics, StepSummary};
351///
352/// let mut summary = StepSummary::default();
353/// summary.add(&StepMetrics { amplitude: 1.0, overshoot: 0.2, ..Default::default() });
354/// summary.add(&StepMetrics { amplitude: -1.0, overshoot: 0.1, ..Default::default() });
355/// assert_eq!(summary.overshoot.mean(), Some(0.15));
356/// assert_eq!(summary.overshoot_positive.mean(), Some(0.2));
357/// ```
358#[derive(Clone, Copy, Debug, Default, PartialEq)]
359pub struct StepSummary {
360    /// [`StepMetrics::overshoot`] over every step.
361    pub overshoot: Stat,
362    /// Overshoot of the steps with a positive amplitude.
363    pub overshoot_positive: Stat,
364    /// Overshoot of the steps with a negative amplitude.
365    pub overshoot_negative: Stat,
366    /// [`StepMetrics::rise_time_s`] over the steps that rose.
367    pub rise_time_s: Stat,
368    /// [`StepMetrics::settling_time_s`] over the steps that settled.
369    pub settling_time_s: Stat,
370    /// [`StepMetrics::bounce_back`].
371    pub bounce_back: Stat,
372    /// [`StepMetrics::final_value`].
373    pub final_value: Stat,
374    /// How far each step's peak went past where it ended, or past the step when it ended short
375    /// of it: `peak − max(1, final_value)`, or 0. A step held past the step by a disturbance,
376    /// without ringing, reads 0 here though its [`overshoot`](StepMetrics::overshoot) reads how
377    /// far past it ended (#564). Meaningful when the window outlasts the rise, so the end is
378    /// where the response settled.
379    pub overshoot_past_end: Stat,
380    /// Steps that never reached 90%.
381    pub not_risen: usize,
382    /// Steps that ended outside the settle band.
383    pub not_settled: usize,
384}
385
386impl StepSummary {
387    /// Adds one step's metrics.
388    pub fn add(&mut self, metrics: &StepMetrics) {
389        self.overshoot.add(metrics.overshoot);
390        if metrics.amplitude > 0.0 {
391            self.overshoot_positive.add(metrics.overshoot);
392        } else {
393            self.overshoot_negative.add(metrics.overshoot);
394        }
395        match metrics.rise_time_s {
396            Some(rise) => self.rise_time_s.add(rise),
397            None => self.not_risen += 1,
398        }
399        match metrics.settling_time_s {
400            Some(settling) => self.settling_time_s.add(settling),
401            None => self.not_settled += 1,
402        }
403        self.bounce_back.add(metrics.bounce_back);
404        let settled_at = metrics.final_value.max(1.0);
405        self.overshoot_past_end
406            .add((metrics.peak - settled_at).max(0.0));
407        self.final_value.add(metrics.final_value);
408    }
409
410    /// Steps added.
411    pub fn count(&self) -> usize {
412        self.overshoot.count
413    }
414}