stable-flight 0.3.0

no_std autopilot core for Stable Flight: copter, plane, tailsitter, and quadplane guidance and stabilizers, waypoint navigation, failsafe, autotune, mixers, and the per-tick flight loop
Documentation
//! A plane design stage: see [`PlaneDesign`].

use super::{Action, MAX_MEASURE_STOPS};
use crate::stabilizers::plane::PlaneAxisGains;
use crate::tuning::autotune::side::Decide;
use crate::tuning::autotune::{AutotuneAbort, Outcome, PlaneDesignPlan};
use crate::tuning::wing::design::meets_targets;
use crate::tuning::{
    DesignError, Measurement, ProbeAbort, ProbeConfig, StepMetrics, StepSummary, WingDesign,
    WingDesignConfig, WingDesignStatus,
};

#[cfg(test)]
mod tests;

/// Fits a design stage may lose before it fails: a fit that doesn't solve, or a model no gains
/// fly, runs again (the copter design's three, `MAX_UNUSABLE_FITS`).
const MAX_UNUSABLE_FITS: usize = 3;

/// What a sagging pair multiplies I by, at least [`MIN_SAG_I`]: a held attitude whose airspeed
/// bleeds off needs more I than the fit at constant airspeed asks for (#533).
const SAG_I_FACTOR: f32 = 1.5;

/// The I a sagging pair's raise starts from when the design had none.
const MIN_SAG_I: f32 = 0.05;

/// What a pair that holds or ends past its target multiplies I by, at least [`MIN_SAG_I`]:
/// faster than a sag's raise, since the offset is a steady moment that only I supplies, and the
/// fit from level flight sized I for none. Higher reaches it in fewer pairs; a sag's 1.5 left
/// the X-Plane Alia 250, which rolls into its 20° banks against a 0.2 aileron moment, ending
/// steps 1.09–1.22 past through all eight pairs as I climbed from 0.01 to 0.85 (#537). On the
/// sim Alia, its yaw-rate roll moment fitted to X-Plane's held aileron, 2 tunes from every
/// start by the seventh pair and 1.5 fails it (#458).
const HOLD_PAST_I_FACTOR: f32 = 2.0;

/// The most of its overshoot a step that holds past its target gives back, as a share: one
/// that ends this close to its peak isn't swinging past, it's short of a steady moment the
/// fit didn't see, which I supplies. Higher reads more overshoots as offsets and raises I on
/// them; at 0 every overshoot slows the time constant. The Titan Cobra's 30° roll steps in
/// RealFlight peak 0.10–0.15 past and give back 0.01–0.03, against a 0.08 aileron moment the
/// 22 m turn needs (#635).
const HOLD_PAST_BOUNCE_SHARE: f32 = 0.5;

/// How far past its target, as a share of the overshoot limit, a step that swings back may end
/// before the pair also raises I: its overshoot is then part swing, part a steady offset, and
/// a slower time constant alone takes the swing out but leaves the offset. Lower raises I on
/// smaller offsets. The Titan Cobra's 30° roll steps at 14 m/s in RealFlight overshot
/// 0.04–0.07, gave back 0.02–0.05, and ended 1.02–1.04 (#635).
const END_PAST_SHARE: f32 = 0.5;

/// How far apart, as a share of the verify step's settle band, a pair's two steps may end
/// before the pair raises I by [`SAG_I_FACTOR`], ahead of a slow rise's P and an overshoot's
/// time constant: steps that end apart, the usual case one short of its target and the other
/// on or past it, are held off by a steady moment, which only I supplies; a higher P or a
/// slower time constant leaves it. Lower raises I on smaller offsets. The sim Alia 250's 5°
/// pitch steps from its own gains end 1.005 nose-up and 0.90 nose-down, 0.105 apart, the
/// nose-down creeping in over 3 s whatever P; from a third of its gains its first pair ends
/// 0.045 apart and tunes on a raised P. The design converges on every subject at 0.5–1.0 of the
/// band (#688).
const ENDS_APART_SHARE: f32 = 0.75;

