Skip to main content

stable_flight/tuning/
probe.rs

1//! What an autotune stage runs inside the tick: see [`Probe`].
2
3use super::{
4    IdentifyAbort, IdentifyConfig, IdentifyProbe, IdentifyStatus, RateModel, StepAbort, StepConfig,
5    StepMetrics, StepProbe, StepStatus, WingModel, WingStatus,
6};
7use crate::controllers::InvalidConfig;
8
9/// How to excite and measure one loop: what a [`Probe`] runs.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub enum ProbeConfig {
12    /// A step: the loop's setpoint is held at a step and its response measured.
13    Step(StepConfig),
14    /// Identification: a square wave added to the loop's setpoint while its axis's rate and
15    /// moment are recorded and fitted. Its amplitude is in the target loop's setpoint units;
16    /// [`COPTER_IDENTIFY`](crate::tuning::autotune::COPTER_IDENTIFY) is for the roll and pitch
17    /// rate loops.
18    Identify(IdentifyConfig),
19    /// A wing's identification: the [`Identify`](Self::Identify) square wave on a plane's
20    /// rate loop, its axis fitted to a [`WingModel`]
21    /// ([`WingIdentifyProbe`](super::WingIdentifyProbe)). The
22    /// [`PlaneStabilizer`](crate::stabilizers::plane::PlaneStabilizer) hosts it; a [`Probe`]
23    /// flies it as an [`Identify`](Self::Identify), so a copter's firmware doesn't carry the
24    /// wing fit.
25    IdentifyWing(IdentifyConfig),
26}
27
28impl ProbeConfig {
29    /// Checks the probe's config ([`StepConfig::validate`], [`IdentifyConfig::validate`]).
30    ///
31    /// # Examples
32    ///
33    /// ```
34    /// use stable_flight::tuning::autotune::COPTER_RATE_STEP;
35    /// use stable_flight::tuning::{ProbeConfig, StepConfig};
36    ///
37    /// assert!(ProbeConfig::Step(COPTER_RATE_STEP).validate().is_ok());
38    /// let bad = StepConfig { duration_s: 0.0, ..COPTER_RATE_STEP };
39    /// assert!(ProbeConfig::Step(bad).validate().is_err());
40    /// ```
41    pub fn validate(&self) -> Result<(), InvalidConfig> {
42        match self {
43            Self::Step(config) => config.validate(),
44            Self::Identify(config) | Self::IdentifyWing(config) => config.validate(),
45        }
46    }
47
48    /// Whether the probe is an identification (a copter's or a wing's).
49    pub fn is_identify(&self) -> bool {
50        matches!(self, Self::Identify(_) | Self::IdentifyWing(_))
51    }
52}
53
54/// What the host tells a probe about its loop each tick, before the loop's controller runs.
55#[derive(Clone, Copy, Debug, Default, PartialEq)]
56pub struct LoopSignals {
57    /// The loop's setpoint this tick, as its controller would see it (a saturated angle, a
58    /// heading).
59    pub setpoint: f32,
60    /// The error the loop acts on: setpoint − measurement (wrapped for a heading).
61    pub error: f32,
62    /// Whether the loop's output, or the loop under it, was clipped on the last tick.
63    pub saturated: bool,
64    /// The loop's axis's body rate this tick, unfiltered, in rad/s: the identify probe fits the
65    /// airframe from it. A copter's rate loop measures the rate through the gyro low-pass
66    /// instead ([`measurement`](Self::measurement)).
67    pub rate_radps: f32,
68    /// The loop's axis's moment command on the last tick, normalized to `[-1, 1]`: as
69    /// commanded, before the mixer; a clip shows in [`saturated`](Self::saturated).
70    pub last_moment: f32,
71    /// The angle of attack the axis's moment works against, in rad: a wing's pitch axis's,
72    /// nose up from the flight path; 0 on every other axis. A wing identification fits the
73    /// wing's stiffness on it ([`WingIdentifyProbe`](super::WingIdentifyProbe)).
74    pub alpha_rad: f32,
75}
76
77impl LoopSignals {
78    /// The measurement: `setpoint − error`, consistent with the setpoint even for a wrapped
79    /// heading.
80    pub fn measurement(&self) -> f32 {
81        self.setpoint - self.error
82    }
83}
84
85/// Where a running probe stands.
86#[derive(Clone, Copy, Debug, PartialEq)]
87pub enum Progress {
88    /// Time into the step.
89    Step {
90        /// Seconds since the step.
91        elapsed_s: f32,
92    },
93    /// Time into the excitation.
94    Identify {
95        /// Seconds since the excitation began.
96        elapsed_s: f32,
97    },
98}
99
100/// What a finished probe measured.
101#[derive(Clone, Copy, Debug, PartialEq)]
102pub enum Measurement {
103    /// The step response.
104    Step(StepMetrics),
105    /// The axis's fitted model.
106    Identify(RateModel),
107    /// The wing axis's fitted model.
108    Wing(WingModel),
109}
110
111/// Why a probe gave up.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum ProbeAbort {
114    /// The step response ran the wrong way or away.
115    Step(StepAbort),
116    /// The fit couldn't be solved.
117    Identify(IdentifyAbort),
118}
119
120/// Where a probe stands, as its host reports it ([`Tunable::probe`](super::Tunable::probe)).
121#[derive(Clone, Copy, Debug, PartialEq)]
122pub enum ProbeStatus {
123    /// The probe is flying the loop.
124    Running(Progress),
125    /// Measured; the loop is back with its controller.
126    Done(Measurement),
127    /// The probe gave up; the loop is back with its controller.
128    Aborted(ProbeAbort),
129    /// The host idled the loop under test, e.g. a
130    /// [`CopterStabilizer`](crate::stabilizers::copter::CopterStabilizer) angle or heading loop
131    /// on a [`Setpoint::Rate`](crate::Setpoint::Rate) tick (the pilot switched to acro). The
132    /// loop is back with its controller, and the rate tick clears the idle angle loops' I terms.
133    Interrupted,
134}
135
136impl ProbeStatus {
137    /// Whether the probe still flies the loop.
138    pub fn is_running(&self) -> bool {
139        matches!(self, Self::Running(_))
140    }
141}
142
143impl From<StepStatus> for ProbeStatus {
144    fn from(status: StepStatus) -> Self {
145        match status {
146            StepStatus::Running { elapsed_s } => Self::Running(Progress::Step { elapsed_s }),
147            StepStatus::Done(metrics) => Self::Done(Measurement::Step(metrics)),
148            StepStatus::Aborted(abort) => Self::Aborted(ProbeAbort::Step(abort)),
149        }
150    }
151}
152
153impl From<WingStatus> for ProbeStatus {
154    fn from(status: WingStatus) -> Self {
155        match status {
156            WingStatus::Running { elapsed_s } => Self::Running(Progress::Identify { elapsed_s }),
157            WingStatus::Done(model) => Self::Done(Measurement::Wing(model)),
158            WingStatus::Aborted(abort) => Self::Aborted(ProbeAbort::Identify(abort)),
159        }
160    }
161}
162
163impl From<IdentifyStatus> for ProbeStatus {
164    fn from(status: IdentifyStatus) -> Self {
165        match status {
166            IdentifyStatus::Running { elapsed_s } => {
167                Self::Running(Progress::Identify { elapsed_s })
168            }
169            IdentifyStatus::Done(model) => Self::Done(Measurement::Identify(model)),
170            IdentifyStatus::Aborted(abort) => Self::Aborted(ProbeAbort::Identify(abort)),
171        }
172    }
173}
174
175/// One loop's excitation and measurement, stepped by its host inside the tick: the host feeds
176/// it the loop's [`LoopSignals`] before the loop's controller runs and runs the controller on
177/// the setpoint it returns.
178///
179/// The host owns the loop and the handoff; the probe owns the signal and what it measures.
180/// Plain data, no allocation.
181///
182/// # Examples
183///
184/// ```
185/// use stable_flight::tuning::autotune::COPTER_RATE_STEP;
186/// use stable_flight::tuning::{LoopSignals, Probe, ProbeConfig};
187///
188/// let mut probe = Probe::new(ProbeConfig::Step(COPTER_RATE_STEP));
189/// // Rolling right at 0.5 rad/s: the step is 1 rad/s above where it started.
190/// let signals = LoopSignals { setpoint: 0.0, error: -0.5, ..LoopSignals::default() };
191/// assert_eq!(probe.step(0.004, &signals), 0.5 + COPTER_RATE_STEP.amplitude);
192/// assert!(probe.status().is_running());
193/// ```
194#[derive(Clone, Debug, PartialEq)]
195pub struct Probe {
196    kind: Kind,
197}
198
199// The identification's window (13 KB) makes its variant the largest; boxing it would
200// allocate, which core doesn't, and a host holds one probe at a time.
201#[allow(clippy::large_enum_variant)]
202#[derive(Clone, Debug, PartialEq)]
203enum Kind {
204    Step(StepProbe),
205    Identify(IdentifyProbe),
206}
207
208impl Probe {
209    /// A probe ready to run.
210    ///
211    /// # Panics
212    ///
213    /// If `config` is invalid ([`ProbeConfig::validate`]).
214    pub fn new(config: ProbeConfig) -> Self {
215        let kind = match config {
216            ProbeConfig::Step(config) => Kind::Step(StepProbe::new(config)),
217            ProbeConfig::Identify(config) | ProbeConfig::IdentifyWing(config) => {
218                Kind::Identify(IdentifyProbe::new(config))
219            }
220        };
221        Self { kind }
222    }
223
224    /// Whether the probe replaces the loop's setpoint outright (a step) rather than adding to
225    /// it (an identification).
226    pub(crate) fn replaces_setpoint(&self) -> bool {
227        matches!(self.kind, Kind::Step(_))
228    }
229
230    /// Advances the probe by `dt` seconds with the loop's `signals` and returns the setpoint
231    /// the loop's controller runs on this tick, in place of its own.
232    ///
233    /// # Panics
234    ///
235    /// If `dt` is not positive and finite.
236    pub fn step(&mut self, dt: f32, signals: &LoopSignals) -> f32 {
237        match &mut self.kind {
238            Kind::Step(step) => step.step(dt, signals.measurement(), signals.saturated),
239            Kind::Identify(identify) => {
240                let offset = identify.step(dt, signals.rate_radps, signals.last_moment);
241                signals.setpoint + offset
242            }
243        }
244    }
245
246    /// Where the probe stands; never [`ProbeStatus::Interrupted`], which only a host reports.
247    pub fn status(&self) -> ProbeStatus {
248        match &self.kind {
249            Kind::Step(step) => step.status().into(),
250            Kind::Identify(identify) => identify.status().into(),
251        }
252    }
253}