Skip to main content

stable_flight/tuning/wing/
design.rs

1//! Gains for a wing axis from its fitted model: see [`WingDesign`].
2
3use super::WingModel;
4use crate::controllers::{InvalidConfig, RateGains, check, check_positive};
5use crate::stabilizers::plane::PlaneAxisGains;
6use crate::tuning::{StepConfig, StepMetrics, StepProbe, StepStatus};
7
8#[cfg(test)]
9mod tests;
10
11/// The tick the model steps at, in s: the flight loop's 250 Hz.
12const MODEL_DT: f32 = 0.004;
13
14/// The rate P values the design tries: 16 from 0.005 to 10, evenly spaced in ratio (×1.66),
15/// spanning the sim's planes' 0.02–2.5 (#533).
16const P_GRID: [f32; 16] = [
17    0.005, 0.0083, 0.0138, 0.0229, 0.0381, 0.0632, 0.105, 0.175, 0.29, 0.482, 0.8, 1.33, 2.21,
18    3.67, 6.09, 10.0,
19];
20
21/// The rate I values the design tries: none, then 11 from 0.01 to 10 (×2), spanning the sim's
22/// planes' 0.04–6.5 (#533).
23const I_GRID: [f32; 12] = [
24    0.0, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.63, 1.26, 2.51, 5.01, 10.0,
25];
26
27const CELLS: usize = P_GRID.len() * I_GRID.len();
28
29/// The bisection stops once the passing time constant is within this ratio of the failing
30/// one.
31const TAU_RATIO: f32 = 1.05;
32
33/// What the design holds a step on the model to, and the limits the model flies under.
34#[derive(Clone, Copy, Debug, PartialEq)]
35pub struct WingDesignConfig {
36    /// The attitude step, in rad, held for `step_duration_s`.
37    pub amplitude_rad: f32,
38    /// How long the step is held, in s.
39    pub step_duration_s: f32,
40    /// The attitude loop's rate limit, in rad/s.
41    pub max_rate_radps: f32,
42    /// The moment the rate loop may command, normalized: full deflection less the trim and a
43    /// margin.
44    pub max_moment: f32,
45    /// The rate loop's integral limit, in rad of accumulated rate error.
46    pub max_integral: f32,
47    /// The trim the rate loop adds without its integral, normalized
48    /// ([`PlaneRateControllerConfig::trim`](crate::controllers::PlaneRateControllerConfig)):
49    /// the integral holds the rest of the model's [`trim_moment`](WingModel::trim_moment).
50    pub static_trim: f32,
51    /// Largest overshoot, as a fraction of the step.
52    pub max_overshoot: f32,
53    /// Longest the moment may clip, in s.
54    pub max_saturated_s: f32,
55    /// The time constants the design may pick, in s, from the least to the most.
56    pub time_constant_range_s: [f32; 2],
57    /// The 10–90% rise allowed, in time constants: a first-order response rises in 2.2.
58    pub rise_per_time_constant: f32,
59}
60
61impl WingDesignConfig {
62    /// Checks that every field is positive and finite (`max_overshoot` and `max_saturated_s`
63    /// may be 0, `max_moment` at most 1) and the time constant range is in order.
64    ///
65    /// # Examples
66    ///
67    /// ```
68    /// use stable_flight::tuning::WingDesignConfig;
69    ///
70    /// let config = WingDesignConfig {
71    ///     amplitude_rad: 0.17,
72    ///     step_duration_s: 4.0,
73    ///     max_rate_radps: 1.0,
74    ///     max_moment: 0.8,
75    ///     max_integral: 2.0,
76    ///     static_trim: 0.0,
77    ///     max_overshoot: 0.05,
78    ///     max_saturated_s: 0.042,
79    ///     time_constant_range_s: [0.2, 1.5],
80    ///     rise_per_time_constant: 2.2,
81    /// };
82    /// assert!(config.validate().is_ok());
83    /// assert!(WingDesignConfig { max_moment: 1.5, ..config }.validate().is_err());
84    /// ```
85    pub fn validate(&self) -> Result<(), InvalidConfig> {
86        check_positive("amplitude_rad", self.amplitude_rad)?;
87        check_positive("step_duration_s", self.step_duration_s)?;
88        check_positive("max_rate_radps", self.max_rate_radps)?;
89        check(
90            "max_moment",
91            self.max_moment > 0.0 && self.max_moment <= 1.0,
92            "in (0, 1]",
93        )?;
94        check_positive("max_integral", self.max_integral)?;
95        check("static_trim", self.static_trim.abs() <= 1.0, "in [-1, 1]")?;
96        check(
97            "max_overshoot",
98            self.max_overshoot >= 0.0 && self.max_overshoot.is_finite(),
99            "non-negative and finite",
100        )?;
101        check(
102            "max_saturated_s",
103            self.max_saturated_s >= 0.0 && self.max_saturated_s.is_finite(),
104            "non-negative and finite",
105        )?;
106        let [least, most] = self.time_constant_range_s;
107        check_positive("time_constant_range_s[0]", least)?;
108        check(
109            "time_constant_range_s[1]",
110            most > least && most.is_finite(),
111            "finite and above time_constant_range_s[0]",
112        )?;
113        check_positive("rise_per_time_constant", self.rise_per_time_constant)
114    }
115}
116
117/// Where a [`WingDesign`] stands.
118#[derive(Clone, Copy, Debug, PartialEq)]
119pub enum WingDesignStatus {
120    /// Still stepping candidates on the model.
121    Running,
122    /// The designed gains.
123    Done(PlaneAxisGains),
124    /// The model can't be designed for: its control or damping isn't positive, or no gains
125    /// meet the targets at the slowest time constant.
126    Failed,
127}
128
129/// Designs one wing axis's rate gains and attitude time constant on its fitted
130/// [`WingModel`], by stepping the attitude loop on the model rather than in flight.
131///
132/// The feedforward is the model's: the moment that holds a rate against the damping. On a
133/// stiff axis (stiffness above 0, a wing's pitch) a damping fitted at or below 0 is read as
134/// none, so no feedforward: the angle of attack follows the rate, and the fit splits the
135/// damping loosely between the two. For P, I,
136/// and the time constant τ, each candidate flies an attitude step on the model through the
137/// plane's loops (the rate target the error over τ within the rate limit, the moment its P, I,
138/// and feedforward terms within the limit) and passes when the step overshoots by no more than
139/// the allowance, settles, rises within `rise_per_time_constant` × τ, and clips for no longer
140/// than allowed: the plane spec's targets. τ is bisected to the quickest at which some P and I
141/// on a coarse grid pass (16 × 12), then raised by 15% for margin; at that τ the design takes
142/// the passing P and I farthest from any failing one on the grid, the middle of what works,
143/// so a model a little off still flies. An I too small to hold the model's trim (beyond the
144/// static trim) within half the integral limit never passes: the integral would clip holding
145/// it. The airplane's pitch designed at I 0.25 against a 2 rad limit sat 1.75° off its held
146/// attitude, slowed 1.75 m/s, and its stage timed out settling (#534).
147///
148/// Each candidate is a step of up to `step_duration_s` on the model at 250 Hz, a few thousand
149/// multiplies; a design takes up to about 1,350. [`advance`](Self::advance) runs a given number
150/// of candidates, so a host spreads the design over its updates.
151///
152/// # Examples
153///
154/// ```
155/// use stable_flight::tuning::{WingDesign, WingDesignConfig, WingDesignStatus, WingModel};
156///
157/// let model = WingModel {
158///     stiffness_per_s2: 0.0,
159///     damping_per_s: 8.0,
160///     control_radps2: 40.0,
161///     lag_s: 0.02,
162///     delay_s: 0.0,
163///     path_turn_per_s: 0.0,
164///     trim_moment: 0.0,
165/// };
166/// let config = WingDesignConfig {
167///     amplitude_rad: 0.5,
168///     step_duration_s: 4.0,
169///     max_rate_radps: 1.2,
170///     max_moment: 0.8,
171///     max_integral: 2.0,
172///     static_trim: 0.0,
173///     max_overshoot: 0.05,
174///     max_saturated_s: 0.042,
175///     time_constant_range_s: [0.2, 1.5],
176///     rise_per_time_constant: 2.2,
177/// };
178/// let mut design = WingDesign::new(model, config);
179/// while design.advance(100) == WingDesignStatus::Running {}
180/// let WingDesignStatus::Done(gains) = design.advance(1) else { panic!("no design") };
181/// assert_eq!(gains.rate.ff, model.feedforward());
182/// ```
183#[derive(Clone, Copy, Debug, PartialEq)]
184pub struct WingDesign {
185    model: WingModel,
186    config: WingDesignConfig,
187    /// The least I that holds the model's trim within [`TRIM_INTEGRAL_SHARE`] of the limit.
188    min_i: f32,
189    phase: Phase,
190}
191
192/// The share of the integral limit the trim may take: the rest answers steps.
193const TRIM_INTEGRAL_SHARE: f32 = 0.5;
194
195#[derive(Clone, Copy, Debug, PartialEq)]
196enum Phase {
197    /// Searching the grid at `tau_s` for a passing cell, from `cell`; `passing_tau_s` is the
198    /// quickest τ found to pass so far, `failing_tau_s` the slowest found to fail.
199    Bisect {
200        tau_s: f32,
201        cell: usize,
202        passing_tau_s: Option<f32>,
203        failing_tau_s: f32,
204    },
205    /// Mapping which cells pass at the design's `tau_s`, up to `cell`.
206    Map {
207        tau_s: f32,
208        cell: usize,
209        passes: [bool; CELLS],
210    },
211    Done(WingDesignStatus),
212}
213
214impl WingDesign {
215    /// A design of `model`'s axis to `config`'s targets, ready to [`advance`](Self::advance).
216    ///
217    /// # Panics
218    ///
219    /// If `config` is invalid ([`WingDesignConfig::validate`]).
220    pub fn new(model: WingModel, config: WingDesignConfig) -> Self {
221        if let Err(error) = config.validate() {
222            panic!("invalid WingDesignConfig: {error}");
223        }
224        // On a stiff axis the fit trades damping for stiffness, so a damping at or below 0
225        // reads as none: the eXplora's pitch fits 0.89/s of damping from its own gains and
226        // −0.72/s from three times them, its stiffness 62/s² and 96/s² (#618).
227        let stiff = model.stiffness_per_s2 > 0.0;
228        let usable = model.control_radps2 > 0.0
229            && (model.damping_per_s > 0.0 || stiff)
230            && model.feedforward().is_finite();
231        let model = WingModel {
232            damping_per_s: model.damping_per_s.max(0.0),
233            ..model
234        };
235        let [least_s, most_s] = config.time_constant_range_s;
236        let phase = if usable {
237            // The slowest first: if nothing passes there, nothing will.
238            Phase::Bisect {
239                tau_s: most_s,
240                cell: 0,
241                passing_tau_s: None,
242                failing_tau_s: least_s / TAU_RATIO,
243            }
244        } else {
245            Phase::Done(WingDesignStatus::Failed)
246        };
247        let integral_trim = (model.trim_moment - config.static_trim).abs();
248        Self {
249            model,
250            config,
251            min_i: integral_trim / (TRIM_INTEGRAL_SHARE * config.max_integral),
252            phase,
253        }
254    }
255
256    /// Steps up to `candidates` candidates on the model, and returns where the design stands.
257    pub fn advance(&mut self, candidates: usize) -> WingDesignStatus {
258        for _ in 0..candidates {
259            if let Phase::Done(status) = self.phase {
260                return status;
261            }
262            self.phase = self.next_phase();
263        }
264        match self.phase {
265            Phase::Done(status) => status,
266            _ => WingDesignStatus::Running,
267        }
268    }
269
270    /// The phase after stepping one candidate.
271    fn next_phase(&self) -> Phase {
272        match self.phase {
273            Phase::Bisect {
274                tau_s,
275                cell,
276                passing_tau_s,
277                failing_tau_s,
278            } => {
279                if self.passes(cell, tau_s) {
280                    self.bisected(failing_tau_s, Some(tau_s))
281                } else if cell + 1 < CELLS {
282                    Phase::Bisect {
283                        tau_s,
284                        cell: cell + 1,
285                        passing_tau_s,
286                        failing_tau_s,
287                    }
288                } else if passing_tau_s.is_none() {
289                    // Nothing passes at the slowest time constant.
290                    Phase::Done(WingDesignStatus::Failed)
291                } else {
292                    self.bisected(tau_s, passing_tau_s)
293                }
294            }
295            Phase::Map {
296                tau_s,
297                cell,
298                mut passes,
299            } => {
300                passes[cell] = self.passes(cell, tau_s);
301                if cell + 1 < CELLS {
302                    Phase::Map {
303                        tau_s,
304                        cell: cell + 1,
305                        passes,
306                    }
307                } else {
308                    Phase::Done(self.pick(tau_s, &passes))
309                }
310            }
311            Phase::Done(status) => Phase::Done(status),
312        }
313    }
314
315    /// The next τ to search between `failing_tau_s` and `passing_tau_s` (geometric middle), or
316    /// the map at the passing one with margin once they're close.
317    fn bisected(&self, failing_tau_s: f32, passing_tau_s: Option<f32>) -> Phase {
318        let passing_tau_s = passing_tau_s.unwrap_or_else(|| unreachable!("bisected after a pass"));
319        if passing_tau_s <= failing_tau_s * TAU_RATIO {
320            let most_s = self.config.time_constant_range_s[1];
321            return Phase::Map {
322                tau_s: (passing_tau_s * TAU_MARGIN).min(most_s),
323                cell: 0,
324                passes: [false; CELLS],
325            };
326        }
327        Phase::Bisect {
328            tau_s: libm::sqrtf(failing_tau_s * passing_tau_s),
329            cell: 0,
330            passing_tau_s: Some(passing_tau_s),
331            failing_tau_s,
332        }
333    }
334
335    /// The gains at the passing cell farthest, in grid steps along P and I, from a failing
336    /// one or the grid's edge.
337    fn pick(&self, tau_s: f32, passes: &[bool; CELLS]) -> WingDesignStatus {
338        let passing = |p: isize, i: isize| {
339            let inside =
340                (0..P_GRID.len() as isize).contains(&p) && (0..I_GRID.len() as isize).contains(&i);
341            inside && passes[p as usize * I_GRID.len() + i as usize]
342        };
343        let depth = |p: isize, i: isize| {
344            (1..)
345                .take_while(|&d| {
346                    [(d, 0), (-d, 0), (0, d), (0, -d)]
347                        .iter()
348                        .all(|&(dp, di)| passing(p + dp, i + di))
349                })
350                .count()
351        };
352        let best = (0..CELLS)
353            .filter(|&cell| passes[cell])
354            .map(|cell| {
355                let (p, i) = (
356                    (cell / I_GRID.len()) as isize,
357                    (cell % I_GRID.len()) as isize,
358                );
359                (cell, depth(p, i))
360            })
361            // The first deepest: `max_by_key` keeps the last of a tie.
362            .fold(
363                None,
364                |best: Option<(usize, usize)>, (cell, depth)| match best {
365                    Some((_, kept)) if kept >= depth => best,
366                    _ => Some((cell, depth)),
367                },
368            );
369        match best {
370            Some((cell, _)) => WingDesignStatus::Done(self.gains(cell, tau_s)),
371            None => WingDesignStatus::Failed,
372        }
373    }
374
375    /// The axis gains at grid `cell` and `tau_s`.
376    fn gains(&self, cell: usize, tau_s: f32) -> PlaneAxisGains {
377        PlaneAxisGains {
378            rate: RateGains {
379                p: P_GRID[cell / I_GRID.len()],
380                i: I_GRID[cell % I_GRID.len()],
381                ff: self.model.feedforward(),
382            },
383            time_constant_s: tau_s,
384        }
385    }
386
387    /// Whether the step on the model at grid `cell` and `tau_s` meets the targets.
388    fn passes(&self, cell: usize, tau_s: f32) -> bool {
389        let gains = self.gains(cell, tau_s);
390        if gains.rate.i < self.min_i {
391            return false;
392        }
393        model_step(&self.model, gains, &self.config)
394            .is_some_and(|metrics| meets_targets(&metrics, tau_s, &self.config))
395    }
396}
397
398/// The margin on the quickest passing time constant: a model a little off still settles.
399const TAU_MARGIN: f32 = 1.15;
400
401/// Whether `metrics` of a step at time constant `tau_s` meet `config`'s targets: overshoot
402/// within the allowance, settled, risen within the allowed time constants, clipped no longer
403/// than allowed.
404pub(crate) fn meets_targets(metrics: &StepMetrics, tau_s: f32, config: &WingDesignConfig) -> bool {
405    let max_rise_s = config.rise_per_time_constant * tau_s;
406    metrics.overshoot <= config.max_overshoot
407        && metrics.settling_time_s.is_some()
408        && metrics.saturated_s <= config.max_saturated_s
409        && metrics
410            .rise_time_s
411            .is_some_and(|rise_s| rise_s <= max_rise_s)
412}
413
414/// An attitude step of `config`'s amplitude on `model`, flown by the plane's loops at `gains`
415/// from level and still, measured by a [`StepProbe`] as a flight step is; `None` when the step
416/// aborts or overshoots past the allowance (no need to fly it out).
417fn model_step(
418    model: &WingModel,
419    gains: PlaneAxisGains,
420    config: &WingDesignConfig,
421) -> Option<StepMetrics> {
422    let RateGains { p, i, ff } = gains.rate;
423    let surface_share = MODEL_DT / (MODEL_DT + model.lag_s);
424    let delay_ticks = libm::roundf(model.delay_s / MODEL_DT) as usize;
425    let mut probe = StepProbe::new(StepConfig {
426        amplitude: config.amplitude_rad,
427        duration_s: config.step_duration_s,
428        settle_band: 0.1,
429        filter_hz: 0.0,
430    });
431    // Moments on their way to the surfaces, oldest first, as a ring.
432    let mut queue = [0.0f32; MAX_MODEL_DELAY_TICKS];
433    let delay_ticks = delay_ticks.min(MAX_MODEL_DELAY_TICKS);
434    let (mut angle_rad, mut rate_radps, mut alpha_rad) = (0.0f32, 0.0f32, 0.0f32);
435    let (mut surface, mut integral, mut clipped) = (0.0f32, 0.0f32, false);
436    let peak_limit = 1.0 + config.max_overshoot;
437    let mut tick = 0usize;
438    loop {
439        let target_rad = probe.step(MODEL_DT, angle_rad, clipped);
440        match probe.status() {
441            StepStatus::Running { .. } => {}
442            StepStatus::Done(metrics) => return Some(metrics),
443            StepStatus::Aborted(_) => return None,
444        }
445        if angle_rad > peak_limit * config.amplitude_rad {
446            return None;
447        }
448        let rate_target_radps = ((target_rad - angle_rad) / gains.time_constant_s)
449            .clamp(-config.max_rate_radps, config.max_rate_radps);
450        let error_radps = rate_target_radps - rate_radps;
451        integral =
452            (integral + error_radps * MODEL_DT).clamp(-config.max_integral, config.max_integral);
453        let raw = p * error_radps + i * integral + ff * rate_target_radps;
454        let moment = raw.clamp(-config.max_moment, config.max_moment);
455        clipped = raw.abs() > config.max_moment;
456        let felt = if delay_ticks == 0 {
457            moment
458        } else {
459            let slot = tick % delay_ticks;
460            core::mem::replace(&mut queue[slot], moment)
461        };
462        surface += surface_share * (felt - surface);
463        let accel_radps2 = -model.stiffness_per_s2 * alpha_rad - model.damping_per_s * rate_radps
464            + model.control_radps2 * surface;
465        alpha_rad += (rate_radps - model.path_turn_per_s * alpha_rad) * MODEL_DT;
466        angle_rad += rate_radps * MODEL_DT;
467        rate_radps += accel_radps2 * MODEL_DT;
468        tick += 1;
469    }
470}
471
472/// The longest delay the model flies, in ticks: 100 ms, past the fit's 40 ms.
473const MAX_MODEL_DELAY_TICKS: usize = 25;