/// What a pair that overshoots or clips multiplies the time constant by: a slower attitude loop
/// asks for less rate, so less overshoot and less deflection (#533).
const OVERSHOOT_TAU_FACTOR: f32 = 1.15;

/// What a pair that settles but rises too slowly multiplies P by: one step of the design's
/// grid.
const SLOW_P_FACTOR: f32 = 1.66;

/// A [`PlaneDesignPlan`] as a pure state machine: a wing fit of the stage's axis, gains
/// designed on it over several updates, then attitude pairs flown on the candidate until one
/// meets the targets, each miss nudging the candidate (a sag, a hold past the target, or steps
/// that end apart raise I, a slow rise P, an overshoot or clip the time constant, both I and
/// the time constant an overshoot that swings back but ends past the target).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(in crate::tuning::autotune) struct PlaneDesign {
    plan: PlaneDesignPlan,
    step: Step,
    /// Probes a slow host stopped in a row.
    stops: usize,
    /// Fits the design couldn't use.
    unusable: usize,
}

#[expect(
    clippy::large_enum_variant,
    reason = "one per stage, replaced between stages; the core has no allocator to box with"
)]
#[derive(Clone, Copy, Debug, PartialEq)]
enum Step {
    Fitting,
    Designing(WingDesign),
    /// Flying pair `pair` (from 0) on `candidate`; `first` is the pair's first step, once
    /// measured.
    Verifying {
        candidate: PlaneAxisGains,
        pair: usize,
        first: Option<StepMetrics>,
    },
}

impl PlaneDesign {
    pub(super) fn new(plan: PlaneDesignPlan) -> Self {
        Self {
            plan,
            step: Step::Fitting,
            stops: 0,
            unusable: 0,
        }
    }

    pub(super) fn next(&mut self, on: Decide) -> Action<PlaneAxisGains> {
        match (self.step, on) {
            (Step::Fitting, Decide::Start) => self.fit(),
            (
                Step::Fitting,
                Decide::Measured {
                    measurement: Measurement::Wing(model),
                    stalled: false,
                },
            ) => {
                self.stops = 0;
                self.step = Step::Designing(WingDesign::new(model, self.plan.design));
                Action::Compute
            }
            (
                Step::Fitting,
                Decide::Measured {
                    measurement: Measurement::Wing(_),
                    stalled: true,
                },
            )
            | (Step::Fitting, Decide::Stalled) => self.again(Action::probe(self.identify())),
            (
                Step::Fitting,
                Decide::Aborted {
                    abort: ProbeAbort::Identify(abort),
                },
            ) => self.refit(AutotuneAbort::Probe(ProbeAbort::Identify(abort))),
            (Step::Designing(mut design), Decide::Computing) => {
                match design.advance(self.plan.candidates_per_update) {
                    WingDesignStatus::Running => {
                        self.step = Step::Designing(design);
                        Action::Compute
                    }
                    WingDesignStatus::Done(candidate) => self.verify(candidate, 0),
                    WingDesignStatus::Failed => {
                        self.refit(AutotuneAbort::Design(DesignError::NoWingDesign))
                    }
                }
            }
            // Settled on the candidate: step it.
            (
                Step::Verifying {
                    candidate, first, ..
                },
                Decide::Held { settled: true },
            ) => Action::Probe {
                probe: self.verify_step(first.is_some()),
                gains: Some(candidate),
                commit: None,
                wait_for_settle: true,
            },
            (
                Step::Verifying {
                    candidate,
                    pair,
                    first,
                },
                Decide::Measured {
                    measurement: Measurement::Step(metrics),
                    stalled,
                },
            ) => {
                if stalled {
                    return self.again(Action::Hold { gains: candidate });
                }
                self.stops = 0;
                match first {
                    None => {
                        self.step = Step::Verifying {
                            candidate,
                            pair,
                            first: Some(metrics),
                        };
                        Action::Hold { gains: candidate }
                    }
                    Some(first) => self.judge(candidate, pair, [first, metrics]),
                }
            }
            (Step::Verifying { candidate, .. }, Decide::Stalled) => {
                self.again(Action::Hold { gains: candidate })
            }
            // A candidate that won't hold still, runs away, or leaves the envelope asks for too
            // much: slower.
            (
                Step::Verifying {
                    candidate, pair, ..
                },
                Decide::Held { settled: false }
                | Decide::Aborted {
                    abort: ProbeAbort::Step(_),
                }
                | Decide::Breached { .. },
            ) => self.verify(slower(candidate, &self.plan), pair + 1),
            (_, Decide::Breached { reason }) => Action::Fail(reason),
            (_, Decide::Unsettled) => Action::Fail(AutotuneAbort::NotSettled),
            (_, Decide::Aborted { abort }) => Action::Fail(AutotuneAbort::Probe(abort)),
            _ => Action::Fail(AutotuneAbort::Interrupted),
        }
    }

