use crate::Vec3;
use super::derivative::DerivativeState;
use super::{Gains, InvalidConfig, check_limit, rescale_integral};
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 = 1.0;
const DEFAULT_YAW_MAX_INTEGRAL: f32 = 5.0;
#[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_limit("max_integral", self.max_integral)?;
check_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]
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BodyRateController {
axes: [RateAxis; 3],
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct RateAxis {
integrated_error: 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;
let integrated_error =
clamp_symmetric(self.integrated_error + dt * error_radps, max_integral);
let moment = pd + gains.i * integrated_error;
let clipped = moment.abs() > 1.0;
if !clipped || integrated_error.abs() < self.integrated_error.abs() {
self.integrated_error = integrated_error;
}
clamp_symmetric(pd + gains.i * self.integrated_error, 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 rescale_integral(
&mut self,
old: &BodyRateControllerConfig,
new: &BodyRateControllerConfig,
) {
let gains = old.axis_gains().into_iter().zip(new.axis_gains());
for (axis, (old, new)) in self.axes.iter_mut().zip(gains) {
axis.integrated_error = rescale_integral(axis.integrated_error, old.i, new.i);
}
}
pub(crate) fn clear_integral(&mut self) {
for axis in &mut self.axes {
axis.integrated_error = 0.0;
}
}
#[cfg(test)]
pub(crate) fn integral_term(&self, config: &BodyRateControllerConfig, axis: usize) -> f32 {
config.axis_gains()[axis].i * self.axes[axis].integrated_error
}
pub(crate) fn hand_back(&mut self, axis: usize) {
self.axes[axis].derivative = DerivativeState::default();
}
#[cfg(test)]
fn integrated_error(&self) -> Vec3 {
Vec3::from_fn(|axis, _| self.axes[axis].integrated_error)
}
}
#[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].integrated_error == before[0].integrated_error);
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: 1.0,
..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: 1.0,
yaw_max_integral: 1.5,
..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.integrated_error() - Vec3::new(0.2, -0.2, 0.2)).amax() < 1e-6);
for _ in 0..20 {
c.control(&cfg, 0.1, error, Vec3::zeros());
}
assert!((c.integrated_error() - Vec3::new(1.0, -1.0, 1.5)).amax() < 1e-6);
}
#[test]
fn clipped_moment_stops_the_integral_growing() {
let start = 0.5;
let rows = [
("unclipped grows", 0.1, 1.0, start + 0.1),
("clipped toward the error holds", 2.0, 1.0, start),
(
"clipped against the integral shrinks",
2.0,
-1.0,
start - 0.1,
),
(
"clipped, error crossing zero shrinks",
2.0,
-0.6,
start - 0.06,
),
];
for (case, p, error, expected) in rows {
let cfg = config(p, 0.1, 0.0);
let mut c = BodyRateController::default();
c.axes[0].integrated_error = start;
let out = c.control(&cfg, 0.1, Vec3::new(error, 0.0, 0.0), Vec3::zeros());
let integral = c.integrated_error().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 gain_change_between_ticks_keeps_state() {
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 integral = c.integrated_error();
let out = c.control(&config(0.0, 0.5, 0.0), 0.1, Vec3::zeros(), Vec3::zeros());
assert!(c.integrated_error() == integral);
assert_abs_diff_eq!(out.x, 0.5 * integral.x, epsilon = 1e-6);
}
#[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(0.8, 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.integrated_error().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 [-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.integrated_error() == 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.integrated_error();
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] + DT * after_gap[axis];
let expected = 0.15 * after_gap[axis] + 0.1 * 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:?}");
}
}
}
}
}