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