    fn identify(&self) -> ProbeConfig {
        ProbeConfig::IdentifyWing(self.plan.identify)
    }

    /// Starts a fit.
    fn fit(&mut self) -> Action<PlaneAxisGains> {
        self.step = Step::Fitting;
        Action::probe(self.identify())
    }

    /// A fit the design couldn't use: fit again, or fail with `abort` at
    /// [`MAX_UNUSABLE_FITS`].
    fn refit(&mut self, abort: AutotuneAbort) -> Action<PlaneAxisGains> {
        self.unusable += 1;
        if self.unusable >= MAX_UNUSABLE_FITS {
            return Action::Fail(abort);
        }
        self.fit()
    }

    /// A probe a slow host spoiled: `retry`, or fail the stage at `MAX_MEASURE_STOPS` in a
    /// row.
    fn again(&mut self, retry: Action<PlaneAxisGains>) -> Action<PlaneAxisGains> {
        self.stops += 1;
        if self.stops >= MAX_MEASURE_STOPS {
            return Action::Fail(AutotuneAbort::Stalled);
        }
        retry
    }

    /// Starts pair `pair` on `candidate`, or fails the stage past the plan's pairs. Each step
    /// first holds the candidate until its axis settles on it: the rate loop's integral then
    /// holds what the candidate needs, where one carried over from the committed gains biases
    /// the step. From three times its gains, the airplane's committed roll loop settled with
    /// an I term its candidate's tenth-as-large I took seconds to unwind, and every pair's
    /// second step rose in 3.6 s against the first's 1.1 (#534).
    fn verify(&mut self, candidate: PlaneAxisGains, pair: usize) -> Action<PlaneAxisGains> {
        if pair >= self.plan.max_verify_pairs {
            return Action::Fail(AutotuneAbort::Unverified);
        }
        self.step = Step::Verifying {
            candidate,
            pair,
            first: None,
        };
        Action::Hold { gains: candidate }
    }

    /// The verify step: the plan's, or reversed for a pair's second.
    fn verify_step(&self, second: bool) -> ProbeConfig {
        let step = self.plan.verify;
        ProbeConfig::Step(if second { step.reversed() } else { step })
    }

