stable_flight/stabilizers/copter/tuning.rs
1//! Autotune stages hosted by the [`CopterStabilizer`]: one loop's setpoint replaced by a
2//! [`Probe`]. See the "Tuning" section on [`CopterStabilizer`].
3
4use crate::Vec3;
5use crate::tuning::{LoopSignals, Probe, ProbeConfig, ProbeStatus, Tunable};
6
7use super::{CopterStabilizer, CopterStabilizerConfig};
8use crate::controllers::Gains;
9
10#[cfg(test)]
11mod tests;
12
13/// A loop of the [`CopterStabilizer`] that a tuning stage can replace.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum TunedLoop {
16 /// Roll rate loop: a probe sets the roll rate setpoint, in rad/s.
17 RollRate,
18 /// Pitch rate loop: a probe sets the pitch rate setpoint, in rad/s.
19 PitchRate,
20 /// Yaw rate loop: a probe sets the yaw rate setpoint, in rad/s.
21 YawRate,
22 /// Roll angle loop: a probe sets the roll angle setpoint, in rad.
23 Roll,
24 /// Pitch angle loop: a probe sets the pitch angle setpoint, in rad.
25 Pitch,
26 /// Heading loop: a probe sets the heading setpoint, in rad.
27 Heading,
28}
29
30/// Where a [`TunedLoop`] sits in the cascade: the controller that owns it and its axis.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub(super) enum Location {
33 /// The body-rate loop, axis 0 roll, 1 pitch, 2 yaw.
34 Rate(usize),
35 /// The attitude loop, axis 0 roll, 1 pitch.
36 Angle(usize),
37 /// The heading loop.
38 Heading,
39}
40
41impl TunedLoop {
42 /// The gains this loop flies in `config`.
43 ///
44 /// # Examples
45 ///
46 /// ```
47 /// use stable_flight::stabilizers::copter::{CopterStabilizerConfig, TunedLoop};
48 ///
49 /// let mut config = CopterStabilizerConfig::default();
50 /// TunedLoop::Heading.gains_mut(&mut config).p = 4.0;
51 /// assert_eq!(config.yaw.gains.p, 4.0);
52 /// assert_eq!(TunedLoop::Heading.gains(&config).p, 4.0);
53 /// ```
54 pub fn gains(self, config: &CopterStabilizerConfig) -> Gains {
55 let mut config = *config;
56 *self.gains_mut(&mut config)
57 }
58
59 /// The gains this loop flies in `config`, to retune them.
60 pub fn gains_mut(self, config: &mut CopterStabilizerConfig) -> &mut Gains {
61 match self {
62 Self::RollRate => &mut config.body_rate.roll_gains,
63 Self::PitchRate => &mut config.body_rate.pitch_gains,
64 Self::YawRate => &mut config.body_rate.yaw_gains,
65 Self::Roll => &mut config.attitude.roll_gains,
66 Self::Pitch => &mut config.attitude.pitch_gains,
67 Self::Heading => &mut config.yaw.gains,
68 }
69 }
70
71 /// Whether this is a rate loop (the others are angle and heading loops).
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// use stable_flight::stabilizers::copter::TunedLoop;
77 ///
78 /// assert!(TunedLoop::YawRate.is_rate());
79 /// assert!(!TunedLoop::Heading.is_rate());
80 /// ```
81 pub fn is_rate(self) -> bool {
82 matches!(self.location(), Location::Rate(_))
83 }
84
85 /// The rate loop under this angle or heading loop, which flies its rate setpoint; `None`
86 /// for a rate loop.
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// use stable_flight::stabilizers::copter::TunedLoop;
92 ///
93 /// assert_eq!(TunedLoop::Roll.inner(), Some(TunedLoop::RollRate));
94 /// assert_eq!(TunedLoop::RollRate.inner(), None);
95 /// ```
96 pub fn inner(self) -> Option<Self> {
97 match self {
98 Self::Roll => Some(Self::RollRate),
99 Self::Pitch => Some(Self::PitchRate),
100 Self::Heading => Some(Self::YawRate),
101 Self::RollRate | Self::PitchRate | Self::YawRate => None,
102 }
103 }
104
105 /// The angle or heading loop over this rate loop, which sets its setpoint; `None` for an
106 /// angle or heading loop.
107 ///
108 /// # Examples
109 ///
110 /// ```
111 /// use stable_flight::stabilizers::copter::TunedLoop;
112 ///
113 /// assert_eq!(TunedLoop::PitchRate.outer(), Some(TunedLoop::Pitch));
114 /// assert_eq!(TunedLoop::Pitch.outer(), None);
115 /// ```
116 pub fn outer(self) -> Option<Self> {
117 match self {
118 Self::RollRate => Some(Self::Roll),
119 Self::PitchRate => Some(Self::Pitch),
120 Self::YawRate => Some(Self::Heading),
121 Self::Roll | Self::Pitch | Self::Heading => None,
122 }
123 }
124
125 pub(super) fn location(self) -> Location {
126 match self {
127 Self::RollRate => Location::Rate(0),
128 Self::PitchRate => Location::Rate(1),
129 Self::YawRate => Location::Rate(2),
130 Self::Roll => Location::Angle(0),
131 Self::Pitch => Location::Angle(1),
132 Self::Heading => Location::Heading,
133 }
134 }
135}
136
137/// A tuning stage: the loop under test and its probe.
138#[derive(Clone, Debug, PartialEq)]
139pub(super) struct Stage {
140 pub(super) target: TunedLoop,
141 pub(super) probe: Probe,
142 /// The loop has been handed back (finished, interrupted, or stopped): no more override.
143 handed_back: bool,
144 interrupted: bool,
145}
146
147impl Stage {
148 /// Whether the probe still flies the loop.
149 pub(super) fn is_running(&self) -> bool {
150 !self.handed_back
151 }
152
153 fn status(&self) -> ProbeStatus {
154 if self.interrupted {
155 ProbeStatus::Interrupted
156 } else {
157 self.probe.status()
158 }
159 }
160}
161
162impl Tunable<TunedLoop> for CopterStabilizer {
163 /// Starts a probe on `target`: from the next [`stabilize`](crate::Stabilizer::stabilize),
164 /// a [`Probe`] with `config` sets that loop's setpoint (see the "Tuning" section on
165 /// [`CopterStabilizer`]).
166 ///
167 /// # Examples
168 ///
169 /// ```
170 /// use stable_flight::stabilizers::copter::{
171 /// CopterStabilizer, CopterStabilizerConfig, TunedLoop,
172 /// };
173 /// use stable_flight::tuning::autotune::COPTER_RATE_STEP;
174 /// use stable_flight::tuning::{ProbeConfig, ProbeStatus, Tunable};
175 /// use stable_flight::{RateSetpoint, Setpoint, Stabilizer, VehicleState};
176 ///
177 /// let mut stabilizer = CopterStabilizer::new(CopterStabilizerConfig::default());
178 /// stabilizer.start_probe(TunedLoop::RollRate, ProbeConfig::Step(COPTER_RATE_STEP));
179 ///
180 /// // At rest with a zero rate setpoint: the step asks for 1 rad/s of roll, so the loop
181 /// // pushes right.
182 /// let state = VehicleState::default();
183 /// let output = stabilizer.stabilize(0.004, &Setpoint::Rate(RateSetpoint::default()), &state);
184 /// assert!(output.moments.x > 0.0);
185 ///
186 /// assert!(matches!(stabilizer.probe(), Some((TunedLoop::RollRate, ProbeStatus::Running(_)))));
187 /// stabilizer.stop_probe(); // hands the roll rate loop back
188 /// assert!(stabilizer.probe().is_none());
189 /// ```
190 fn start_probe(&mut self, target: TunedLoop, config: ProbeConfig) {
191 self.stop_probe();
192 self.stage = Some(Stage {
193 target,
194 probe: Probe::new(config),
195 handed_back: false,
196 interrupted: false,
197 });
198 }
199
200 fn probe(&self) -> Option<(TunedLoop, ProbeStatus)> {
201 self.stage
202 .as_ref()
203 .map(|stage| (stage.target, stage.status()))
204 }
205
206 fn stop_probe(&mut self) -> Option<(TunedLoop, ProbeStatus)> {
207 self.hand_back();
208 self.stage
209 .take()
210 .map(|stage| (stage.target, stage.status()))
211 }
212}
213
214impl CopterStabilizer {
215 /// Hands a running stage's loop back to its controller: the loop restarts with no
216 /// derivative history, so the setpoint's jump back doesn't kick it, and keeps its I term.
217 /// A no-op when no stage is running.
218 pub(super) fn hand_back(&mut self) {
219 let Some(stage) = &mut self.stage else {
220 return;
221 };
222 if stage.handed_back {
223 return;
224 }
225 stage.handed_back = true;
226 match stage.target.location() {
227 Location::Rate(axis) => self.body_rate.hand_back(axis),
228 Location::Angle(axis) => self.attitude.hand_back(axis),
229 Location::Heading => self.yaw.hand_back(),
230 }
231 }
232
233 /// Which attitude loops keep their integral this tick (roll, pitch, heading): the loop over
234 /// the rate loop a step is flying, none otherwise. The step tilts or turns the vehicle away
235 /// from that loop's setpoint; integrating that error would wind the loop up and kick the
236 /// vehicle at the handoff. At angle P 2 and I 0.25, the sim's `quad_x` then didn't settle
237 /// within 10 s after a large rate step (#579).
238 pub(super) fn held_integrals(&self) -> [bool; 3] {
239 let stepped_axis = self
240 .stage
241 .as_ref()
242 .filter(|stage| stage.is_running() && stage.probe.replaces_setpoint())
243 .and_then(|stage| match stage.target.location() {
244 Location::Rate(axis) => Some(axis),
245 Location::Angle(_) | Location::Heading => None,
246 });
247 [0, 1, 2].map(|axis| stepped_axis == Some(axis))
248 }
249
250 /// Ends a running stage as interrupted: a VTOL's setpoint stopped flying the hover side
251 /// (a plane setpoint, a transition's blend).
252 pub(crate) fn interrupt_stage(&mut self) {
253 if let Some(stage) = &mut self.stage
254 && stage.is_running()
255 {
256 stage.interrupted = true;
257 self.hand_back();
258 }
259 }
260
261 /// Ends a running angle or heading stage as interrupted (its loop is idle on a rate tick).
262 pub(super) fn interrupt_attitude_stage(&mut self) {
263 let Some(stage) = &mut self.stage else {
264 return;
265 };
266 let angle_loop = !matches!(stage.target.location(), Location::Rate(_));
267 if angle_loop && stage.is_running() {
268 stage.interrupted = true;
269 self.hand_back();
270 }
271 }
272
273 /// Where the running stage replaces a value, or None when no stage runs: the one check an
274 /// idle tick pays.
275 pub(super) fn running_stage(&self) -> Option<Location> {
276 self.stage
277 .as_ref()
278 .filter(|stage| stage.is_running())
279 .map(|stage| stage.target.location())
280 }
281
282 /// Steps the running stage with its loop's `signals` and returns the setpoint the loop
283 /// runs on (`None` when no stage runs). The loop is handed back at the end of the tick
284 /// ([`finish_stage`](Self::finish_stage)), after its controller ran.
285 fn step_stage(&mut self, dt: f32, signals: &LoopSignals) -> Option<f32> {
286 let stage = self.stage.as_mut().filter(|stage| stage.is_running())?;
287 Some(stage.probe.step(dt, signals))
288 }
289
290 /// Hands the loop back once its probe has finished; call it at the end of the tick.
291 pub(super) fn finish_stage(&mut self) {
292 let finished = self
293 .stage
294 .as_ref()
295 .is_some_and(|stage| stage.is_running() && !stage.probe.status().is_running());
296 if finished {
297 self.hand_back();
298 }
299 }
300
301 /// Steps a probe on an angle or heading loop before the controllers run. `setpoints` are
302 /// the saturated roll, pitch, and heading setpoints, `error` the body-frame attitude error
303 /// the loops act on, `rates_radps` the body rates: the probe replaces one setpoint.
304 pub(super) fn probe_attitude(
305 &mut self,
306 dt: f32,
307 setpoints: &mut Vec3,
308 error: &Vec3,
309 rates_radps: &Vec3,
310 ) {
311 let Some(location) = self.running_stage() else {
312 return;
313 };
314 let saturated = self.loop_saturated(location);
315 let axis = match location {
316 Location::Angle(axis) => axis,
317 Location::Heading => 2,
318 Location::Rate(_) => return,
319 };
320 let signals = LoopSignals {
321 setpoint: setpoints[axis],
322 error: error[axis],
323 saturated,
324 rate_radps: rates_radps[axis],
325 last_moment: self.last_moments[axis],
326 alpha_rad: 0.0,
327 };
328 self.inject(dt, axis, &signals, setpoints)
329 }
330
331 /// Steps a probe on a rate loop before the rate controller runs: the probe replaces that
332 /// axis's rate in `setpoints`. `filtered_rates_radps` holds the filtered rates the loop
333 /// runs on, `raw_rates_radps` the unfiltered ones the identify fit models the airframe from.
334 pub(super) fn probe_rates(
335 &mut self,
336 dt: f32,
337 setpoints: &mut Vec3,
338 filtered_rates_radps: &Vec3,
339 raw_rates_radps: &Vec3,
340 ) {
341 let Some(location @ Location::Rate(axis)) = self.running_stage() else {
342 return;
343 };
344 let signals = LoopSignals {
345 setpoint: setpoints[axis],
346 error: setpoints[axis] - filtered_rates_radps[axis],
347 saturated: self.loop_saturated(location),
348 rate_radps: raw_rates_radps[axis],
349 last_moment: self.last_moments[axis],
350 alpha_rad: 0.0,
351 };
352 self.inject(dt, axis, &signals, setpoints)
353 }
354
355 /// Steps the running probe with `signals` for `axis` of `setpoints`: its setpoint
356 /// replaces `setpoints[axis]`.
357 fn inject(&mut self, dt: f32, axis: usize, signals: &LoopSignals, setpoints: &mut Vec3) {
358 if let Some(setpoint) = self.step_stage(dt, signals) {
359 setpoints[axis] = setpoint;
360 }
361 }
362
363 /// Whether `location`'s loop, or the loop under it, clipped on the last tick: a rate
364 /// loop's moment; an angle or heading loop's rate setpoint or that axis's moment.
365 fn loop_saturated(&self, location: Location) -> bool {
366 let clipped = &self.clipped;
367 match location {
368 Location::Rate(axis) => clipped.moments[axis],
369 Location::Angle(axis) => clipped.rates[axis] || clipped.moments[axis],
370 Location::Heading => clipped.rates[2] || clipped.moments[2],
371 }
372 }
373}