use crate::Vec3;
use super::derivative::DerivativeState;
use super::{Gains, InvalidConfig, check};
use crate::math::{assert_dt, clamp_symmetric};
const DEFAULT_P: f32 = 0.15;
const DEFAULT_D: f32 = 0.003;
pub const RATE_I_PER_P: f32 = 0.2;
pub const YAW_RATE_I_PER_P: f32 = 0.3;
const DEFAULT_YAW_P: f32 = 0.3;
const DEFAULT_YAW_I: f32 = 0.1;
const DEFAULT_MAX_INTEGRAL: f32 = 0.5;
const DEFAULT_YAW_MAX_INTEGRAL: f32 = 0.5;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BodyRateControllerConfig {
pub roll_gains: Gains,
pub pitch_gains: Gains,
pub yaw_gains: Gains,
pub max_integral: f32,
pub yaw_max_integral: f32,
}
impl Default for BodyRateControllerConfig {
fn default() -> Self {
let roll_pitch_gains = Gains {
p: DEFAULT_P,
i: RATE_I_PER_P * DEFAULT_P,
d: DEFAULT_D,
};
Self {
roll_gains: roll_pitch_gains,
pitch_gains: roll_pitch_gains,
yaw_gains: Gains {
p: DEFAULT_YAW_P,
i: DEFAULT_YAW_I,
d: 0.0,
},
max_integral: DEFAULT_MAX_INTEGRAL,
yaw_max_integral: DEFAULT_YAW_MAX_INTEGRAL,
}
}
}
impl BodyRateControllerConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
check_moment_limit("max_integral", self.max_integral)?;
check_moment_limit("yaw_max_integral", self.yaw_max_integral)
}
fn axis_gains(&self) -> [Gains; 3] {
[self.roll_gains, self.pitch_gains, self.yaw_gains]
}
fn axis_max_integrals(&self) -> [f32; 3] {
[self.max_integral, self.max_integral, self.yaw_max_integral]
}
}
fn check_moment_limit(field: &'static str, limit: f32) -> Result<(), InvalidConfig> {
check(field, (0.0..=1.0).contains(&limit), "in [0, 1]")
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BodyRateController {
axes: [RateAxis; 3],
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct RateAxis {
integral: f32,
derivative: DerivativeState<f32>,
}
impl RateAxis {
fn step(
&mut self,
gains: Gains,
max_integral: f32,
dt: f32,
desired_radps: f32,
measured_radps: f32,
) -> f32 {
let error_radps = desired_radps - measured_radps;
if !error_radps.is_finite() {
self.derivative.forget();
return 0.0;
}
let accel_radps2 = self.derivative.step(measured_radps, dt);
let pd = gains.p * error_radps - gains.d * accel_radps2;
if gains.i == 0.0 {
self.integral = 0.0;
}
let integral = clamp_symmetric(self.integral + gains.i * error_radps * dt, max_integral);
let clipped = (pd + integral).abs() > 1.0;
if !clipped || integral.abs() < self.integral.abs() {
self.integral = integral;
}
clamp_symmetric(pd + self.integral, 1.0)
}
}
impl BodyRateController {
pub fn control(
&mut self,
config: &BodyRateControllerConfig,
dt: f32,
desired_rates_radps: Vec3,
estimated_rates_radps: Vec3,
) -> Vec3 {
assert_dt(dt);
let gains = config.axis_gains();
let max_integrals = config.axis_max_integrals();
Vec3::from_fn(|axis, _| {
self.axes[axis].step(
gains[axis],
max_integrals[axis],
dt,
desired_rates_radps[axis],
estimated_rates_radps[axis],
)
})
}
pub(crate) fn clear_integral(&mut self) {
for axis in &mut self.axes {
axis.integral = 0.0;
}
}
#[cfg(test)]
pub(crate) fn integral_term(&self, axis: usize) -> f32 {
self.axes[axis].integral
}
pub(crate) fn hand_back(&mut self, axis: usize) {
self.axes[axis].derivative = DerivativeState::default();
}
#[cfg(test)]
fn integral(&self) -> Vec3 {
Vec3::from_fn(|axis, _| self.axes[axis].integral)
}
}
#[cfg(test)]
mod tests {
use super::*;
use approx::assert_abs_diff_eq;
use assert2::assert;
const DT: f32 = 0.004;
fn config(p: f32, i: f32, d: f32) -> BodyRateControllerConfig {
BodyRateControllerConfig {
roll_gains: Gains { p, i, d },
pitch_gains: Gains { p, i, d },
yaw_gains: Gains { p, i, d },
max_integral: 1.0,
yaw_max_integral: 1.0,
}
}
#[test]
fn hand_back_restarts_one_axis_only() {
let config = config(1.0, 2.0, 0.5);
let mut controller = BodyRateController::default();
controller.control(&config, DT, Vec3::new(0.5, 0.5, 0.5), Vec3::zeros());
let before = controller.axes;
controller.hand_back(0);
assert!(controller.axes[0].integral == before[0].integral);
assert!(controller.axes[0].derivative == DerivativeState::default());
assert!(controller.axes[1..] == before[1..]);
}
#[test]
fn first_tick_output_is_saturated_p_plus_i() {
let cases = [
(0.15, 0.0, Vec3::zeros(), Vec3::zeros(), Vec3::zeros()),
(
0.15,
0.0,
Vec3::new(1.0, 0.0, 0.0),
Vec3::zeros(),
Vec3::new(0.15, 0.0, 0.0),
),
(
0.15,
0.0,
Vec3::new(0.0, 2.0, -2.0),
Vec3::zeros(),
Vec3::new(0.0, 0.3, -0.3),
),
(
0.15,
0.0,
Vec3::new(1.0, 1.0, 1.0),
Vec3::new(1.0, 2.0, 0.0),
Vec3::new(0.0, -0.15, 0.15),
),
(
0.15,
0.0,
Vec3::new(10.0, -10.0, 0.0),
Vec3::zeros(),
Vec3::new(1.0, -1.0, 0.0),
),
(
0.0,
10.0,
Vec3::new(5.0, 0.0, 0.0),
Vec3::zeros(),
Vec3::new(10.0 * 5.0 * DT, 0.0, 0.0),
),
];
for (p, i, desired, estimated, expected) in cases {
let mut c = BodyRateController::default();
let out = c.control(&config(p, i, 0.0), DT, desired, estimated);
assert!(
(out - expected).amax() < 1e-6,
"p={p} i={i} {desired:?}/{estimated:?}: {out:?}"
);
}
}
#[test]
fn integral_cancels_a_constant_yaw_torque_up_to_its_authority() {
let cfg = BodyRateControllerConfig {
yaw_gains: Gains {
p: 0.6,
i: 0.2,
d: 0.0,
},
yaw_max_integral: 0.2,
..config(0.0, 0.0, 0.0)
};
let cases = [
(0.0, 0.0),
(0.15, 0.0),
(-0.15, 0.0),
(0.4, -0.333_333), (-0.4, 0.333_333),
];
for (disturbance, expected) in cases {
let rate = crate::testing::settled_yaw_rate(&cfg, disturbance);
assert!(
(rate - expected).abs() < 1e-3,
"disturbance {disturbance}: settled at {rate} rad/s, expected {expected}"
);
}
}
#[test]
fn proportional_output_does_not_depend_on_dt() {
for dt in [0.0001, 0.004, 0.02, 0.1] {
let mut c = BodyRateController::default();
let out = c.control(
&config(0.15, 0.0, 0.0),
dt,
Vec3::new(1.0, 0.0, 0.0),
Vec3::zeros(),
);
assert_abs_diff_eq!(out.x, 0.15, epsilon = 1e-6);
}
}
#[test]
fn derivative_term_opposes_a_rising_rate() {
let cfg = config(0.0, 0.0, 0.003);
let mut c = BodyRateController::default();
c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
let steady = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
let rising = c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.5, 0.0, 0.0));
assert_abs_diff_eq!(steady.x, 0.0, epsilon = 1e-6);
assert_abs_diff_eq!(rising.x, 0.003 * -0.5 / DT, epsilon = 1e-5);
}
#[test]
fn a_setpoint_step_has_no_derivative_kick() {
let rows = [
(1.0, 0.003),
(-1.0, 0.003),
(0.2, 0.139),
(1.0, 0.139),
(-3.0, 0.05),
];
let p = 0.15;
for (step_radps, d) in rows {
let cfg = config(p, 0.0, d);
let mut c = BodyRateController::default();
let measured = Vec3::new(0.3, 0.3, 0.3);
c.control(&cfg, DT, measured, measured);
let stepped = measured + Vec3::repeat(step_radps);
let moments = c.control(&cfg, DT, stepped, measured);
let expected = clamp_symmetric(p * step_radps, 1.0);
assert!(
(moments - Vec3::repeat(expected)).amax() < 1e-6,
"step {step_radps} rad/s, d {d}: {moments:?}"
);
}
}
#[test]
fn first_tick_has_no_derivative_kick() {
let mut c = BodyRateController::default();
let moments = c.control(
&config(0.0, 0.0, 0.01),
DT,
Vec3::new(1.0, -2.0, 0.5),
Vec3::zeros(),
);
assert!(moments == Vec3::zeros());
}
#[test]
fn integral_accumulates_and_clamps_per_axis() {
let cfg = BodyRateControllerConfig {
max_integral: 0.1,
yaw_max_integral: 0.15,
..config(0.0, 0.1, 0.0)
};
let error = Vec3::new(2.0, -2.0, 2.0);
let mut c = BodyRateController::default();
c.control(&cfg, 0.1, error, Vec3::zeros());
assert!((c.integral() - Vec3::new(0.02, -0.02, 0.02)).amax() < 1e-6);
for _ in 0..20 {
c.control(&cfg, 0.1, error, Vec3::zeros());
}
assert!((c.integral() - Vec3::new(0.1, -0.1, 0.15)).amax() < 1e-6);
}
#[test]
fn a_limit_of_i_times_the_rad_limit_flies_as_the_rad_limit_did() {
fn rad_law(
integrated_error: &mut f32,
gains: Gains,
limit_rad: f32,
dt: f32,
e: f32,
) -> f32 {
let pd = gains.p * e;
let integral = clamp_symmetric(*integrated_error + dt * e, limit_rad);
let clipped = (pd + gains.i * integral).abs() > 1.0;
if !clipped || integral.abs() < integrated_error.abs() {
*integrated_error = integral;
}
clamp_symmetric(pd + gains.i * *integrated_error, 1.0)
}
let rows = [
(
"eXplora pitch",
Gains {
p: 1.4217,
i: 0.2844,
d: 0.0,
},
1.0,
),
(
"Cobra roll",
Gains {
p: 0.4847,
i: 0.0969,
d: 0.0,
},
3.0,
),
(
"Alia",
Gains {
p: 1.52,
i: 0.2,
d: 0.0,
},
1.0,
),
];
let errors = (0..2000).map(|tick| match tick {
0..1000 => 0.8,
1000..1100 => 3.0,
1100..1500 => -0.5,
_ => 0.05,
});
for (name, gains, limit_rad) in rows {
let cfg = BodyRateControllerConfig {
roll_gains: gains,
max_integral: gains.i * limit_rad,
..config(0.0, 0.0, 0.0)
};
let mut c = BodyRateController::default();
let mut integrated_error = 0.0;
for (tick, e) in errors.clone().enumerate() {
let new = c.control(&cfg, DT, Vec3::new(e, 0.0, 0.0), Vec3::zeros()).x;
let old = rad_law(&mut integrated_error, gains, limit_rad, DT, e);
assert!(
(new - old).abs() < 1e-5,
"{name} tick {tick}: {new} vs {old}"
);
}
}
}
#[test]
fn integral_limit_does_not_scale_with_the_i_gain() {
for i in [0.03, 0.3, 3.0] {
let cfg = config(0.0, i, 0.0);
let mut c = BodyRateController::default();
for _ in 0..10_000 {
c.control(&cfg, DT, Vec3::new(1.0, 0.0, 0.0), Vec3::zeros());
}
assert_abs_diff_eq!(c.integral().x, cfg.max_integral, epsilon = 1e-6);
}
}
#[test]
fn clipped_moment_stops_the_integral_growing() {
let start = 0.5;
let rows = [
("unclipped grows", 0.1, 1.0, start + 0.01),
("clipped toward the error holds", 2.0, 1.0, start),
(
"clipped against the integral shrinks",
2.0,
-1.0,
start - 0.01,
),
(
"clipped, error crossing zero shrinks",
2.0,
-0.6,
start - 0.006,
),
];
for (case, p, error, expected) in rows {
let cfg = config(p, 0.1, 0.0);
let mut c = BodyRateController::default();
c.axes[0].integral = start;
let out = c.control(&cfg, 0.1, Vec3::new(error, 0.0, 0.0), Vec3::zeros());
let integral = c.integral().x;
assert!((integral - expected).abs() < 1e-6, "{case}: {integral}");
assert!(out.x.abs() <= 1.0, "{case}");
}
}
#[test]
fn each_axis_uses_its_own_gains() {
let p_only = |p| Gains { p, i: 0.0, d: 0.0 };
let cfg = BodyRateControllerConfig {
roll_gains: p_only(0.15),
pitch_gains: p_only(0.25),
yaw_gains: p_only(0.5),
max_integral: 1.0,
yaw_max_integral: 1.0,
};
let out = BodyRateController::default().control(
&cfg,
DT,
Vec3::new(1.0, 1.0, 1.0),
Vec3::zeros(),
);
assert!((out - Vec3::new(0.15, 0.25, 0.5)).amax() < 1e-6);
}
#[test]
fn i_gain_change_keeps_the_i_term_or_drops_it_at_zero() {
let rows = [
("raised", 0.5, 0.02),
("lowered", 0.01, 0.02),
("zeroed", 0.0, 0.0),
];
for (case, new_i, expected) in rows {
let mut c = BodyRateController::default();
c.control(
&config(0.0, 0.1, 0.0),
0.1,
Vec3::new(2.0, 0.0, 0.0),
Vec3::zeros(),
);
let out = c.control(&config(0.0, new_i, 0.0), 0.1, Vec3::zeros(), Vec3::zeros());
assert!((c.integral().x - expected).abs() < 1e-6, "{case}");
assert!((out.x - expected).abs() < 1e-6, "{case}");
}
}
#[test]
fn shrinking_max_integral_clamps_the_integral() {
let mut c = BodyRateController::default();
c.control(
&config(0.0, 0.1, 0.0),
1.0,
Vec3::new(8.0, 0.0, 0.0),
Vec3::zeros(),
);
let shrunk = BodyRateControllerConfig {
max_integral: 0.25,
..config(0.0, 0.1, 0.0)
};
c.control(&shrunk, DT, Vec3::zeros(), Vec3::zeros());
assert_abs_diff_eq!(c.integral().x, 0.25, epsilon = 1e-6);
}
#[test]
fn invalid_max_integral_is_rejected_and_does_not_panic_the_tick() {
type SetLimit = fn(&mut BodyRateControllerConfig, f32);
let rows: [(&str, SetLimit, Vec3); 2] = [
("max_integral", |c, v| c.max_integral = v, Vec3::x()),
("yaw_max_integral", |c, v| c.yaw_max_integral = v, Vec3::z()),
];
for (field, set, error) in rows {
for limit in [5.0, 1.01] {
let mut cfg = config(0.0, 0.1, 0.0);
set(&mut cfg, limit);
assert_eq!(cfg.validate().map_err(|e| e.field), Err(field));
}
for limit in [-1.0, f32::NAN] {
let mut cfg = config(0.0, 0.1, 0.0);
set(&mut cfg, limit);
assert_eq!(cfg.validate().map_err(|e| e.field), Err(field));
let mut c = BodyRateController::default();
let out = c.control(&cfg, DT, error, Vec3::zeros());
assert!(c.integral() == Vec3::zeros(), "{field} {limit}");
assert!(out == Vec3::zeros(), "{field} {limit}");
}
}
}
#[test]
#[should_panic(expected = "dt must be positive and finite")]
fn zero_dt_panics() {
BodyRateController::default().control(
&config(0.15, 0.0, 0.0),
0.0,
Vec3::zeros(),
Vec3::zeros(),
);
}
#[test]
fn non_finite_rate_zeroes_only_its_axis() {
let nan = f32::NAN;
let inf = f32::INFINITY;
let cases = [
(Vec3::new(inf, 0.3, -0.2), Vec3::zeros()),
(Vec3::new(0.4, 0.3, -0.2), Vec3::new(0.0, nan, 0.0)),
(Vec3::new(0.4, 0.3, nan), Vec3::zeros()),
(Vec3::new(0.4, inf, 0.0), Vec3::new(0.0, inf, 0.0)), (Vec3::new(nan, nan, nan), Vec3::zeros()),
];
let cfg = config(0.15, 0.1, 0.003);
let warm_up = Vec3::new(0.5, -0.4, 0.3);
let after_gap = Vec3::new(0.2, 0.2, 0.2);
for (desired, estimated) in cases {
let bad = (desired - estimated).map(|e| !e.is_finite());
let finite = |v: Vec3| v.map(|c| if c.is_finite() { c } else { 0.0 });
let mut c = BodyRateController::default();
let mut twin = BodyRateController::default();
c.control(&cfg, DT, warm_up, Vec3::zeros());
twin.control(&cfg, DT, warm_up, Vec3::zeros());
let integral_before = c.integral();
let during = c.control(&cfg, DT, desired, estimated);
let twin_during = twin.control(&cfg, DT, finite(desired), finite(estimated));
let after = c.control(&cfg, DT, after_gap, Vec3::zeros());
let twin_after = twin.control(&cfg, DT, after_gap, Vec3::zeros());
for axis in 0..3 {
let row = format!("{desired:?}/{estimated:?} axis {axis}");
if bad[axis] {
assert!(during[axis] == 0.0, "{row}: {during:?}");
let integral = integral_before[axis] + 0.1 * after_gap[axis] * DT;
let expected = 0.15 * after_gap[axis] + integral;
assert!((after[axis] - expected).abs() < 1e-6, "{row}: {after:?}");
} else {
assert!(during[axis] == twin_during[axis], "{row}: {during:?}");
assert!(after[axis] == twin_after[axis], "{row}: {after:?}");
}
}
}
}
}