use assert2::{assert, check};
use super::*;
use crate::tuning::plant::{Plant, PlantParams, gyro_noise};
use crate::tuning::{LoopSignals, Measurement, Probe, ProbeConfig, ProbeStatus};
const DT: f32 = 0.004;
const CONFIG: IdentifyConfig = IdentifyConfig {
amplitude: 0.07,
duration_s: 3.0,
washout_tc_s: 0.2,
noisy: None,
};
const EXTENDED: IdentifyConfig = IdentifyConfig {
noisy: Some(IdentifyExtension {
amplitude: 0.14,
duration_s: 8.0,
}),
..CONFIG
};
const ANGLE_P: f32 = 4.0;
const RATE_P: f32 = 0.3;
fn identify_with(
params: PlantParams,
mut probe: IdentifyProbe,
corrupt: impl Fn(usize, f32) -> f32,
) -> IdentifyProbe {
let mut plant = Plant::new(params, DT);
let (mut angle_rad, mut last_moment) = (0.0f32, 0.0f32);
let mut tick = 0;
while matches!(probe.status(), IdentifyStatus::Running { .. }) {
let rate_radps = plant.measure();
let offset_rad = probe.step(DT, corrupt(tick, rate_radps), last_moment);
let rate_setpoint_radps = ANGLE_P * (offset_rad - angle_rad);
last_moment = (RATE_P * (rate_setpoint_radps - rate_radps)).clamp(-1.0, 1.0);
plant.step(last_moment);
angle_rad += plant.output() * DT;
tick += 1;
}
probe
}
fn identify(params: PlantParams, probe: IdentifyProbe) -> IdentifyStatus {
identify_with(params, probe, |_, rate_radps| rate_radps).status()
}
fn model(status: IdentifyStatus) -> RateModel {
match status {
IdentifyStatus::Done(model) => model,
other => panic!("expected Done, got {other:?}"),
}
}
fn single_lag(gain: f32, lag_s: f32, delay_s: f32) -> PlantParams {
PlantParams {
gain,
lag1_s: lag_s,
lag2_s: 0.001,
delay_s,
..PlantParams::rate_axis()
}
}
#[test]
fn recovers_lag_delay_and_gain() {
let rows = [
((20.0, 0.02, 0.0), 1.5),
((40.0, 0.03, 0.0), 1.5),
((10.0, 0.05, 0.0), 1.5),
((5.0, 0.2, 0.0), 1.5),
((20.0, 0.03, 0.008), 3.5),
((20.0, 0.03, 0.02), 6.5),
];
for ((gain, lag_s, delay_s), delay_ticks) in rows {
let row = format!("gain {gain}, lag {lag_s} s, delay {delay_s} s");
let fitted = model(identify(
single_lag(gain, lag_s, delay_s),
IdentifyProbe::new(CONFIG),
));
let [now, next, _] = fitted.moment_weights.map(f32::abs);
let fitted_ticks = fitted.delay_ticks as f32 + next / (now + next);
check!(
(fitted_ticks - delay_ticks).abs() <= 1.0,
"{row}: {fitted:?}"
);
let fitted_s = fitted.lag_s().unwrap_or(f32::NAN) + fitted_ticks * DT;
let plant_s = lag_s + 0.001 + delay_ticks * DT;
check!(
(fitted_s - plant_s).abs() <= 0.1 * plant_s,
"{row}: lag and delay {fitted_s} s against {plant_s} s"
);
let accel = fitted.accel_radps2().unwrap_or(f32::NAN);
check!((accel - gain).abs() <= 0.1 * gain, "{row}: accel {accel}");
check!((fitted.dt_s - DT).abs() < 1e-6);
}
}
fn fitted_ticks(fitted: &RateModel) -> f32 {
let [now, next, _] = fitted.moment_weights.map(f32::abs);
fitted.delay_ticks as f32 + next / (now + next)
}
#[test]
fn the_integrated_fit_reads_the_delay_through_gyro_noise() {
let rows = [
((0.03, 0.0), 1.5),
((0.03, 0.008), 3.5),
((0.05, 0.008), 3.5),
((0.03, 0.02), 6.5),
];
for ((lag_s, delay_s), delay_ticks) in rows {
let row = format!("lag {lag_s} s, delay {delay_s} s");
let params = single_lag(20.0, lag_s, delay_s);
let probe = identify_with(params, IdentifyProbe::new(EXTENDED), |tick, rate| {
rate + gyro_noise(tick, 0.035)
});
check!(probe.window.len > 1900, "{row}: not extended");
let fitted = model(probe.status());
let ticks = fitted_ticks(&fitted);
check!((ticks - delay_ticks).abs() <= 1.0, "{row}: {fitted:?}");
let fitted_s = fitted.lag_s().unwrap_or(f32::NAN) + ticks * DT;
let plant_s = lag_s + 0.001 + delay_ticks * DT;
check!(
(fitted_s - plant_s).abs() <= 0.2 * plant_s,
"{row}: lag and delay {fitted_s} s against {plant_s} s: {fitted:?}"
);
let recorded = fit_recorded(&probe.window).expect("recorded fit").model;
check!(recorded.lag_s() < Some(0.01), "{row}: {recorded:?}");
}
}
#[test]
fn a_noisy_window_is_extended() {
let params = single_lag(20.0, 0.03, 0.0);
let rows = [
("noisy", EXTENDED, 0.06, 2000, 0.14),
("quiet", EXTENDED, 0.0, 750, 0.0),
("noisy, no extension", CONFIG, 0.06, 750, 0.0),
];
for (case, config, noise, ticks, peak) in rows {
let probe = identify_with(params, IdentifyProbe::new(config), |tick, rate| {
rate + gyro_noise(tick, noise)
});
let window = &probe.window;
let after = window.offsets[..window.len].iter().skip(775);
let largest = after.map(|offset| offset.abs()).fold(0.0f32, f32::max);
check!(
probe.window.len.abs_diff(ticks) <= 1,
"{case}: {} ticks",
probe.window.len
);
check!(
(largest - peak).abs() <= 0.01,
"{case}: largest offset {largest}"
);
}
}
#[derive(Clone, Copy, Debug)]
enum Taken {
LeastSquares,
Integrated,
Saturated,
}
#[test]
fn a_window_takes_the_fit_its_noise_and_saturation_call_for() {
let params = single_lag(20.0, 0.03, 0.0);
let rows = [
("quiet", RATE_P, 0.0, Taken::LeastSquares),
("quiet and stiff", 4.0 * RATE_P, 0.0, Taken::LeastSquares),
("quiet and saturated", 40.0, 0.0, Taken::LeastSquares),
("noisy", RATE_P, 0.06, Taken::Integrated),
("noisy and saturated", 40.0, 0.06, Taken::Saturated),
];
for (case, rate_p, noise, taken) in rows {
let mut plant = Plant::new(params, DT);
let (mut angle_rad, mut last_moment) = (0.0f32, 0.0f32);
let mut probe = IdentifyProbe::new(CONFIG);
let mut tick = 0;
while matches!(probe.status(), IdentifyStatus::Running { .. }) {
let rate_radps = plant.measure() + gyro_noise(tick, noise);
tick += 1;
let offset_rad = probe.step(DT, rate_radps, last_moment);
let rate_setpoint_radps = ANGLE_P * (offset_rad - angle_rad);
last_moment = (rate_p * (rate_setpoint_radps - rate_radps)).clamp(-1.0, 1.0);
plant.step(last_moment);
angle_rad += plant.output() * DT;
}
let window = &probe.window;
let expected = match taken {
Taken::LeastSquares => fit_recorded(window)
.map(|fit| fit.model)
.ok_or(IdentifyAbort::Unexcited),
Taken::Integrated => fit_integrated(window).ok_or(IdentifyAbort::Unexcited),
Taken::Saturated => Err(IdentifyAbort::Saturated),
};
check!(fit_window(window) == expected, "{case}");
}
}
#[test]
fn a_long_window_fits_its_first_ticks() {
let config = IdentifyConfig {
duration_s: 10.0,
..CONFIG
};
let probe = identify_with(
single_lag(20.0, 0.03, 0.0),
IdentifyProbe::new(config),
|_, rate| rate,
);
check!(probe.window.len == WINDOW_CAPACITY);
check!(
matches!(probe.status(), IdentifyStatus::Done(_)),
"{:?}",
probe.status()
);
}
#[test]
fn excites_with_a_washed_out_shrinking_square_wave() {
let config = IdentifyConfig {
duration_s: 10.0,
..CONFIG
};
let mut probe = IdentifyProbe::new(config);
let offsets: Vec<f32> = (0..2500).map(|_| probe.step(DT, 0.0, 0.0)).collect();
let edges_s: Vec<f32> = offsets
.windows(2)
.enumerate()
.filter(|(_, pair)| (pair[1] - pair[0]).abs() > 0.5 * config.amplitude)
.map(|(tick, _)| (tick + 1) as f32 * DT)
.collect();
for (edge_s, expected_s) in edges_s.iter().zip([1.0, 1.9, 2.7, 3.4, 4.0]) {
check!((edge_s - expected_s).abs() <= 1.5 * DT, "{edges_s:?}");
}
let one_tc = offsets[(config.washout_tc_s / DT) as usize - 1];
let expected = config.amplitude * (-1.0f32).exp();
check!(
(one_tc - expected).abs() <= 0.05 * config.amplitude,
"{one_tc}"
);
}
#[test]
fn holds_a_non_finite_tick_at_the_last_value() {
let params = single_lag(20.0, 0.02, 0.0);
let clean = model(identify(params, IdentifyProbe::new(CONFIG)));
let dropped = model(
identify_with(params, IdentifyProbe::new(CONFIG), |tick, rate| {
if tick == 300 { f32::NAN } else { rate }
})
.status(),
);
check!(dropped.delay_ticks == clean.delay_ticks, "{dropped:?}");
let [dropped_s, clean_s] = [dropped, clean].map(|model| model.lag_s().unwrap_or(f32::NAN));
check!(
(dropped_s - clean_s).abs() <= 0.01 * clean_s,
"{dropped:?} against {clean:?}"
);
}
#[test]
fn picks_the_shortest_of_near_tied_delays() {
type Row<'a> = (&'a [Option<f32>], f32, Option<usize>);
let rows: [Row; 8] = [
(&[Some(3.0), Some(1.0), Some(2.0)], TIE_SHARE, Some(2)),
(&[Some(1.005), Some(1.0)], TIE_SHARE, Some(1)),
(&[Some(1.02), Some(1.0)], TIE_SHARE, Some(2)),
(&[Some(1.0005), Some(1.0)], 0.0, Some(2)),
(&[Some(1.0), Some(1.0)], 0.0, Some(1)),
(&[None, Some(0.0), Some(0.0)], TIE_SHARE, Some(2)),
(&[None, None], TIE_SHARE, None),
(&[], TIE_SHARE, None),
];
for (residuals, tie_share, delay) in rows {
check!(
shortest_tied(residuals, tie_share) == delay,
"{residuals:?} at {tie_share}"
);
}
}
type DelayFit = Option<(f32, f32)>;
#[test]
fn fits_a_delay_whose_moment_pushes_the_right_way() {
let rows: [(&str, &[DelayFit], Option<usize>); 4] = [
(
"all push: least residual",
&[Some((1.0, 2.0)), Some((1.0, 1.0))],
Some(2),
),
(
"the least pushes back: the next",
&[Some((1.0, 1.5)), Some((-1.0, 1.0))],
Some(1),
),
(
"none pushes: least of all",
&[Some((-1.0, 2.0)), Some((-1.0, 1.0))],
Some(2),
),
("none solved", &[None, None], None),
];
for (row, fits, delay) in rows {
check!(delay_to_fit(fits, TIE_SHARE) == delay, "{row}");
}
}
#[test]
fn a_recorded_fit_reads_a_positive_acceleration() {
let mut probe = IdentifyProbe::new(CONFIG);
for line in include_str!("realflight_roll_fit.csv").lines() {
if line.starts_with('#') {
continue;
}
let (rate, moment) = line.split_once(',').expect("rate,moment");
let rate_radps = rate.parse().expect("rate");
let last_moment = moment.parse().expect("moment");
probe.step(DT, rate_radps, last_moment);
}
let model = model(probe.status());
check!(model.moment_effect() > 0.0, "{model:?}");
let accel_radps2 = model.accel_radps2().unwrap_or(f32::NAN);
check!(accel_radps2 > 0.0, "{model:?}: {accel_radps2} rad/s²");
}
fn realflight_windows<const N: usize>(fixture: &str) -> [Vec<(f32, f32)>; N] {
let mut windows: [Vec<(f32, f32)>; N] = core::array::from_fn(|_| Vec::new());
for line in fixture.lines().filter(|line| !line.starts_with('#')) {
let fields: Vec<&str> = line.split(',').collect();
let window: usize = fields[0].parse().expect("window");
let rate_radps = fields[1].parse().expect("rate");
let last_moment = fields[2].parse().expect("moment");
windows[window].push((rate_radps, last_moment));
}
windows
}
fn fit_recorded_window(window: &[(f32, f32)]) -> (RateModel, f32) {
let mut probe = IdentifyProbe::new(crate::tuning::autotune::COPTER_IDENTIFY);
for &(rate_radps, last_moment) in window {
probe.step(DT, rate_radps, last_moment);
}
let residual_radps = fit_recorded(&probe.window)
.expect("recorded fit")
.residual_radps;
(model(probe.status()), residual_radps)
}
fn designed_p(fitted: &RateModel, start: crate::controllers::Gains) -> Option<f32> {
use crate::tuning::autotune::COPTER_LOOP_SHAPING;
crate::tuning::design_rate(
fitted,
start,
crate::controllers::GyroFilters::low_pass(40.0),
&COPTER_LOOP_SHAPING,
)
.ok()
.map(|gains| gains.p)
}
#[test]
fn realflight_quadcopterx_windows_design_rate_p_in_range() {
let start = crate::controllers::Gains {
p: 0.5,
i: 0.1,
d: 0.004,
};
let windows = realflight_windows::<4>(include_str!("realflight_quadcopterx_windows.csv"));
for (index, window) in windows.iter().enumerate() {
let (fitted, residual) = fit_recorded_window(window);
check!(
residual < NOISY_RESIDUAL_RADPS,
"window {index}: residual {residual}"
);
let p = designed_p(&fitted, start);
check!(
p.is_some_and(|p| (0.5..=1.0).contains(&p)),
"window {index}: P {p:?} from {fitted:?}"
);
}
}
#[test]
fn realflight_explora_windows_design_realflights_rate_p() {
let start = crate::controllers::Gains {
p: 0.4,
i: 0.2,
d: 0.03,
};
let designs = [("roll", 0.94), ("pitch", 1.69)];
let windows = realflight_windows::<2>(include_str!("realflight_explora_windows.csv"));
for ((axis, realflight_p), window) in designs.into_iter().zip(&windows) {
let (fitted, residual) = fit_recorded_window(window);
check!(
residual < NOISY_RESIDUAL_RADPS,
"{axis}: residual {residual}"
);
let p = designed_p(&fitted, start);
check!(
p.is_some_and(|p| (p - realflight_p).abs() <= 0.05 * realflight_p),
"{axis}: P {p:?} against {realflight_p} from {fitted:?}"
);
}
}
#[test]
fn a_motionless_axis_is_unexcited() {
let mut probe = IdentifyProbe::new(CONFIG);
while matches!(probe.status(), IdentifyStatus::Running { .. }) {
probe.step(DT, 0.0, 0.0);
}
check!(probe.status() == IdentifyStatus::Aborted(IdentifyAbort::Unexcited));
}
#[test]
fn a_finished_probe_offsets_nothing() {
let mut probe = IdentifyProbe::new(CONFIG);
while matches!(probe.status(), IdentifyStatus::Running { .. }) {
probe.step(DT, 0.0, 0.0);
}
let status = probe.status();
check!(probe.step(DT, 1.0, 1.0) == 0.0);
check!(probe.status() == status);
}
#[test]
fn probe_injects_the_offset_on_the_setpoint() {
let mut probe = Probe::new(ProbeConfig::Identify(CONFIG));
let signals = LoopSignals {
setpoint: 0.1,
..LoopSignals::default()
};
let setpoint = probe.step(DT, &signals);
check!(setpoint > 0.1 && setpoint <= 0.1 + CONFIG.amplitude);
let fitted = identify(single_lag(20.0, 0.02, 0.0), IdentifyProbe::new(CONFIG));
let status = ProbeStatus::from(fitted);
assert!(matches!(
status,
ProbeStatus::Done(Measurement::Identify(_))
));
}
#[test]
fn validate_checks_each_field() {
let rows = [
(CONFIG, true),
(
IdentifyConfig {
amplitude: 0.0,
..CONFIG
},
false,
),
(
IdentifyConfig {
amplitude: -0.07,
..CONFIG
},
true,
),
(
IdentifyConfig {
amplitude: f32::NAN,
..CONFIG
},
false,
),
(
IdentifyConfig {
duration_s: 0.0,
..CONFIG
},
false,
),
(
IdentifyConfig {
duration_s: f32::INFINITY,
..CONFIG
},
false,
),
(
IdentifyConfig {
washout_tc_s: 0.0,
..CONFIG
},
false,
),
(EXTENDED, true),
(extended(-0.14, 8.0), true),
(extended(0.0, 8.0), false),
(extended(f32::NAN, 8.0), false),
(extended(0.14, 3.0), true),
(extended(0.14, 2.9), false),
(extended(0.14, f32::INFINITY), false),
];
for (config, valid) in rows {
check!(config.validate().is_ok() == valid, "{config:?}");
}
}
fn extended(amplitude: f32, duration_s: f32) -> IdentifyConfig {
IdentifyConfig {
noisy: Some(IdentifyExtension {
amplitude,
duration_s,
}),
..CONFIG
}
}
#[test]
fn lag_needs_a_pole_below_one() {
let rows = [
(0.9, Some(-DT / 0.9f32.ln())),
(0.0, Some(0.0)),
(-0.2, Some(0.0)),
(1.0, None),
(1.2, None),
];
for (pole, lag_s) in rows {
let model = RateModel {
rate_weights: [1.0 + pole, -pole],
moment_weights: [0.1, 0.0, 0.0],
delay_ticks: 1,
dt_s: DT,
};
check!(model.lag_s() == lag_s, "pole {pole}");
let accel = lag_s.map(|_| 0.1 / ((1.0 - pole.max(0.0)) * DT));
check!(model.accel_radps2() == accel, "pole {pole}");
}
}