numeris 0.5.5

Pure-Rust numerical algorithms library — high performance with SIMD support while also supporting no-std for embedded and WASM targets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use crate::matrix::vector::Vector;
use crate::traits::FloatScalar;
use crate::Matrix;

use super::{apply_var_floor, cholesky_with_jitter, fd_jacobian, EstimateError};

/// Extended Kalman Filter with const-generic state and measurement dimensions.
///
/// `N` is the state dimension, `M` is the measurement dimension.
/// The EKF linearizes nonlinear dynamics and measurement models via
/// user-supplied or finite-difference Jacobians.
///
/// All operations are stack-allocated — no heap, fully no-std compatible.
///
/// # Robustness features
///
/// - **Joseph form** covariance update: `P = (I-KH)P(I-KH)ᵀ + KRKᵀ`
/// - **Cholesky with jitter**: retries with small diagonal ε·I when S is near-singular
/// - **Covariance floor**: `set_min_variance` clamps P diagonal entries to a minimum
/// - **Fading memory**: `set_fading_memory` scales predicted covariance by γ≥1
/// - **Innovation gating**: `update_gated` / `update_fd_gated` reject outlier measurements
/// - **Iterated EKF**: `update_iterated` / `update_fd_iterated` re-linearize at each step
///
/// # Example
///
/// ```
/// use numeris::estimate::Ekf;
/// use numeris::{Vector, Matrix};
///
/// // Constant-velocity model: state = [position, velocity]
/// let x0 = Vector::from_array([0.0_f64, 1.0]);
/// let p0 = Matrix::new([[1.0, 0.0], [0.0, 1.0]]);
/// let mut ekf = Ekf::<f64, 2, 1>::new(x0, p0);
///
/// let dt = 0.1;
/// let q = Matrix::new([[0.01, 0.0], [0.0, 0.01]]);
/// let r = Matrix::new([[0.5]]);
///
/// // Predict (with process noise)
/// ekf.predict(
///     |x| Vector::from_array([x[0] + dt * x[1], x[1]]),
///     |_x| Matrix::new([[1.0, dt], [0.0, 1.0]]),
///     Some(&q),
/// );
///
/// // Update with position measurement
/// ekf.update(
///     &Vector::from_array([0.12]),
///     |x| Vector::from_array([x[0]]),
///     |_x| Matrix::new([[1.0, 0.0]]),
///     &r,
/// ).unwrap();
/// ```
pub struct Ekf<T: FloatScalar, const N: usize, const M: usize> {
    /// State estimate.
    pub x: Vector<T, N>,
    /// State covariance.
    pub p: Matrix<T, N, N>,
    /// Minimum allowed diagonal variance (0 = disabled).
    min_variance: T,
    /// Fading-memory factor γ≥1 applied to predicted covariance (1 = standard).
    gamma: T,
}

impl<T: FloatScalar, const N: usize, const M: usize> Ekf<T, N, M> {
    /// Create a new EKF with initial state `x0` and covariance `p0`.
    pub fn new(x0: Vector<T, N>, p0: Matrix<T, N, N>) -> Self {
        Self {
            x: x0,
            p: p0,
            min_variance: T::zero(),
            gamma: T::one(),
        }
    }

    /// Set a minimum diagonal variance floor applied after every predict/update.
    ///
    /// Prevents covariance from degenerating to zero or going negative
    /// from accumulated numerical subtractions. Pass `0` to disable (default).
    pub fn with_min_variance(mut self, min_variance: T) -> Self {
        self.min_variance = min_variance;
        self
    }

    /// Set a fading-memory factor `γ ≥ 1` applied to the propagated covariance.
    ///
    /// The predicted covariance becomes `γ · F P Fᵀ + Q`. Values `γ > 1`
    /// inflate uncertainty after prediction to compensate for unmodeled dynamics.
    /// Default is `1.0` (standard filter).
    pub fn with_fading_memory(mut self, gamma: T) -> Self {
        self.gamma = gamma;
        self
    }

    /// Reference to the current state estimate.
    #[inline]
    pub fn state(&self) -> &Vector<T, N> {
        &self.x
    }

    /// Reference to the current state covariance.
    #[inline]
    pub fn covariance(&self) -> &Matrix<T, N, N> {
        &self.p
    }

