use nalgebra::{Complex, SMatrix, SVector};
use crate::controllers::{InvalidConfig, check, check_positive};
use crate::math::{assert_dt, lagged};
#[cfg(test)]
mod tests;
pub const MAX_DELAY_TICKS: usize = 10;
const SATURATED_SHARE: f32 = 0.2;
const SATURATED_MOMENT: f32 = 0.999;
const NOISY_RESIDUAL_RADPS: f32 = 0.017;
const WINDOW_CAPACITY: usize = 2048;
const INTEGRATION_TC_S: f32 = 0.1;
const MIN_LAG_S: f32 = 0.001;
const MAX_LAG_S: f32 = 0.5;
const LAG_RATIO: f32 = 1.05;
fn half_period_s(index: usize) -> f32 {
const FIRST_SWEEP_HALVES: usize = 9;
match index {
0..FIRST_SWEEP_HALVES => 1.0 - 0.1 * index as f32,
_ => 0.6 - 0.1 * ((index - FIRST_SWEEP_HALVES) % 5) as f32,
}
}
const TIE_SHARE: f32 = 0.01;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IdentifyConfig {
pub amplitude: f32,
pub duration_s: f32,
pub washout_tc_s: f32,
pub noisy: Option<IdentifyExtension>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IdentifyExtension {
pub amplitude: f32,
pub duration_s: f32,
}
impl IdentifyConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
check(
"amplitude",
non_zero_finite(self.amplitude),
"non-zero and finite",
)?;
check_positive("duration_s", self.duration_s)?;
check_positive("washout_tc_s", self.washout_tc_s)?;
let Some(noisy) = self.noisy else {
return Ok(());
};
check(
"noisy.amplitude",
non_zero_finite(noisy.amplitude),
"non-zero and finite",
)?;
check(
"noisy.duration_s",
noisy.duration_s.is_finite() && noisy.duration_s >= self.duration_s,
"finite and at least duration_s",
)
}
}
fn non_zero_finite(value: f32) -> bool {
value != 0.0 && value.is_finite()
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RateModel {
pub rate_weights: [f32; 2],
pub moment_weights: [f32; 3],
pub delay_ticks: usize,
pub dt_s: f32,
}
impl RateModel {
pub fn lag_s(&self) -> Option<f32> {
let pole = -self.rate_weights[1];
if pole >= 1.0 || pole.is_nan() {
return None;
}
Some(if pole > 0.0 {
-self.dt_s / libm::logf(pole)
} else {
0.0
})
}
pub fn response(&self, w_radps: f32) -> Complex<f32> {
let z1 = unit_delay(w_radps, self.dt_s);
let [m0, m1, m2] = self.moment_weights;
let [r1, r2] = self.rate_weights;
let one = Complex::new(1.0, 0.0);
let numerator = (one * m0 + z1 * m1 + z1 * z1 * m2) * z1.powu(self.delay_ticks as u32);
numerator / (one - z1 * r1 - z1 * z1 * r2)
}
pub fn accel_radps2(&self) -> Option<f32> {
self.lag_s()?;
let pole = (-self.rate_weights[1]).max(0.0);
Some(self.moment_effect() / ((1.0 - pole) * self.dt_s))
}
pub(crate) fn moment_effect(&self) -> f32 {
self.moment_weights.iter().sum()
}
}
pub(crate) fn unit_delay(w_radps: f32, dt_s: f32) -> Complex<f32> {
let angle = -w_radps * dt_s;
Complex::new(libm::cosf(angle), libm::sinf(angle))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum IdentifyAbort {
Unexcited,
Saturated,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IdentifyStatus {
Running {
elapsed_s: f32,
},
Done(RateModel),
Aborted(IdentifyAbort),
}
#[derive(Clone, Debug, PartialEq)]
pub struct IdentifyProbe {
duration_s: f32,
noisy: Option<IdentifyExtension>,
status: IdentifyStatus,
sweep: SquareSweep,
window: Window,
}
impl IdentifyProbe {
pub fn new(config: IdentifyConfig) -> Self {
if let Err(error) = config.validate() {
panic!("invalid IdentifyConfig: {error}");
}
IdentifyProbe {
duration_s: config.duration_s,
noisy: config.noisy,
status: IdentifyStatus::Running { elapsed_s: 0.0 },
sweep: SquareSweep::new(config.amplitude, config.washout_tc_s),
window: Window::new(),
}
}
pub fn step(&mut self, dt: f32, rate_radps: f32, last_moment: f32) -> f32 {
assert_dt(dt);
let IdentifyStatus::Running { elapsed_s } = self.status else {
return 0.0;
};
let elapsed_s = elapsed_s + dt;
let offset = self.sweep.next(dt, elapsed_s);
self.window.record(dt, rate_radps, last_moment, offset);
self.status = IdentifyStatus::Running { elapsed_s };
if elapsed_s < self.duration_s {
return offset;
}
let fit = classify(&self.window);
if let (Some(noisy), Ok(Fit::Integrated)) = (self.noisy.take(), fit) {
self.duration_s = noisy.duration_s;
self.sweep.amplitude = noisy.amplitude;
if elapsed_s < self.duration_s {
return offset;
}
}
self.status = match fit_classified(&self.window, fit) {
Ok(model) => IdentifyStatus::Done(model),
Err(abort) => IdentifyStatus::Aborted(abort),
};
offset
}
pub fn status(&self) -> IdentifyStatus {
self.status
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct SquareSweep {
amplitude: f32,
washout_tc_s: f32,
next_edge_s: f32,
edge: usize,
high: bool,
washout: f32,
}
impl SquareSweep {
pub(super) fn new(amplitude: f32, washout_tc_s: f32) -> Self {
SquareSweep {
amplitude,
washout_tc_s,
next_edge_s: half_period_s(0),
edge: 0,
high: true,
washout: 0.0,
}
}
pub(super) fn next(&mut self, dt: f32, elapsed_s: f32) -> f32 {
while elapsed_s >= self.next_edge_s {
self.edge += 1;
self.next_edge_s += half_period_s(self.edge);
self.high = !self.high;
}
let square = if self.high { self.amplitude } else { 0.0 };
self.washout = lagged(self.washout, square, dt, self.washout_tc_s);
square - self.washout
}
}
#[derive(Clone, Debug, PartialEq)]
struct Window {
rates_radps: [f32; WINDOW_CAPACITY],
moments: [f32; WINDOW_CAPACITY],
offsets: [f32; WINDOW_CAPACITY],
held: [bool; WINDOW_CAPACITY],
len: usize,
duration_s: f32,
}
impl Window {
fn new() -> Self {
Window {
rates_radps: [0.0; WINDOW_CAPACITY],
moments: [0.0; WINDOW_CAPACITY],
offsets: [0.0; WINDOW_CAPACITY],
held: [false; WINDOW_CAPACITY],
len: 0,
duration_s: 0.0,
}
}
fn record(&mut self, dt: f32, rate_radps: f32, last_moment: f32, offset: f32) {
let index = self.len;
if index == WINDOW_CAPACITY {
return;
}
let held = |value: f32, values: &[f32; WINDOW_CAPACITY]| {
if value.is_finite() {
value
} else {
index.checked_sub(1).map_or(0.0, |last| values[last])
}
};
self.rates_radps[index] = held(rate_radps, &self.rates_radps);
self.moments[index] = held(last_moment, &self.moments);
self.offsets[index] = offset;
self.held[index] = !(rate_radps.is_finite() && last_moment.is_finite());
self.len += 1;
self.duration_s += dt;
}
}
#[cfg(test)]
fn fit_window(window: &Window) -> Result<RateModel, IdentifyAbort> {
fit_classified(window, classify(window))
}
fn fit_classified(
window: &Window,
fit: Result<Fit, IdentifyAbort>,
) -> Result<RateModel, IdentifyAbort> {
match fit? {
Fit::Recorded(model) => Ok(model),
Fit::Integrated => fit_integrated(window).ok_or(IdentifyAbort::Unexcited),
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Fit {
Recorded(RateModel),
Integrated,
}
fn classify(window: &Window) -> Result<Fit, IdentifyAbort> {
let recorded = fit_recorded(window).ok_or(IdentifyAbort::Unexcited)?;
if recorded.residual_radps <= NOISY_RESIDUAL_RADPS {
return Ok(Fit::Recorded(recorded.model));
}
let moments = &window.moments[..window.len];
let saturated = moments
.iter()
.filter(|moment| moment.abs() >= SATURATED_MOMENT)
.count();
if saturated as f32 > SATURATED_SHARE * window.len as f32 {
return Err(IdentifyAbort::Saturated);
}
Ok(Fit::Integrated)
}
fn fit_integrated(window: &Window) -> Option<RateModel> {
let len = window.len;
let dt_s = window.duration_s / len.max(1) as f32;
let first = MAX_DELAY_TICKS + 1;
if len <= first + 1 {
return None;
}
let integrator = Integrator::new(dt_s);
let mut best: [Option<LagFit>; DELAY_STEPS] = [None; DELAY_STEPS];
let mut accel = [0.0f32; WINDOW_CAPACITY];
let mut previous_pole = 0.0;
let mut poles = lag_poles(dt_s).peekable();
while let Some(pole) = poles.next() {
lag_through(&window.moments, pole, len, &mut accel);
let next_pole = poles.peek().copied().unwrap_or(pole);
for (step, best) in best.iter_mut().enumerate() {
let fit = fit_gain(window, &accel, Delay::at(step), first, integrator);
if fit.is_some_and(|fit| best.is_none_or(|kept| fit.residual < kept.residual)) {
*best = fit.map(|fit| LagFit {
pole,
bracket: [previous_pole, next_pole],
..fit
});
}
}
previous_pole = pole;
}
let effects = best.map(|fit| fit.map(|fit| (fit.gain, fit.residual)));
let step = delay_to_fit(&effects, 0.0)? - 1;
let delay = Delay::at(step);
let grid_fit = best[step]?;
let LagFit { pole, gain, .. } = refine(window, delay, grid_fit, first, integrator, &mut accel);
let [now, next] = delay.split().map(|share| share * gain * (1.0 - pole));
Some(RateModel {
rate_weights: [1.0 + pole, -pole],
moment_weights: [now, next, 0.0],
delay_ticks: delay.ticks,
dt_s,
})
}
fn lag_through(
moments: &[f32; WINDOW_CAPACITY],
pole: f32,
len: usize,
accel: &mut [f32; WINDOW_CAPACITY],
) {
let mut lagged = 0.0;
for (accel, moment) in accel.iter_mut().zip(moments).take(len) {
lagged = pole * lagged + (1.0 - pole) * moment;
*accel = lagged;
}
}
const REFINE_STEPS: usize = 12;
fn refine(
window: &Window,
delay: Delay,
grid_fit: LagFit,
first: usize,
integrator: Integrator,
accel: &mut [f32; WINDOW_CAPACITY],
) -> LagFit {
const GOLDEN: f32 = 0.618_034;
let mut fit_at = |pole: f32| {
lag_through(&window.moments, pole, window.len, accel);
fit_gain(window, accel, delay, first, integrator).map(|fit| LagFit { pole, ..fit })
};
let [mut low, mut high] = grid_fit.bracket;
let mut best = grid_fit;
for _ in 0..REFINE_STEPS {
let left = high - GOLDEN * (high - low);
let right = low + GOLDEN * (high - low);
let (Some(left_fit), Some(right_fit)) = (fit_at(left), fit_at(right)) else {
break;
};
let kept = if left_fit.residual < right_fit.residual {
high = right;
left_fit
} else {
low = left;
right_fit
};
if kept.residual < best.residual {
best = kept;
}
}
best
}
fn lag_poles(dt_s: f32) -> impl Iterator<Item = f32> {
let lags_s = core::iter::successors(Some(MIN_LAG_S), |lag_s| Some(lag_s * LAG_RATIO))
.take_while(|lag_s| *lag_s <= MAX_LAG_S);
core::iter::once(0.0).chain(lags_s.map(move |lag_s| libm::expf(-dt_s / lag_s)))
}
fn fit_recorded(window: &Window) -> Option<RecordedFit> {
let dt_s = window.duration_s / window.len.max(1) as f32;
let mut fits = DelayFits::new();
for tick in 0..window.len {
let rate_radps = if window.held[tick] {
f32::NAN
} else {
window.rates_radps[tick]
};
fits.record(dt_s, rate_radps, window.moments[tick]);
}
fits.solve()
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct RecordedFit {
model: RateModel,
residual_radps: f32,
}
const HISTORY: usize = MAX_DELAY_TICKS + 2;
const TERMS: usize = 6;
#[derive(Clone, Debug, PartialEq)]
struct DelayFits {
rates_radps: [f32; 2],
moments: [f32; HISTORY],
filled: usize,
sums: [Sums; MAX_DELAY_TICKS],
rows: usize,
rows_dt_s: f32,
}
impl DelayFits {
fn new() -> Self {
DelayFits {
rates_radps: [0.0; 2],
moments: [0.0; HISTORY],
filled: 0,
sums: [Sums::default(); MAX_DELAY_TICKS],
rows: 0,
rows_dt_s: 0.0,
}
}
fn record(&mut self, dt: f32, rate_radps: f32, last_moment: f32) {
if !(rate_radps.is_finite() && last_moment.is_finite()) {
self.filled = 0;
return;
}
self.moments.rotate_right(1);
self.moments[0] = last_moment;
self.filled = (self.filled + 1).min(HISTORY);
if self.filled == HISTORY {
let [previous, before] = self.rates_radps;
let target = rate_radps - previous;
for (index, sums) in self.sums.iter_mut().enumerate() {
let regressors = SVector::<f32, TERMS>::from([
previous,
previous - before,
self.moments[index],
self.moments[index + 1],
self.moments[index + 2],
1.0,
]);
sums.add(®ressors, target);
}
self.rows += 1;
self.rows_dt_s += dt;
}
self.rates_radps = [rate_radps, self.rates_radps[0]];
}
fn solve(&self) -> Option<RecordedFit> {
let dt_s = self.rows_dt_s / self.rows.max(1) as f32;
let fits: [Option<(RateModel, f32)>; MAX_DELAY_TICKS] = core::array::from_fn(|index| {
let (solution, residual) = self.sums[index].solve()?;
Some((model_at(index + 1, &solution, dt_s), residual))
});
let effects =
fits.map(|fit| fit.map(|(model, residual)| (model.moment_effect(), residual)));
let delay_ticks = delay_to_fit(&effects, TIE_SHARE)?;
let (model, residual) = fits[delay_ticks - 1]?;
Some(RecordedFit {
model,
residual_radps: libm::sqrtf(residual / self.rows.max(1) as f32),
})
}
}
fn model_at(delay_ticks: usize, solution: &SVector<f32, TERMS>, dt_s: f32) -> RateModel {
let (change, difference) = (solution[0], solution[1]);
RateModel {
rate_weights: [1.0 + change + difference, -difference],
moment_weights: [solution[2], solution[3], solution[4]],
delay_ticks,
dt_s,
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Sums {
normal: SMatrix<f32, TERMS, TERMS>,
projected: SVector<f32, TERMS>,
target_squared: f32,
}
impl Default for Sums {
fn default() -> Self {
Sums {
normal: SMatrix::zeros(),
projected: SVector::zeros(),
target_squared: 0.0,
}
}
}
impl Sums {
fn add(&mut self, regressors: &SVector<f32, TERMS>, target: f32) {
self.normal += regressors * regressors.transpose();
self.projected += regressors * target;
self.target_squared += target * target;
}
fn solve(&self) -> Option<(SVector<f32, TERMS>, f32)> {
let solution = self.normal.cholesky()?.solve(&self.projected);
let residual = (self.target_squared - solution.dot(&self.projected)).max(0.0);
let finite = solution.iter().all(|x| x.is_finite()) && residual.is_finite();
finite.then_some((solution, residual))
}
}
const DELAY_STEPS: usize = 2 * MAX_DELAY_TICKS;
#[derive(Clone, Copy, Debug, PartialEq)]
struct Delay {
ticks: usize,
half: bool,
}
impl Delay {
fn at(step: usize) -> Self {
Delay {
ticks: step / 2 + 1,
half: step % 2 == 1,
}
}
fn split(self) -> [f32; 2] {
if self.half { [0.5, 0.5] } else { [1.0, 0.0] }
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct LagFit {
pole: f32,
bracket: [f32; 2],
gain: f32,
residual: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Integrator {
carry: f64,
}
impl Integrator {
fn new(dt_s: f32) -> Self {
Integrator {
carry: f64::from(libm::expf(-dt_s / INTEGRATION_TC_S)),
}
}
}
fn fit_gain(
window: &Window,
accel: &[f32; WINDOW_CAPACITY],
delay: Delay,
first: usize,
integrator: Integrator,
) -> Option<LagFit> {
let [now, next] = delay.split().map(f64::from);
let carry = integrator.carry;
let (mut moment, mut constant, mut target) = (0.0f64, 0.0f64, 0.0f64);
let (mut smm, mut smc, mut scc, mut smt, mut sct, mut stt) = (0.0f64, 0.0, 0.0, 0.0, 0.0, 0.0);
for tick in first..window.len {
let felt = tick + 1 - delay.ticks;
let x = now * f64::from(accel[felt]) + next * f64::from(accel[felt - 1]);
let change = f64::from(window.rates_radps[tick] - window.rates_radps[tick - 1]);
moment = carry * moment + x;
constant = carry * constant + 1.0;
target = carry * target + change;
smm += moment * moment;
smc += moment * constant;
scc += constant * constant;
smt += moment * target;
sct += constant * target;
stt += target * target;
}
let det = smm * scc - smc * smc;
let varies = det > f64::EPSILON * smm * scc;
if !varies {
return None;
}
let gain = (smt * scc - smc * sct) / det;
let trim = (smm * sct - smc * smt) / det;
let residual = (stt - gain * smt - trim * sct).max(0.0);
Some(LagFit {
pole: 0.0,
bracket: [0.0; 2],
gain: gain as f32,
residual: residual as f32,
})
}
fn delay_to_fit(fits: &[Option<(f32, f32)>], tie_share: f32) -> Option<usize> {
let fit_at = |index: usize| fits.get(index).copied().flatten();
let pushing: [Option<f32>; DELAY_STEPS] = core::array::from_fn(|index| {
fit_at(index)
.filter(|(effect, _)| *effect > 0.0)
.map(|(_, residual)| residual)
});
let all: [Option<f32>; DELAY_STEPS] =
core::array::from_fn(|index| fit_at(index).map(|(_, residual)| residual));
shortest_tied(&pushing, tie_share).or_else(|| shortest_tied(&all, tie_share))
}
fn shortest_tied(residuals: &[Option<f32>], tie_share: f32) -> Option<usize> {
let least = residuals.iter().flatten().copied().reduce(f32::min)?;
let tied = least + tie_share * least;
residuals
.iter()
.position(|residual| residual.is_some_and(|r| r <= tied))
.map(|index| index + 1)
}