stable_flight/controllers/plane_rate.rs
1//! [`PlaneRateController`]: the fixed-wing body-rate loop, PI plus feedforward and trim per
2//! axis with airspeed scaling.
3
4use crate::Vec3;
5
6use super::{InvalidConfig, check, check_limit, rescale_integral};
7use crate::math::{assert_dt, clamp_symmetric};
8
9#[cfg(test)]
10mod tests;
11
12/// Gains for one axis of the [`PlaneRateController`], in normalized moment per rad/s of rate
13/// error (`p`), per rad of accumulated error (`i`), and per rad/s of rate setpoint (`ff`).
14#[derive(Clone, Copy, Debug, Default, PartialEq)]
15pub struct RateGains {
16 /// Proportional gain.
17 pub p: f32,
18 /// Integral gain.
19 pub i: f32,
20 /// Feedforward gain on the rate setpoint: the surface deflection a rate needs, which a
21 /// wing holds against its damping.
22 pub ff: f32,
23}
24
25/// Configures the [`PlaneRateController`].
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct PlaneRateControllerConfig {
28 /// Roll-rate gains.
29 pub roll: RateGains,
30 /// Pitch-rate gains.
31 pub pitch: RateGains,
32 /// Yaw-rate gains.
33 pub yaw: RateGains,
34 /// Largest accumulated rate error per axis, in rad.
35 pub max_integral: f32,
36 /// The moment each axis holds at trim airspeed and zero rate error, roll (`x`), pitch
37 /// (`y`), and yaw (`z`), normalized: what the wing needs in steady level flight (a nose-up
38 /// pitch moment for a wing that pitches down), so neither the attitude loop's error nor the
39 /// rate integral has to hold it.
40 pub trim: Vec3,
41}
42
43impl Default for PlaneRateControllerConfig {
44 /// PX4's fixed-wing rate defaults (`fw_rate_control_params.yaml`: roll P 0.05 I 0.1 FF 0.5,
45 /// pitch P 0.08 I 0.1 FF 0.5, yaw P 0.05 FF 0.3, no trim), a starting point for an airframe
46 /// to tune.
47 fn default() -> Self {
48 PlaneRateControllerConfig {
49 roll: RateGains {
50 p: 0.05,
51 i: 0.1,
52 ff: 0.5,
53 },
54 pitch: RateGains {
55 p: 0.08,
56 i: 0.1,
57 ff: 0.5,
58 },
59 yaw: RateGains {
60 p: 0.05,
61 i: 0.0,
62 ff: 0.3,
63 },
64 max_integral: 2.0,
65 trim: Vec3::zeros(),
66 }
67 }
68}
69
70impl PlaneRateControllerConfig {
71 /// `Ok` when every gain and `max_integral` is non-negative and finite, and each trim is in
72 /// `[-1, 1]`.
73 ///
74 /// # Errors
75 ///
76 /// [`InvalidConfig`] naming the first field out of range.
77 ///
78 /// # Examples
79 ///
80 /// ```
81 /// use stable_flight::controllers::PlaneRateControllerConfig;
82 ///
83 /// assert!(PlaneRateControllerConfig::default().validate().is_ok());
84 /// let mut bad = PlaneRateControllerConfig::default();
85 /// bad.pitch.ff = -0.1;
86 /// assert_eq!(bad.validate().unwrap_err().field, "pitch.ff");
87 /// ```
88 pub fn validate(&self) -> Result<(), InvalidConfig> {
89 let (r, p, y) = (self.roll, self.pitch, self.yaw);
90 let fields = [
91 ("roll.p", r.p),
92 ("roll.i", r.i),
93 ("roll.ff", r.ff),
94 ("pitch.p", p.p),
95 ("pitch.i", p.i),
96 ("pitch.ff", p.ff),
97 ("yaw.p", y.p),
98 ("yaw.i", y.i),
99 ("yaw.ff", y.ff),
100 ("max_integral", self.max_integral),
101 ];
102 for (field, value) in fields {
103 check_limit(field, value)?;
104 }
105 let trims = [
106 ("trim.x", self.trim.x),
107 ("trim.y", self.trim.y),
108 ("trim.z", self.trim.z),
109 ];
110 for (field, value) in trims {
111 check(field, (-1.0..=1.0).contains(&value), "in [-1, 1]")?;
112 }
113 Ok(())
114 }
115
116 fn axis_gains(&self) -> [RateGains; 3] {
117 [self.roll, self.pitch, self.yaw]
118 }
119}
120
121/// The fixed-wing body-rate loop: per axis, `s²·(P·e + I·∫e + trim) + s·FF·setpoint`, clamped
122/// to `[-1, 1]`, where `s` is the airspeed scale (trim airspeed over current airspeed).
123///
124/// A surface's moment grows with dynamic pressure (airspeed squared), so the feedback terms
125/// and the trim shrink by `s²` as the wing speeds up; the feedforward, a deflection that holds
126/// a rate against the wing's damping (itself proportional to airspeed), by `s` (PX4's
127/// `FixedwingRateControl::Run`, ArduPilot's `AP_FW_Controller::run_rate_control`). Holds only
128/// its integral; the config is passed to every call.
129///
130/// # Examples
131///
132/// ```
133/// use stable_flight::Vec3;
134/// use stable_flight::controllers::{PlaneRateController, PlaneRateControllerConfig};
135///
136/// let config = PlaneRateControllerConfig::default();
137/// let mut controller = PlaneRateController::default();
138/// let roll = Vec3::new(0.5, 0.0, 0.0);
139/// let at_trim = controller.control(&config, 0.004, roll, Vec3::zeros(), 1.0, true);
140/// let mut fast = PlaneRateController::default();
141/// let faster = fast.control(&config, 0.004, roll, Vec3::zeros(), 0.5, true);
142/// assert!(faster.x < at_trim.x); // less deflection at twice trim airspeed
143/// ```
144#[derive(Clone, Debug, Default, PartialEq)]
145pub struct PlaneRateController {
146 integrated_error: Vec3,
147}
148
149impl PlaneRateController {
150 /// Normalized moments `[-1, 1]` toward `desired_radps` from `current_radps`.
151 ///
152 /// `scale` is the airspeed scale `s` (1 at trim airspeed). `integrate` is false below the
153 /// wing's minimum airspeed, where the surfaces have little authority and the integral
154 /// would only wind up: it is held. A non-finite setpoint or rate on an axis gives that
155 /// axis only its trim and leaves its integral alone (input policy); a non-finite scale
156 /// gives no moment.
157 ///
158 /// # Panics
159 ///
160 /// If `dt` is not positive and finite.
161 pub fn control(
162 &mut self,
163 config: &PlaneRateControllerConfig,
164 dt: f32,
165 desired_radps: Vec3,
166 current_radps: Vec3,
167 scale: f32,
168 integrate: bool,
169 ) -> Vec3 {
170 assert_dt(dt);
171 if !scale.is_finite() {
172 return Vec3::zeros();
173 }
174 let gains = config.axis_gains();
175 let scale_squared = scale * scale;
176 Vec3::from_fn(|axis, _| {
177 let (desired, current) = (desired_radps[axis], current_radps[axis]);
178 let error = desired - current;
179 let trim = scale_squared * config.trim[axis];
180 if !error.is_finite() {
181 return clamp_symmetric(trim, 1.0);
182 }
183 if integrate {
184 self.integrated_error[axis] = clamp_symmetric(
185 self.integrated_error[axis] + error * dt,
186 config.max_integral,
187 );
188 }
189 let RateGains { p, i, ff } = gains[axis];
190 let feedback = p * error + i * self.integrated_error[axis];
191 clamp_symmetric(scale_squared * feedback + trim + scale * ff * desired, 1.0)
192 })
193 }
194
195 /// Zeroes the integral.
196 pub(crate) fn clear_integral(&mut self) {
197 self.integrated_error = Vec3::zeros();
198 }
199
200 /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
201 /// tick's I term picks up where the last left off (`rescale_integral`).
202 pub(crate) fn rescale_integral(
203 &mut self,
204 old: &PlaneRateControllerConfig,
205 new: &PlaneRateControllerConfig,
206 ) {
207 let (old, new) = (old.axis_gains(), new.axis_gains());
208 self.integrated_error = Vec3::from_fn(|axis, _| {
209 rescale_integral(self.integrated_error[axis], old[axis].i, new[axis].i)
210 });
211 }
212}