Skip to main content

stable_flight/tuning/
design.rs

1//! Gains from an identified [`RateModel`] by loop shaping: see [`design_rate`] and
2//! [`design_angle_p`].
3//!
4//! Both read the model's frequency response and set a gain for a target
5//! [phase margin](https://github.com/wboayue/stable-flight/blob/main/docs/glossary.md): how far the loop is from oscillating where its
6//! open-loop gain crosses 1. The rule and its alternatives (PX4's pole placement, a step search
7//! on the model) are in `docs/architecture/autotune-design-search.md#design`; the comparison behind them is the
8//! `autotune_methods` sweep in `stable-flight-sim` (#312).
9
10use core::f32::consts::PI;
11
12use nalgebra::Complex;
13use thiserror::Error;
14
15use super::RateModel;
16use super::identify::unit_delay;
17
18use crate::controllers::{Gains, GyroFilters, InvalidConfig, check, check_positive};
19
20#[cfg(test)]
21mod tests;
22
23/// Lowest frequency of the design grid, in rad/s: below any copter's crossover.
24const LOWEST_RADPS: f32 = 0.1;
25
26/// Points on the log-spaced grid from [`LOWEST_RADPS`] to Nyquist: about 2% apart.
27const GRID_POINTS: usize = 400;
28
29/// Bisections between two grid points to place a crossing, and on angle P.
30const BISECTIONS: usize = 16;
31
32/// How the design sets the gains.
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct LoopShapingConfig {
35    /// The rate loop's phase margin, in degrees, in `(0, 90)`: more is a slower rate loop with
36    /// less overshoot. 65° met the step spec on every clean and delayed sim row; 60° and 55°
37    /// missed on some (#312).
38    pub rate_margin_deg: f32,
39    /// Whether the rate design's D cancels the fitted motor lag ([`design_rate`]); else D is 0
40    /// and P reaches the margin through the lag. Cancelling the lag lets the crossover go as
41    /// far as the delay and the gyro filters allow, about 50 rad/s on every sim copter. Past
42    /// 1/lag the motors fall behind; the crossover sits 1.25–2.5 times 1/lag on the small
43    /// copters but 8.5 times on the Alia 250's 0.17 s lag: rate P 28.6 and D 4.9, against the
44    /// step search's 1.5 without D. Under gyro noise that D drives the motors to their limits (#572).
45    pub cancel_lag: bool,
46    /// The angle loop's phase margin around the designed rate loop, in degrees, in `(0, 90)`.
47    pub angle_margin_deg: f32,
48    /// Least angle P, in rad/s of rate per rad of angle: the bottom of the angle search's range.
49    pub angle_p_min: f32,
50    /// Most angle P, in rad/s per rad: the top of the angle search's range.
51    pub angle_p_max: f32,
52    /// Share of the largest angle P that meets the margin kept, in `(0, 1]`, as the search
53    /// backs off its result.
54    pub angle_back_off: f32,
55}
56
57impl LoopShapingConfig {
58    /// Checks every field's stated requirement, and that the angle range is ordered.
59    ///
60    /// # Examples
61    ///
62    /// ```
63    /// use stable_flight::tuning::autotune::COPTER_LOOP_SHAPING;
64    /// use stable_flight::tuning::LoopShapingConfig;
65    ///
66    /// assert!(COPTER_LOOP_SHAPING.validate().is_ok());
67    /// let bad = LoopShapingConfig { rate_margin_deg: 95.0, ..COPTER_LOOP_SHAPING };
68    /// assert!(bad.validate().is_err());
69    /// ```
70    pub fn validate(&self) -> Result<(), InvalidConfig> {
71        let margin = |deg: f32| deg > 0.0 && deg < 90.0;
72        check(
73            "rate_margin_deg",
74            margin(self.rate_margin_deg),
75            "in (0, 90)",
76        )?;
77        check(
78            "angle_margin_deg",
79            margin(self.angle_margin_deg),
80            "in (0, 90)",
81        )?;
82        check_positive("angle_p_min", self.angle_p_min)?;
83        check(
84            "angle_p_max",
85            self.angle_p_max.is_finite() && self.angle_p_max >= self.angle_p_min,
86            "finite and at least angle_p_min",
87        )?;
88        check(
89            "angle_back_off",
90            self.angle_back_off > 0.0 && self.angle_back_off <= 1.0,
91            "in (0, 1]",
92        )
93    }
94}
95
96/// Why a design found no gains.
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
98pub enum DesignError {
99    /// The fitted pole isn't a lag ([`RateModel::lag_s`] is `None`): at or past 1, the fit
100    /// grows rather than lags.
101    #[error("the fitted model has no motor lag")]
102    NotALag,
103    /// The rate loop's phase never reaches the margin, or falls past it before any frequency,
104    /// or the model's moment doesn't push the axis the way commanded: the model has no usable
105    /// crossover.
106    #[error("no frequency meets the rate margin")]
107    NoCrossover,
108    /// Even the least angle P misses the angle margin around the designed rate loop.
109    #[error("the least angle P misses the angle margin")]
110    AngleUnstable,
111    /// No gains on the wing design's grid meet its targets on the fitted
112    /// [`WingModel`](crate::tuning::WingModel), even at the slowest time constant, or the
113    /// model's control or damping isn't positive ([`WingDesign`](crate::tuning::WingDesign)).
114    #[error("no gains meet the targets on the fitted wing")]
115    NoWingDesign,
116}
117
118/// Rate gains for `model`: P puts the crossover where the loop keeps `config`'s rate margin; D
119/// cancels the motor lag or is 0 ([`cancel_lag`](LoopShapingConfig::cancel_lag)); I stays
120/// `start`'s, since it holds trim rather than shaping the response.
121///
122/// With the lag cancelled, D/P is the fitted lag `τ`, so the PD's zero `1 + τ·s` cancels the
123/// lag's pole, and `C = 1 + τ·(1 − z⁻¹)/dt` is the PD at unit P; otherwise D is 0 and `C = 1`.
124/// P is `1/|C·G·F|` at the first frequency where the phase of `C·G·F` falls to
125/// `−180° + margin`, with `G` the model's [`response`](RateModel::response) and `F` the `gyro`
126/// filters (the stabilizer's
127/// [`gyro_filters_on`](crate::stabilizers::copter::CopterStabilizerConfig::gyro_filters_on)
128/// the axis: its notch, if on, and its low-pass) that the loop's P and D both act through. Its
129/// lag at the crossover is most of the margin: on `quad_x` at 40 Hz, a design that leaves it out keeps about 2° of its 65° (#373).
130/// The kept I isn't in that loop: its lag at the crossover costs the flown loop a little margin
131/// (0.6° at I 0.2 over seven ticks of delay). A fitted integrator past 1 (`r₁ + r₂ > 1`, an
132/// unstable pole from noise, whose phase meets no crossover) is held at 1, the lag kept.
133///
134/// # Errors
135///
136/// [`DesignError::NotALag`] without a lag, [`DesignError::NoCrossover`] when the moment
137/// doesn't push the axis or no frequency on the grid meets the margin.
138///
139/// # Examples
140///
141/// ```
142/// use stable_flight::controllers::{Gains, GyroFilters};
143/// use stable_flight::tuning::autotune::COPTER_LOOP_SHAPING;
144/// use stable_flight::tuning::{RateModel, design_rate};
145///
146/// // quad_x's fit on the sim: a 30 ms lag, one tick of delay.
147/// let model = RateModel {
148///     rate_weights: [1.87437, -0.87447],
149///     moment_weights: [0.0136, 0.0, 0.0],
150///     delay_ticks: 1,
151///     dt_s: 0.004,
152/// };
153/// let start = Gains { p: 0.1, i: 0.0, d: 0.002 };
154/// let gains = design_rate(&model, start, GyroFilters::low_pass(40.0), &COPTER_LOOP_SHAPING).unwrap();
155/// assert!((gains.d / gains.p - model.lag_s().unwrap()).abs() < 1e-6);
156/// ```
157pub fn design_rate(
158    model: &RateModel,
159    start: Gains,
160    gyro: GyroFilters,
161    config: &LoopShapingConfig,
162) -> Result<Gains, DesignError> {
163    let model = &integrating(model);
164    let lag_s = model.lag_s().ok_or(DesignError::NotALag)?;
165    // A reversed axis's phase starts half a turn from an integrator's; through the gyro
166    // filter it then drifts across the margin, which would read as a crossover.
167    if model.moment_effect() <= 0.0 {
168        return Err(DesignError::NoCrossover);
169    }
170    let dt_s = model.dt_s;
171    let d_per_p = if config.cancel_lag { lag_s } else { 0.0 };
172    let unit_pd = Gains {
173        p: 1.0,
174        i: 0.0,
175        d: d_per_p,
176    };
177    let open_loop = |w_radps: f32| {
178        let z1 = unit_delay(w_radps, dt_s);
179        pid_response(unit_pd, z1, dt_s) * model.response(w_radps) * gyro.response(dt_s, z1)
180    };
181    let floor_deg = config.rate_margin_deg - 180.0;
182    let crossover = first_crossing(dt_s, open_loop, |point| point.phase_deg > floor_deg)
183        .ok_or(DesignError::NoCrossover)?;
184    let p = 1.0 / crossover.gain;
185    Ok(Gains {
186        p,
187        i: start.i,
188        d: d_per_p * p,
189    })
190}
191
192/// Angle P for `model` flown on the `rate` gains: the largest in `config`'s range whose angle
193/// loop keeps the angle margin, times the back-off. `angle`'s I and D stay.
194///
195/// The angle loop's open loop is `C_angle · T · dt/(1 − z⁻¹)`: the angle PID, the closed rate
196/// loop `T = P_rate·G/(1 + C_rate·G·F)`, and the integration from rate to angle. In `T`,
197/// `C_rate` is the rate P and D (`BodyRateController`; its I is left out) acting through the
198/// `gyro` filters `F`, and only P acts on the rate setpoint (D acts on the
199/// measured rate). The angle loop reads the attitude, not the filtered rates, so `F` is in the
200/// rate loop alone. Its margin is read where its gain falls to 1, and angle P is bisected on
201/// it. A fitted integrator past 1 is held at 1, as in [`design_rate`].
202///
203/// # Errors
204///
205/// [`DesignError::AngleUnstable`] when even `angle_p_min` misses the margin.
206pub fn design_angle_p(
207    model: &RateModel,
208    rate: Gains,
209    angle: Gains,
210    gyro: GyroFilters,
211    config: &LoopShapingConfig,
212) -> Result<f32, DesignError> {
213    let model = &integrating(model);
214    let dt_s = model.dt_s;
215    let one = Complex::new(1.0, 0.0);
216    // The rate loop's I acts far below the angle crossover (its zero at I/P), so it costs
217    // the margin little, and its integrator around a fit with a pole just outside the unit
218    // circle swings the margin from one near-identical fit to the next (#374): the model
219    // leaves it out.
220    let rate = Gains { i: 0.0, ..rate };
221    let open_loop = |w_radps: f32, angle_p: f32| {
222        let z1 = unit_delay(w_radps, dt_s);
223        let rate_pid = pid_response(rate, z1, dt_s);
224        let plant = model.response(w_radps);
225        let filters = gyro.response(dt_s, z1);
226        let closed_rate = plant * rate.p / (one + rate_pid * plant * filters);
227        let angle_pid = pid_response(
228            Gains {
229                p: angle_p,
230                ..angle
231            },
232            z1,
233            dt_s,
234        );
235        let to_angle = Complex::new(dt_s, 0.0) / (one - z1);
236        angle_pid * closed_rate * to_angle
237    };
238    let floor_deg = config.angle_margin_deg - 180.0;
239    let keeps_margin = |angle_p: f32| {
240        let crossover = first_crossing(dt_s, |w| open_loop(w, angle_p), |point| point.gain > 1.0);
241        crossover.is_some_and(|point| point.phase_deg > floor_deg)
242    };
243    let (low, high) = (config.angle_p_min, config.angle_p_max);
244    if !keeps_margin(low) {
245        return Err(DesignError::AngleUnstable);
246    }
247    if keeps_margin(high) {
248        return Ok(high * config.angle_back_off);
249    }
250    Ok(bisect_geometric(low, high, keeps_margin) * config.angle_back_off)
251}
252
253/// `model` with its integrator held at 1 (`r₁ + r₂ ≤ 1`, the lag's pole `−r₂` kept): a body
254/// integrates its moment exactly, less any rate damping, so a fit past 1 is an unstable pole
255/// from noise, whose phase starts near −180° and meets no crossover (`r₁ + r₂ = 1.00012` on
256/// `quad_x` from a start ringing with 25 ms of delay, #518). A fit at or below 1 stays.
257fn integrating(model: &RateModel) -> RateModel {
258    let [_, r2] = model.rate_weights;
259    if model.rate_weights.iter().sum::<f32>() <= 1.0 {
260        return *model;
261    }
262    RateModel {
263        rate_weights: [1.0 - r2, r2],
264        ..*model
265    }
266}
267
268/// A PID's frequency response at `z1 = e^(−jω·dt)`: `P + I·dt/(1 − z⁻¹) + D·(1 − z⁻¹)/dt`,
269/// core's law in its feedback path (`BodyRateController`, `AttitudeController`: a running
270/// integral and a one-tick difference).
271fn pid_response(gains: Gains, z1: Complex<f32>, dt_s: f32) -> Complex<f32> {
272    let one = Complex::new(1.0, 0.0);
273    let integral = Complex::new(dt_s, 0.0) / (one - z1);
274    let difference = (one - z1) / dt_s;
275    one * gains.p + integral * gains.i + difference * gains.d
276}
277
278/// One frequency of an open loop's response: its gain and its phase in degrees, unwrapped from
279/// [`LOWEST_RADPS`] up, so a lag past −360° reads as such rather than wrapping back toward 0.
280#[derive(Clone, Copy, Debug, PartialEq)]
281struct Point {
282    w_radps: f32,
283    gain: f32,
284    phase_deg: f32,
285}
286
287/// The last point where `above` holds before it first turns false, walking `open_loop` up the
288/// log grid from [`LOWEST_RADPS`] with its phase unwrapped, refined by bisection between that
289/// grid point and the next; `None` if `above` never turns false or is false from the start.
290fn first_crossing(
291    dt_s: f32,
292    open_loop: impl Fn(f32) -> Complex<f32>,
293    above: impl Fn(&Point) -> bool,
294) -> Option<Point> {
295    // The phase on the branch nearest `near_deg`, in degrees.
296    let point = |w_radps: f32, near_deg: f32| {
297        let response = open_loop(w_radps);
298        let raw_deg = libm::atan2f(response.im, response.re).to_degrees();
299        let turns = libm::roundf((near_deg - raw_deg) / 360.0);
300        Point {
301            w_radps,
302            gain: libm::hypotf(response.re, response.im),
303            phase_deg: raw_deg + 360.0 * turns,
304        }
305    };
306    let nyquist_radps = PI / dt_s;
307    let step = libm::powf(nyquist_radps / LOWEST_RADPS, 1.0 / (GRID_POINTS - 1) as f32);
308    // Open loops here start as an integrator: −90°.
309    let mut last = point(LOWEST_RADPS, -90.0);
310    if !above(&last) {
311        return None;
312    }
313    for i in 1..GRID_POINTS {
314        let next = point(LOWEST_RADPS * libm::powf(step, i as f32), last.phase_deg);
315        if !above(&next) {
316            let keeps = |w_radps: f32| above(&point(w_radps, last.phase_deg));
317            let w_radps = bisect_geometric(last.w_radps, next.w_radps, keeps);
318            return Some(point(w_radps, last.phase_deg));
319        }
320        last = next;
321    }
322    None
323}
324
325/// The largest value between `keeps`, where `holds` is true, and `misses`, where it's false,
326/// after [`BISECTIONS`] geometric halvings: the steps are even in ratio, for values that span
327/// orders of magnitude (frequency, angle P).
328fn bisect_geometric(mut keeps: f32, mut misses: f32, holds: impl Fn(f32) -> bool) -> f32 {
329    for _ in 0..BISECTIONS {
330        let middle = libm::sqrtf(keeps * misses);
331        if holds(middle) {
332            keeps = middle;
333        } else {
334            misses = middle;
335        }
336    }
337    keeps
338}