pub const DEFAULT_CHI: f64 = 0.001;
pub const PERIOD_HISTORY: usize = 60;
#[derive(Debug, Clone, Copy)]
pub struct Kalman {
estimate: f64,
error: f64,
measurement_variance: f64,
process_noise: f64,
noise_gain: f64,
chi: f64,
periods: [f64; PERIOD_HISTORY],
next_period: usize,
min_measurement_variance: f64,
}
impl Default for Kalman {
fn default() -> Self {
Self {
estimate: 0.0,
error: 0.1,
measurement_variance: 0.0,
process_noise: 1e-3,
noise_gain: 3e-4,
chi: DEFAULT_CHI,
periods: [0.0; PERIOD_HISTORY],
next_period: 0,
min_measurement_variance: 1.0,
}
}
}
impl Kalman {
pub fn new() -> Self {
Self::default()
}
pub fn with_process_noise(mut self, process_noise: f64) -> Self {
self.process_noise = process_noise;
self
}
pub fn estimate(&self) -> f64 {
self.estimate
}
pub fn update(&mut self, measurement: f64) -> f64 {
let noise_gain = self.noise_gain;
self.update_with_noise_gain(measurement, noise_gain)
}
pub fn update_with_period(&mut self, measurement: f64, period_ms: f64) -> f64 {
if period_ms.is_finite() && period_ms > 0.0 {
self.periods[self.next_period] = period_ms;
self.next_period = (self.next_period + 1) % PERIOD_HISTORY;
}
let shortest = self
.periods
.iter()
.copied()
.filter(|period| *period > 0.0)
.fold(f64::INFINITY, f64::min);
let noise_gain = if shortest.is_finite() {
1.0 - (1.0 - self.chi).powf(30.0 * shortest / 1000.0)
} else {
self.noise_gain
};
self.update_with_noise_gain(measurement, noise_gain)
}
pub fn with_chi(mut self, chi: f64) -> Self {
self.chi = chi.clamp(0.001, 0.1);
self
}
fn update_with_noise_gain(&mut self, measurement: f64, noise_gain: f64) -> f64 {
let residual = measurement - self.estimate;
let limit = 3.0
* self
.measurement_variance
.max(self.min_measurement_variance)
.sqrt();
let counted = residual.clamp(-limit, limit);
self.measurement_variance = ((1.0 - noise_gain) * self.measurement_variance
+ noise_gain * counted * counted)
.max(self.min_measurement_variance);
let predicted_error = self.error + self.process_noise;
let gain = predicted_error / (predicted_error + self.measurement_variance);
self.estimate += gain * residual;
self.error = (1.0 - gain) * predicted_error;
self.estimate
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_zero_signal_keeps_a_zero_estimate() {
let mut kalman = Kalman::new();
for _ in 0..100 {
kalman.update(0.0);
}
assert!(
kalman.estimate().abs() < 1e-9,
"estimate drifted to {}",
kalman.estimate()
);
}
#[test]
fn a_sustained_gradient_is_tracked() {
let mut kalman = Kalman::new();
for _ in 0..200 {
kalman.update(10.0);
}
assert!(
(kalman.estimate() - 10.0).abs() < 1.0,
"a steady 10 ms gradient should be tracked, got {}",
kalman.estimate()
);
}
#[test]
fn symmetric_noise_does_not_move_the_estimate() {
let mut kalman = Kalman::new();
for step in 0..400 {
kalman.update(if step % 2 == 0 { 8.0 } else { -8.0 });
}
assert!(
kalman.estimate().abs() < 2.0,
"alternating noise should average out, got {}",
kalman.estimate()
);
}
#[test]
fn a_negative_gradient_is_tracked_too() {
let mut kalman = Kalman::new();
for _ in 0..200 {
kalman.update(-6.0);
}
assert!(
(kalman.estimate() + 6.0).abs() < 1.0,
"a draining queue should read negative, got {}",
kalman.estimate()
);
}
#[test]
fn process_noise_controls_how_fast_a_change_is_tracked() {
let mut slow = Kalman::new().with_process_noise(1e-5);
let mut fast = Kalman::new().with_process_noise(1e-1);
for _ in 0..30 {
slow.update(20.0);
fast.update(20.0);
}
assert!(
fast.estimate() > slow.estimate(),
"more process noise should track faster: slow {}, fast {}",
slow.estimate(),
fast.estimate()
);
}
#[test]
fn the_first_step_is_set_by_e0_q_and_the_variance_floor() {
let mut kalman = Kalman::new();
let estimate = kalman.update(10.0);
let gain = 0.101 / 1.101;
assert!((estimate - 10.0 * gain).abs() < 1e-9, "{estimate}");
}
#[test]
fn an_outlier_enters_the_variance_as_three_deviations() {
let mut with_outlier = Kalman::new();
let mut with_three = Kalman::new();
for _ in 0..50 {
with_outlier.update_with_period(0.0, 10.0);
with_three.update_with_period(0.0, 10.0);
}
with_outlier.update_with_period(1_000.0, 10.0);
with_three.update_with_period(1_000.0, 10.0);
assert!(
with_outlier.measurement_variance < 1.1,
"{}",
with_outlier.measurement_variance
);
assert_eq!(
with_outlier.measurement_variance,
with_three.measurement_variance
);
}
#[test]
fn the_noise_weight_follows_the_group_rate() {
let run = |period: f64| {
let mut kalman = Kalman::new();
for step in 0..200 {
kalman.update_with_period(if step % 2 == 0 { 5.0 } else { -5.0 }, period);
}
kalman.measurement_variance
};
let fast = run(5.0);
let slow = run(33.0);
assert!(slow > fast * 2.0, "fast {fast}, slow {slow}");
}
}