use nalgebra::{SMatrix, SVector};
use super::identify::SquareSweep;
use super::{IdentifyAbort, IdentifyConfig};
use crate::math::assert_dt;
pub mod design;
#[cfg(test)]
mod tests;
const DECIMATION: usize = 2;
const WINDOW_CAPACITY: usize = 750;
const LAGS_S: [f32; 12] = [
0.0, 0.02, 0.04, 0.06, 0.08, 0.1, 0.12, 0.14, 0.17, 0.2, 0.25, 0.3,
];
const MAX_DELAY_SAMPLES: usize = 5;
const TERMS: usize = 4;
const MIN_ALPHA_SPREAD_RAD: f32 = 1e-4;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WingModel {
pub stiffness_per_s2: f32,
pub damping_per_s: f32,
pub control_radps2: f32,
pub lag_s: f32,
pub delay_s: f32,
pub path_turn_per_s: f32,
pub trim_moment: f32,
}
impl WingModel {
pub fn feedforward(&self) -> f32 {
self.damping_per_s / self.control_radps2
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WingStatus {
Running {
elapsed_s: f32,
},
Done(WingModel),
Aborted(IdentifyAbort),
}
#[derive(Clone, Debug, PartialEq)]
pub struct WingIdentifyProbe {
duration_s: f32,
status: WingStatus,
sweep: SquareSweep,
window: Window,
}
impl WingIdentifyProbe {
pub fn new(config: IdentifyConfig) -> Self {
if let Err(error) = config.validate() {
panic!("invalid IdentifyConfig: {error}");
}
Self {
duration_s: config.duration_s,
status: WingStatus::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, alpha_rad: f32) -> f32 {
assert_dt(dt);
let WingStatus::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, alpha_rad);
self.status = if elapsed_s < self.duration_s {
WingStatus::Running { elapsed_s }
} else {
match fit(&self.window) {
Some(model) => WingStatus::Done(model),
None => WingStatus::Aborted(IdentifyAbort::Unexcited),
}
};
offset
}
pub fn status(&self) -> WingStatus {
self.status
}
}
#[derive(Clone, Debug, PartialEq)]
struct Window {
rates_radps: [f32; WINDOW_CAPACITY],
moments: [f32; WINDOW_CAPACITY],
alphas_rad: [f32; WINDOW_CAPACITY],
len: usize,
ticks: usize,
duration_s: f32,
last: [f32; 3],
moment_sum: f32,
}
impl Window {
fn new() -> Self {
Self {
rates_radps: [0.0; WINDOW_CAPACITY],
moments: [0.0; WINDOW_CAPACITY],
alphas_rad: [0.0; WINDOW_CAPACITY],
len: 0,
ticks: 0,
duration_s: 0.0,
last: [0.0; 3],
moment_sum: 0.0,
}
}
fn record(&mut self, dt: f32, rate_radps: f32, last_moment: f32, alpha_rad: f32) {
if self.len == WINDOW_CAPACITY {
return;
}
for (last, value) in self
.last
.iter_mut()
.zip([rate_radps, last_moment, alpha_rad])
{
if value.is_finite() {
*last = value;
}
}
self.duration_s += dt;
self.ticks += 1;
let [rate_radps, moment, alpha_rad] = self.last;
self.moment_sum += moment;
if !self.ticks.is_multiple_of(DECIMATION) {
return;
}
self.rates_radps[self.len] = rate_radps;
self.moments[self.len] = self.moment_sum / DECIMATION as f32;
self.alphas_rad[self.len] = alpha_rad;
self.moment_sum = 0.0;
self.len += 1;
}
fn sample_s(&self) -> f32 {
self.duration_s / self.ticks.max(1) as f32 * DECIMATION as f32
}
fn has_alpha(&self) -> bool {
let alphas = &self.alphas_rad[..self.len];
let (low, high) = alphas
.iter()
.fold((f32::INFINITY, f32::NEG_INFINITY), |(low, high), &alpha| {
(low.min(alpha), high.max(alpha))
});
high - low > MIN_ALPHA_SPREAD_RAD
}
}
struct Fit {
terms: SVector<f64, TERMS>,
residual: f64,
}
fn fit(window: &Window) -> Option<WingModel> {
let sample_s = window.sample_s();
let with_alpha = window.has_alpha();
let mut best: Option<(Fit, f32, usize)> = None;
let mut surface = [0.0f32; WINDOW_CAPACITY];
for lag_s in LAGS_S {
lag_through(window, lag_s, sample_s, &mut surface);
for delay in 0..=MAX_DELAY_SAMPLES {
let Some(fit) = fit_at(window, &surface, delay, sample_s, with_alpha) else {
continue;
};
if best
.as_ref()
.is_none_or(|(kept, ..)| fit.residual < kept.residual)
{
best = Some((fit, lag_s, delay));
}
}
}
let (fit, lag_s, delay) = best?;
let moments = &window.moments[..window.len];
let trim_moment = moments.iter().sum::<f32>() / moments.len() as f32;
let path_turn_per_s = if with_alpha {
fit_path_turn(window, sample_s)?
} else {
0.0
};
Some(WingModel {
stiffness_per_s2: -fit.terms[0] as f32,
damping_per_s: -fit.terms[1] as f32,
control_radps2: fit.terms[2] as f32,
lag_s,
delay_s: delay as f32 * sample_s,
path_turn_per_s,
trim_moment,
})
}
fn lag_through(window: &Window, lag_s: f32, sample_s: f32, surface: &mut [f32; WINDOW_CAPACITY]) {
let share = sample_s / (sample_s + lag_s);
let mut lagged = window.moments[0];
for (out, &moment) in surface.iter_mut().zip(&window.moments[..window.len]) {
lagged += share * (moment - lagged);
*out = lagged;
}
}
fn fit_at(
window: &Window,
surface: &[f32; WINDOW_CAPACITY],
delay: usize,
sample_s: f32,
with_alpha: bool,
) -> Option<Fit> {
let len = window.len;
if len < delay + TERMS + 2 {
return None;
}
let between = |values: &[f32; WINDOW_CAPACITY], k: usize| 0.5 * (values[k] + values[k - 1]);
let regressors = |k: usize| {
let alpha = if with_alpha {
between(&window.alphas_rad, k)
} else {
0.0
};
SVector::<f64, TERMS>::new(
f64::from(alpha),
f64::from(between(&window.rates_radps, k)),
f64::from(surface[k - delay]),
1.0,
)
};
let accel =
|k: usize| f64::from((window.rates_radps[k] - window.rates_radps[k - 1]) / sample_s);
let first = delay + 1;
let mut normal = SMatrix::<f64, TERMS, TERMS>::zeros();
let mut moment = SVector::<f64, TERMS>::zeros();
let mut accel_squares = 0.0f64;
for k in first..len {
let (x, y) = (regressors(k), accel(k));
normal += x * x.transpose();
moment += x * y;
accel_squares += y * y;
}
if !with_alpha {
normal[(0, 0)] = 1.0;
}
let terms = normal.lu().solve(&moment)?;
let sum_squares = (accel_squares - terms.dot(&moment)).max(0.0);
let count = (len - first) as f64;
terms.iter().all(|term| term.is_finite()).then(|| Fit {
terms,
residual: libm::sqrt(sum_squares / count),
})
}
fn fit_path_turn(window: &Window, sample_s: f32) -> Option<f32> {
let (mut sxx, mut sx, mut sxy, mut sy, mut n) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 0.0f64);
for k in 1..window.len {
let (alphas, rates) = (&window.alphas_rad, &window.rates_radps);
let alpha = f64::from(0.5 * (alphas[k] + alphas[k - 1]));
let alpha_rate = (alphas[k] - alphas[k - 1]) / sample_s;
let path_rate = f64::from(0.5 * (rates[k] + rates[k - 1]) - alpha_rate);
sxx += alpha * alpha;
sx += alpha;
sxy += alpha * path_rate;
sy += path_rate;
n += 1.0;
}
let spread = n * sxx - sx * sx;
(spread > 0.0).then(|| ((n * sxy - sx * sy) / spread) as f32)
}