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