From 077f4a17101c2c07acde9b556cd1b0d854b806d3 Mon Sep 17 00:00:00 2001 From: Rahad Bhuiya Date: Sun, 29 Nov 2026 10:05:28 +0600 Subject: [PATCH 1/2] feat(fdir): implement dual-rate adaptive fading memory Kalman filter Closes #36 --- src/fading.rs | 423 ++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 + tests/fading.rs | 129 +++++++++++++++ 3 files changed, 554 insertions(+) create mode 100644 src/fading.rs create mode 100644 tests/fading.rs diff --git a/src/fading.rs b/src/fading.rs new file mode 100644 index 0000000..dadac7c --- /dev/null +++ b/src/fading.rs @@ -0,0 +1,423 @@ +#![allow(clippy::needless_range_loop)] + +use crate::common::{FilterError, FloatOps, Real, DEFAULT_MAX_CONDITION_NUMBER}; +use crate::linear::{check_matrix_conditioning, invert_matrix}; +use crate::simd::joseph_form_covariance_update; + +/// Configuration for [`DualRateFadingKalmanFilter`]. +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct DualRateFadingConfig { + /// Upper bound for the fast fading memory factor ($\lambda \ge 1.0$). + pub max_fading_factor: Real, + /// Upper bound for the slow process noise scaling factor ($Q_{\text{scale}} \ge 1.0$). + pub max_q_scale: Real, + /// Mean Normalized Innovation Squared (NIS) threshold above which $Q$ scales up. + pub nis_upper_threshold: Real, + /// Mean NIS threshold below which $Q_{\text{scale}}$ decays back toward `1.0`. + pub nis_lower_threshold: Real, + /// Multiplicative growth rate applied to `q_scale` when NIS exceeds `nis_upper_threshold`. + pub q_growth_rate: Real, + /// Exponential decay factor in `(0, 1)` pulling `q_scale` back toward `1.0` when nominal. + pub q_decay_rate: Real, +} + +impl Default for DualRateFadingConfig { + fn default() -> Self { + Self { + max_fading_factor: 8.0, + max_q_scale: 100.0, + nis_upper_threshold: 2.0, + nis_lower_threshold: 1.2, + q_growth_rate: 1.25, + q_decay_rate: 0.9, + } + } +} + +impl DualRateFadingConfig { + pub fn validate(&self) -> Result<(), FilterError> { + if !self.max_fading_factor.is_valid_float() + || !self.max_q_scale.is_valid_float() + || !self.nis_upper_threshold.is_valid_float() + || !self.nis_lower_threshold.is_valid_float() + || !self.q_growth_rate.is_valid_float() + || !self.q_decay_rate.is_valid_float() + { + return Err(FilterError::NonFiniteInput); + } + if self.max_fading_factor < 1.0 + || self.max_q_scale < 1.0 + || self.nis_lower_threshold <= 0.0 + || self.nis_upper_threshold < self.nis_lower_threshold + || self.q_growth_rate < 1.0 + || self.q_decay_rate <= 0.0 + || self.q_decay_rate >= 1.0 + { + return Err(FilterError::InvalidParameter); + } + Ok(()) + } +} + +/// Dual-rate adaptive fading memory Kalman filter for tracking unmodeled dynamics and sensor degradation. +/// +/// Combines: +/// - **Fast rate**: A fading memory factor $\lambda_k \ge 1.0$ that inflates the prior covariance +/// $P_{k|k-1}$ whenever residuals exceed theoretical innovation bounds. +/// - **Slow rate**: A sliding-window innovation covariance $\hat{C}_k$ over `W` samples that scales +/// process noise $Q$ when normalized innovations persistently exceed statistical bounds. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct DualRateFadingKalmanFilter { + x: [Real; S], + p: [[Real; S]; S], + f: [[Real; S]; S], + h: [[Real; S]; M], + q_base: [[Real; S]; S], + r: [[Real; M]; M], + config: DualRateFadingConfig, + lambda: Real, + q_scale: Real, + #[cfg_attr(feature = "serde", serde(skip))] + y_window: [[Real; M]; W], + #[cfg_attr(feature = "serde", serde(skip))] + nis_window: [Real; W], + window_head: usize, + window_count: usize, +} + +impl DualRateFadingKalmanFilter { + pub fn new( + initial_x: [Real; S], + initial_p: [[Real; S]; S], + f: [[Real; S]; S], + h: [[Real; S]; M], + q_base: [[Real; S]; S], + r: [[Real; M]; M], + config: DualRateFadingConfig, + ) -> Result { + if S == 0 || M == 0 || W == 0 { + return Err(FilterError::InvalidParameter); + } + config.validate()?; + if !initial_x.iter().all(|v| v.is_valid_float()) + || !f.iter().flatten().all(|v| v.is_valid_float()) + || !h.iter().flatten().all(|v| v.is_valid_float()) + || !q_base.iter().flatten().all(|v| v.is_valid_float()) + { + return Err(FilterError::NonFiniteInput); + } + + check_matrix_conditioning(&initial_p, DEFAULT_MAX_CONDITION_NUMBER)?; + check_matrix_conditioning(&r, DEFAULT_MAX_CONDITION_NUMBER)?; + for i in 0..S { + if q_base[i][i] < 0.0 { + return Err(FilterError::InvalidCovariance); + } + } + + Ok(Self { + x: initial_x, + p: initial_p, + f, + h, + q_base, + r, + config, + lambda: 1.0, + q_scale: 1.0, + y_window: [[0.0; M]; W], + nis_window: [0.0; W], + window_head: 0, + window_count: 0, + }) + } + + pub fn set_transition(&mut self, f: [[Real; S]; S]) -> Result<(), FilterError> { + if !f.iter().flatten().all(|v| v.is_valid_float()) { + return Err(FilterError::NonFiniteInput); + } + self.f = f; + Ok(()) + } + + #[inline] + pub fn state(&self) -> &[Real; S] { + &self.x + } + + #[inline] + pub fn covariance(&self) -> &[[Real; S]; S] { + &self.p + } + + #[inline] + pub fn fading_factor(&self) -> Real { + self.lambda + } + + #[inline] + pub fn q_scale(&self) -> Real { + self.q_scale + } + + /// Computes the empirical sliding-window innovation covariance $\hat{C}_k = \frac{1}{n} \sum y_i y_i^T$. + pub fn sliding_window_innovation_covariance(&self) -> [[Real; M]; M] { + let mut c = [[0.0; M]; M]; + if self.window_count == 0 { + return c; + } + let inv_n = 1.0 / (self.window_count as Real); + for idx in 0..self.window_count { + let y = &self.y_window[idx]; + for i in 0..M { + for j in 0..M { + c[i][j] += y[i] * y[j] * inv_n; + } + } + } + c + } + + /// Returns the mean Normalized Innovation Squared (NIS / M) across the active sliding window. + pub fn window_mean_nis(&self) -> Real { + if self.window_count == 0 { + return 0.0; + } + let mut sum = 0.0; + for idx in 0..self.window_count { + sum += self.nis_window[idx]; + } + sum / (self.window_count as Real) + } + + pub fn predict(&mut self) -> Result<[Real; S], FilterError> { + let mut x_next = [0.0; S]; + for i in 0..S { + let mut acc = 0.0; + for j in 0..S { + acc += self.f[i][j] * self.x[j]; + } + if !acc.is_valid_float() { + return Err(FilterError::NumericalInstability); + } + x_next[i] = acc; + } + + let mut fp = [[0.0; S]; S]; + for i in 0..S { + for j in 0..S { + let mut acc = 0.0; + for k in 0..S { + acc += self.f[i][k] * self.p[k][j]; + } + fp[i][j] = acc; + } + } + + let mut p_next = [[0.0; S]; S]; + for i in 0..S { + for j in 0..S { + let mut acc = 0.0; + for k in 0..S { + acc += fp[i][k] * self.f[j][k]; + } + p_next[i][j] = acc + self.q_scale * self.q_base[i][j]; + } + } + + for i in 0..S { + for j in (i + 1)..S { + let avg = 0.5 * (p_next[i][j] + p_next[j][i]); + p_next[i][j] = avg; + p_next[j][i] = avg; + } + if !p_next[i][i].is_valid_float() { + return Err(FilterError::NumericalInstability); + } + } + + self.x = x_next; + self.p = p_next; + Ok(self.x) + } + + pub fn update( + &mut self, + measurement: &[Real; M], + gate_sigma: Option, + ) -> Result<[Real; S], FilterError> { + if !measurement.iter().all(|v| v.is_valid_float()) { + return Err(FilterError::NonFiniteInput); + } + + let mut y = [0.0; M]; + for j in 0..M { + let mut z_hat = 0.0; + for i in 0..S { + z_hat += self.h[j][i] * self.x[i]; + } + y[j] = measurement[j] - z_hat; + } + + let (mut pht, mut s, mut s_inv) = self.compute_innovation_cov(&self.p)?; + + let mut d2_nom = 0.0; + for i in 0..M { + for j in 0..M { + d2_nom += y[i] * s_inv[i][j] * y[j]; + } + } + if !d2_nom.is_valid_float() { + return Err(FilterError::NumericalInstability); + } + let d2_nom = d2_nom.max(0.0); + + if let Some(gate) = gate_sigma { + if gate <= 0.0 || !gate.is_valid_float() { + return Err(FilterError::InvalidParameter); + } + if d2_nom.sqrt_val() > gate { + return Err(FilterError::MeasurementGated); + } + } + + let nis_sample = d2_nom / (M as Real); + self.y_window[self.window_head] = y; + self.nis_window[self.window_head] = nis_sample; + self.window_head = (self.window_head + 1) % W; + if self.window_count < W { + self.window_count += 1; + } + + let c_hat = self.sliding_window_innovation_covariance(); + let mean_nis = self.window_mean_nis(); + + let mut tr_c = 0.0; + let mut tr_s = 0.0; + for i in 0..M { + tr_c += c_hat[i][i]; + tr_s += s[i][i]; + } + let trace_ratio = if tr_s > 1e-15 { tr_c / tr_s } else { 1.0 }; + + // Fast rate: fading factor lambda >= 1.0 scales prior covariance when residuals jump. + let fast_ratio = trace_ratio.max(nis_sample); + self.lambda = fast_ratio.clamp(1.0, self.config.max_fading_factor); + + if self.lambda > 1.0 { + for i in 0..S { + for j in 0..S { + self.p[i][j] *= self.lambda; + } + } + let recomputed = self.compute_innovation_cov(&self.p)?; + pht = recomputed.0; + s = recomputed.1; + s_inv = recomputed.2; + } + let _ = s; + + // Slow rate: scale process noise Q based on persistent window NIS. + if mean_nis > self.config.nis_upper_threshold { + self.q_scale = (self.q_scale * self.config.q_growth_rate).min(self.config.max_q_scale); + } else if mean_nis < self.config.nis_lower_threshold { + let decayed = 1.0 + (self.q_scale - 1.0) * self.config.q_decay_rate; + self.q_scale = decayed.max(1.0); + } + + let mut k = [[0.0; M]; S]; + for i in 0..S { + for j in 0..M { + let mut acc = 0.0; + for l in 0..M { + acc += pht[i][l] * s_inv[l][j]; + } + k[i][j] = acc; + } + } + + let mut x_new = self.x; + for i in 0..S { + let mut acc = 0.0; + for j in 0..M { + acc += k[i][j] * y[j]; + } + x_new[i] += acc; + } + + let mut e = [[0.0; S]; S]; + for i in 0..S { + for j in 0..S { + let mut kh = 0.0; + for l in 0..M { + kh += k[i][l] * self.h[l][j]; + } + e[i][j] = if i == j { 1.0 - kh } else { -kh }; + } + } + + let mut p_new = [[0.0; S]; S]; + joseph_form_covariance_update::(&e, &self.p, &k, &self.r, &mut p_new); + + for i in 0..S { + for j in i..S { + let avg = 0.5 * (p_new[i][j] + p_new[j][i]); + p_new[i][j] = avg; + p_new[j][i] = avg; + } + if p_new[i][i] < 1e-15 { + p_new[i][i] = 1e-15; + } + } + + if !x_new.iter().all(|v| v.is_valid_float()) + || !p_new.iter().flatten().all(|v| v.is_valid_float()) + { + return Err(FilterError::NumericalInstability); + } + + self.x = x_new; + self.p = p_new; + Ok(self.x) + } + + #[allow(clippy::type_complexity)] + fn compute_innovation_cov( + &self, + p: &[[Real; S]; S], + ) -> Result<([[Real; M]; S], [[Real; M]; M], [[Real; M]; M]), FilterError> { + let mut pht = [[0.0; M]; S]; + for i in 0..S { + for j in 0..M { + let mut acc = 0.0; + for l in 0..S { + acc += p[i][l] * self.h[j][l]; + } + pht[i][j] = acc; + } + } + + let mut s = [[0.0; M]; M]; + for i in 0..M { + for j in 0..M { + let mut acc = self.r[i][j]; + for l in 0..S { + acc += self.h[i][l] * pht[l][j]; + } + s[i][j] = acc; + } + } + for i in 0..M { + for j in (i + 1)..M { + let avg = 0.5 * (s[i][j] + s[j][i]); + s[i][j] = avg; + s[j][i] = avg; + } + } + + let s_inv = invert_matrix(&s)?; + Ok((pht, s, s_inv)) + } +} diff --git a/src/lib.rs b/src/lib.rs index 9825efc..38bcb1b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,6 +26,7 @@ fn panic(_info: &core::panic::PanicInfo) -> ! { pub mod common; pub mod eskf; +pub mod fading; #[cfg(feature = "ffi")] pub mod ffi; pub mod fusion; @@ -43,6 +44,7 @@ pub use eskf::{ ErrorStateKalmanFilter, EskfNoiseParameters, EskfNominalState, Quaternion, Vector3, EARTH_GRAVITY_Z_UP, }; +pub use fading::{DualRateFadingConfig, DualRateFadingKalmanFilter}; pub use fusion::{FusionStatus, MultiSensorFusion1D, SensorMeasurement, SensorSource}; pub use linear::{ check_matrix_conditioning, invert_matrix, matrix_condition_number, matrix_norm_1, diff --git a/tests/fading.rs b/tests/fading.rs new file mode 100644 index 0000000..ad40bb7 --- /dev/null +++ b/tests/fading.rs @@ -0,0 +1,129 @@ +use aegis_filter::{ + DualRateFadingConfig, DualRateFadingKalmanFilter, FilterError, LinearKalmanFilter, +}; + +#[test] +fn step_function_acceleration_anomaly_adapts_and_recovers() { + let dt = 0.1; + let f = [[1.0, dt], [0.0, 1.0]]; + let h = [[1.0, 0.0]]; + let q_base = [[1e-4, 0.0], [0.0, 1e-4]]; + let r = [[0.04]]; + let init_p = [[1.0, 0.0], [0.0, 1.0]]; + let init_x = [0.0, 10.0]; + + let mut fading = DualRateFadingKalmanFilter::<2, 1, 8>::new( + init_x, + init_p, + f, + h, + q_base, + r, + DualRateFadingConfig::default(), + ) + .expect("valid fading filter"); + + let mut static_kf = + LinearKalmanFilter::<2, 1>::new(init_x, init_p, f, q_base, h, r).expect("valid static kf"); + + let mut true_pos = 0.0; + let mut true_vel = 10.0; + let mut max_lambda_during_burn = 1.0_f64; + let mut max_q_scale_during_burn = 1.0_f64; + let mut fading_burn_err_sum = 0.0; + let mut static_burn_err_sum = 0.0; + + for step in 0..200 { + let accel = if (40..100).contains(&step) { 6.0 } else { 0.0 }; + true_pos += true_vel * dt + 0.5 * accel * dt * dt; + true_vel += accel * dt; + + fading.predict().expect("fading predict"); + static_kf.predict().expect("static predict"); + + let z = [true_pos]; + let x_f = fading.update(&z, None).expect("fading update"); + let x_s = static_kf.update(&z, None).expect("static update"); + + if (40..100).contains(&step) { + max_lambda_during_burn = max_lambda_during_burn.max(fading.fading_factor()); + max_q_scale_during_burn = max_q_scale_during_burn.max(fading.q_scale()); + fading_burn_err_sum += (x_f[0] - true_pos).abs(); + static_burn_err_sum += (x_s[0] - true_pos).abs(); + } + } + + assert!( + max_lambda_during_burn > 1.5, + "expected fast fading factor > 1.5 during step acceleration, got {max_lambda_during_burn}" + ); + assert!( + max_q_scale_during_burn > 2.0, + "expected slow Q scaling > 2.0 during step acceleration, got {max_q_scale_during_burn}" + ); + assert!( + fading_burn_err_sum < static_burn_err_sum * 0.25, + "expected fading filter error ({fading_burn_err_sum}) << static KF error ({static_burn_err_sum})" + ); + + // After 100 nominal post-burn steps, fading factor and q_scale should recover toward 1.0. + assert!(fading.fading_factor() <= 1.05); + assert!(fading.q_scale() < max_q_scale_during_burn); + assert!((fading.state()[0] - true_pos).abs() < 0.5); + assert!((fading.state()[1] - true_vel).abs() < 1.0); +} + +#[test] +fn sliding_window_innovation_covariance_tracks_residual_energy() { + let f = [[1.0]]; + let h = [[1.0]]; + let q_base = [[1e-3]]; + let r = [[1.0]]; + let init_p = [[1.0]]; + let init_x = [0.0]; + + let mut filter = DualRateFadingKalmanFilter::<1, 1, 4>::new( + init_x, + init_p, + f, + h, + q_base, + r, + DualRateFadingConfig::default(), + ) + .expect("valid filter"); + + for i in 0..4 { + filter.predict().expect("predict"); + filter.update(&[(i + 1) as f64], None).expect("update"); + } + + let c_hat = filter.sliding_window_innovation_covariance(); + assert!(c_hat[0][0] > 0.0); + assert!(filter.window_mean_nis() > 0.0); +} + +#[test] +fn outlier_gating_and_config_validation() { + let bad_cfg = DualRateFadingConfig { + max_fading_factor: 0.5, + ..Default::default() + }; + assert_eq!(bad_cfg.validate(), Err(FilterError::InvalidParameter)); + + let mut filter = DualRateFadingKalmanFilter::<1, 1, 4>::new( + [0.0], + [[1.0]], + [[1.0]], + [[1.0]], + [[0.01]], + [[0.01]], + DualRateFadingConfig::default(), + ) + .expect("valid filter"); + + filter.predict().expect("predict"); + let gated = filter.update(&[100.0], Some(3.0)); + assert_eq!(gated, Err(FilterError::MeasurementGated)); + assert_eq!(filter.fading_factor(), 1.0); +} From 676d4236eb496c6ff1792f9c14fe7dbaa475c3bd Mon Sep 17 00:00:00 2001 From: Rahad Bhuiya Date: Sun, 29 Nov 2026 10:09:35 +0600 Subject: [PATCH 2/2] fix(fading): remove serde derive on const-generic array struct --- src/fading.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/fading.rs b/src/fading.rs index dadac7c..0e3e056 100644 --- a/src/fading.rs +++ b/src/fading.rs @@ -68,7 +68,6 @@ impl DualRateFadingConfig { /// - **Slow rate**: A sliding-window innovation covariance $\hat{C}_k$ over `W` samples that scales /// process noise $Q$ when normalized innovations persistently exceed statistical bounds. #[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct DualRateFadingKalmanFilter { x: [Real; S], p: [[Real; S]; S], @@ -79,9 +78,7 @@ pub struct DualRateFadingKalmanFilter