    /// Predict step with explicit dynamics Jacobian.
    ///
    /// - `f` — state transition: `x_{k+1} = f(x_k)`
    /// - `fj` — Jacobian of `f` evaluated at `x_k`: `F = ∂f/∂x`
    /// - `q` — process noise covariance (pass `None` for zero process noise)
    ///
    /// Updates: `x = f(x)`, `P = γ · F P Fᵀ + Q`.
    pub fn predict(
        &mut self,
        f: impl Fn(&Vector<T, N>) -> Vector<T, N>,
        fj: impl Fn(&Vector<T, N>) -> Matrix<T, N, N>,
        q: Option<&Matrix<T, N, N>>,
    ) {
        let big_f = fj(&self.x);
        self.x = f(&self.x);
        self.p = big_f * self.p * big_f.transpose() * self.gamma;
        if let Some(q) = q {
            self.p = self.p + *q;
        }
        let half = T::from(0.5).unwrap();
        self.p = (self.p + self.p.transpose()) * half;
        apply_var_floor(&mut self.p, self.min_variance);
    }

    /// Predict step with finite-difference Jacobian.
    ///
    /// Computes the Jacobian of `f` automatically using forward differences.
    /// Pass `None` for `q` if there is no process noise.
    pub fn predict_fd(
        &mut self,
        f: impl Fn(&Vector<T, N>) -> Vector<T, N>,
        q: Option<&Matrix<T, N, N>>,
    ) {
        let big_f = fd_jacobian(&f, &self.x);
        self.x = f(&self.x);
        self.p = big_f * self.p * big_f.transpose() * self.gamma;
        if let Some(q) = q {
            self.p = self.p + *q;
        }
        let half = T::from(0.5).unwrap();
        self.p = (self.p + self.p.transpose()) * half;
        apply_var_floor(&mut self.p, self.min_variance);
    }

    /// Update step with explicit measurement Jacobian.
    ///
    /// - `z` — measurement vector
    /// - `h` — measurement model: `z = h(x)`
    /// - `hj` — Jacobian of `h` evaluated at `x`: `H = ∂h/∂x`
    /// - `r` — measurement noise covariance
    ///
    /// Uses Joseph form for numerical stability:
    /// `P = (I - KH) P (I - KH)ᵀ + K R Kᵀ`
    ///
    /// Returns the Normalized Innovation Squared (NIS): `yᵀ S⁻¹ y`.
    pub fn update(
        &mut self,
        z: &Vector<T, M>,
        h: impl Fn(&Vector<T, N>) -> Vector<T, M>,
        hj: impl Fn(&Vector<T, N>) -> Matrix<T, M, N>,
        r: &Matrix<T, M, M>,
    ) -> Result<T, EstimateError> {
        let big_h = hj(&self.x);
        let y = *z - h(&self.x); // innovation
        let s = big_h * self.p * big_h.transpose() + *r; // innovation covariance

        // K = P Hᵀ S⁻¹  — S is SPD, so use Cholesky inverse (with jitter fallback).
        let s_inv = cholesky_with_jitter(&s)
            .map_err(|_| EstimateError::SingularInnovation)?
            .inverse();
        let k = self.p * big_h.transpose() * s_inv; // N×M

        // NIS = yᵀ S⁻¹ y
        let nis = (y.transpose() * s_inv * y)[(0, 0)];

        self.x = self.x + k * y;

        // Joseph form: P = (I - KH) P (I - KH)ᵀ + K R Kᵀ
        let eye: Matrix<T, N, N> = Matrix::eye();
        let i_kh = eye - k * big_h;
        self.p = i_kh * self.p * i_kh.transpose() + k * *r * k.transpose();
        let half = T::from(0.5).unwrap();
        self.p = (self.p + self.p.transpose()) * half;
        apply_var_floor(&mut self.p, self.min_variance);

        Ok(nis)
    }