    /// Finishes on `candidate` when both of `pair`'s steps meet the targets; else flies the
    /// next pair on it nudged: much more I for a step that holds past its target (overshoots
    /// and gives little of it back), more I for a sag (a step that doesn't settle), much more I
    /// and a slower time constant for an overshoot that swings back but still ends past the
    /// target, more I for steps that end apart (a steady moment the fit didn't see), more P for
    /// a step that settles but rises too slowly (the rate loop lags its target), else (an
    /// overshoot that swings back to it, or a clip) a slower time constant.
    /// A slower time constant doesn't speed a slow rise: the airplane's roll rose in 2.0, 2.5,
    /// 3.0, and 3.5 time constants at 0.56, 0.64, 0.74, and 0.85 s (#534).
    fn judge(
        &mut self,
        candidate: PlaneAxisGains,
        pair: usize,
        steps: [StepMetrics; 2],
    ) -> Action<PlaneAxisGains> {
        let tau_s = candidate.time_constant_s;
        let design = &self.plan.design;
        if steps.iter().all(|m| meets_targets(m, tau_s, design)) {
            let mut summary = StepSummary::default();
            steps.iter().for_each(|m| summary.add(m));
            return Action::Finish {
                gains: candidate,
                outcome: Outcome::Tuned,
                steps: Some(summary),
                baseline: None,
            };
        }
        let sags = steps.iter().any(|m| m.settling_time_s.is_none());
        let holds = steps.iter().any(|m| holds_past(m, design));
        let ends_past = steps.iter().any(|m| swings_and_ends_past(m, design));
        let apart = ends_apart(&steps, self.plan.verify.settle_band);
        let max_rise_s = design.rise_per_time_constant * tau_s;
        let slow = steps
            .iter()
            .any(|m| m.rise_time_s.is_none_or(|rise_s| rise_s > max_rise_s));
        let wide = steps
            .iter()
            .any(|m| m.overshoot > design.max_overshoot || m.saturated_s > design.max_saturated_s);
        let mut next = candidate;
        if holds {
            next.rate.i = (candidate.rate.i * HOLD_PAST_I_FACTOR).max(MIN_SAG_I);
        } else if sags {
            next.rate.i = (candidate.rate.i * SAG_I_FACTOR).max(MIN_SAG_I);
        } else if ends_past {
            next.rate.i = (candidate.rate.i * HOLD_PAST_I_FACTOR).max(MIN_SAG_I);
            next = slower(next, &self.plan);
        } else if apart {
            next.rate.i = (candidate.rate.i * SAG_I_FACTOR).max(MIN_SAG_I);
        } else if slow && !wide {
            next.rate.p = candidate.rate.p * SLOW_P_FACTOR;
        } else {
            next = slower(candidate, &self.plan);
        }
        self.verify(next, pair + 1)
    }
}

/// Whether a step overshoots past `design`'s limit and keeps most of it: an offset a slower
/// time constant only widens (the error then carries the moment), where a swing past the target
/// gives most of its overshoot back.
fn holds_past(metrics: &StepMetrics, design: &WingDesignConfig) -> bool {
    metrics.overshoot > design.max_overshoot
        && metrics.bounce_back < HOLD_PAST_BOUNCE_SHARE * metrics.overshoot
}

/// Whether a step overshoots past `design`'s limit, swings back, and still ends past its
/// target by more than [`END_PAST_SHARE`] of the limit.
fn swings_and_ends_past(metrics: &StepMetrics, design: &WingDesignConfig) -> bool {
    metrics.overshoot > design.max_overshoot
        && metrics.final_value - 1.0 > END_PAST_SHARE * design.max_overshoot
}

/// Whether a pair's steps end further apart than [`ENDS_APART_SHARE`] of `settle_band`, each
/// as a share of its own step: a steady moment in one direction holds a nose-up step past its
/// target and the nose-down one short, or the other way round.
fn ends_apart(steps: &[StepMetrics; 2], settle_band: f32) -> bool {
    let [first, second] = steps;
    (first.final_value - second.final_value).abs() > ENDS_APART_SHARE * settle_band
}

/// `candidate` with its time constant raised by [`OVERSHOOT_TAU_FACTOR`], up to the plan's
/// slowest.
fn slower(candidate: PlaneAxisGains, plan: &PlaneDesignPlan) -> PlaneAxisGains {
    let most_s = plan.design.time_constant_range_s[1];
    PlaneAxisGains {
        time_constant_s: (candidate.time_constant_s * OVERSHOOT_TAU_FACTOR).min(most_s),
        ..candidate
    }
}