    /// Update step with finite-difference measurement Jacobian.
    ///
    /// Computes the Jacobian of `h` automatically using forward differences.
    ///
    /// Returns the Normalized Innovation Squared (NIS): `yᵀ S⁻¹ y`.
    pub fn update_fd(
        &mut self,
        z: &Vector<T, M>,
        h: impl Fn(&Vector<T, N>) -> Vector<T, M>,
        r: &Matrix<T, M, M>,
    ) -> Result<T, EstimateError> {
        let big_h = fd_jacobian(&h, &self.x);
        let y = *z - h(&self.x);
        let s = big_h * self.p * big_h.transpose() + *r;

        let s_inv = cholesky_with_jitter(&s)
            .map_err(|_| EstimateError::SingularInnovation)?
            .inverse();
        let k = self.p * big_h.transpose() * s_inv;

        // NIS = yᵀ S⁻¹ y
        let nis = (y.transpose() * s_inv * y)[(0, 0)];

        self.x = self.x + k * y;

        let eye: Matrix<T, N, N> = Matrix::eye();
        let i_kh = eye - k * big_h;
        self.p = i_kh * self.p * i_kh.transpose() + k * *r * k.transpose();
        let half = T::from(0.5).unwrap();
        self.p = (self.p + self.p.transpose()) * half;
        apply_var_floor(&mut self.p, self.min_variance);

        Ok(nis)
    }

    /// Update with innovation gating — skips state update if NIS exceeds `gate`.
    ///
    /// Returns `Ok(None)` when the measurement is rejected (outlier), or
    /// `Ok(Some(nis))` when accepted and applied.
    ///
    /// A chi-squared table gives typical gate thresholds:
    /// M=1 → 99%: 6.63 | M=2 → 9.21 | M=3 → 11.34 | M=6 → 16.81
    pub fn update_gated(
        &mut self,
        z: &Vector<T, M>,
        h: impl Fn(&Vector<T, N>) -> Vector<T, M>,
        hj: impl Fn(&Vector<T, N>) -> Matrix<T, M, N>,
        r: &Matrix<T, M, M>,
        gate: T,
    ) -> Result<Option<T>, EstimateError> {
        // Compute NIS without modifying state.
        let big_h = hj(&self.x);
        let y = *z - h(&self.x);
        let s = big_h * self.p * big_h.transpose() + *r;
        let s_inv = cholesky_with_jitter(&s)
            .map_err(|_| EstimateError::SingularInnovation)?
            .inverse();
        let nis = (y.transpose() * s_inv * y)[(0, 0)];
        if nis > gate {
            return Ok(None);
        }
        let nis = self.update(z, h, hj, r)?;
        Ok(Some(nis))
    }

    /// Update with gating and finite-difference Jacobian.
    ///
    /// Returns `Ok(None)` when rejected, `Ok(Some(nis))` when accepted.
    pub fn update_fd_gated(
        &mut self,
        z: &Vector<T, M>,
        h: impl Fn(&Vector<T, N>) -> Vector<T, M>,
        r: &Matrix<T, M, M>,
        gate: T,
    ) -> Result<Option<T>, EstimateError> {
        let big_h = fd_jacobian(&h, &self.x);
        let y = *z - h(&self.x);
        let s = big_h * self.p * big_h.transpose() + *r;
        let s_inv = cholesky_with_jitter(&s)
            .map_err(|_| EstimateError::SingularInnovation)?
            .inverse();
        let nis = (y.transpose() * s_inv * y)[(0, 0)];
        if nis > gate {
            return Ok(None);
        }
        let nis = self.update_fd(z, h, r)?;
        Ok(Some(nis))
    }

    /// Iterated EKF update — re-linearizes at the current iterate until convergence.
    ///
    /// Substantially more accurate than the standard EKF for highly nonlinear
    /// measurement models (e.g., angle/range measurements, attitude-to-pixel projection).
    ///
    /// At each iteration the linearization point advances:
    /// `x_{i+1} = x̄ + K_i (z - h(x_i) - H_i (x̄ - x_i))`
    ///
    /// Iteration stops when `‖x_{i+1} - x_i‖² < tol²`. The final covariance is
    /// updated with the Joseph form at the converged linearization point.
    ///
    /// Returns the Normalized Innovation Squared at the converged solution.
    pub fn update_iterated(
        &mut self,
        z: &Vector<T, M>,
        h: impl Fn(&Vector<T, N>) -> Vector<T, M>,
        hj: impl Fn(&Vector<T, N>) -> Matrix<T, M, N>,
        r: &Matrix<T, M, M>,
        max_iter: usize,
        tol: T,
    ) -> Result<T, EstimateError> {
        let x_pred = self.x;
        let p_pred = self.p;
        let tol_sq = tol * tol;

        let mut x_iter = x_pred;
        for _ in 0..max_iter {
            let big_h = hj(&x_iter);
            // Linearized innovation anchored at x_pred, evaluated at x_iter:
            // y = z - h(x_iter) - H*(x_pred - x_iter) = z - h(x_iter) + H*(x_iter - x_pred)
            let y = *z - h(&x_iter) + big_h * (x_iter - x_pred);
            let s = big_h * p_pred * big_h.transpose() + *r;
            let s_inv = cholesky_with_jitter(&s)
                .map_err(|_| EstimateError::SingularInnovation)?
                .inverse();
            let k = p_pred * big_h.transpose() * s_inv;
            let x_new = x_pred + k * y;

            let delta = x_new - x_iter;
            let sq_norm = delta.frobenius_norm_squared();
            x_iter = x_new;
            if sq_norm < tol_sq {
                break;
            }
        }

        // Final covariance update (Joseph form) at the converged linearization point.
        let big_h = hj(&x_iter);
        let s = big_h * p_pred * big_h.transpose() + *r;
        let s_inv = cholesky_with_jitter(&s)
            .map_err(|_| EstimateError::SingularInnovation)?
            .inverse();
        let k = p_pred * big_h.transpose() * s_inv;

        let y_final = *z - h(&x_iter);
        let nis = (y_final.transpose() * s_inv * y_final)[(0, 0)];

        self.x = x_iter;
        let eye: Matrix<T, N, N> = Matrix::eye();
        let i_kh = eye - k * big_h;
        self.p = i_kh * p_pred * i_kh.transpose() + k * *r * k.transpose();
        let half = T::from(0.5).unwrap();
        self.p = (self.p + self.p.transpose()) * half;
        apply_var_floor(&mut self.p, self.min_variance);

        Ok(nis)
    }

    /// Iterated EKF update with finite-difference Jacobian.
    ///
    /// See [`update_iterated`](Self::update_iterated) for details.
    pub fn update_fd_iterated(
        &mut self,
        z: &Vector<T, M>,
        h: impl Fn(&Vector<T, N>) -> Vector<T, M>,
        r: &Matrix<T, M, M>,
        max_iter: usize,
        tol: T,
    ) -> Result<T, EstimateError> {
        let x_pred = self.x;
        let p_pred = self.p;
        let tol_sq = tol * tol;

        let mut x_iter = x_pred;
        for _ in 0..max_iter {
            let big_h = fd_jacobian(&h, &x_iter);
            let y = *z - h(&x_iter) + big_h * (x_iter - x_pred);
            let s = big_h * p_pred * big_h.transpose() + *r;
            let s_inv = cholesky_with_jitter(&s)
                .map_err(|_| EstimateError::SingularInnovation)?
                .inverse();
            let k = p_pred * big_h.transpose() * s_inv;
            let x_new = x_pred + k * y;

            let delta = x_new - x_iter;
            let sq_norm = delta.frobenius_norm_squared();
            x_iter = x_new;
            if sq_norm < tol_sq {
                break;
            }
        }

        // Final covariance update at converged point.
        let big_h = fd_jacobian(&h, &x_iter);
        let s = big_h * p_pred * big_h.transpose() + *r;
        let s_inv = cholesky_with_jitter(&s)
            .map_err(|_| EstimateError::SingularInnovation)?
            .inverse();
        let k = p_pred * big_h.transpose() * s_inv;

        let y_final = *z - h(&x_iter);
        let nis = (y_final.transpose() * s_inv * y_final)[(0, 0)];

        self.x = x_iter;
        let eye: Matrix<T, N, N> = Matrix::eye();
        let i_kh = eye - k * big_h;
        self.p = i_kh * p_pred * i_kh.transpose() + k * *r * k.transpose();
        let half = T::from(0.5).unwrap();
        self.p = (self.p + self.p.transpose()) * half;
        apply_var_floor(&mut self.p, self.min_variance);

        Ok(nis)
    }
}