nexus-stats 3.0.0

Fixed-memory, zero-allocation streaming statistics for real-time systems
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#![allow(clippy::suboptimal_flops, clippy::float_cmp)]

macro_rules! impl_kalman3d {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// 3-state Kalman filter with configurable observation model.
        ///
        /// Tracks a 3-element state vector from noisy scalar measurements.
        /// The observation model H is provided at each update, allowing
        /// the measurement to be any linear combination of the state.
        ///
        /// The predict step adds process noise Q to the covariance.
        /// The update step applies the standard Kalman correction.
        ///
        /// # Use Cases
        /// - Position + velocity + acceleration tracking
        /// - Level + trend + curvature estimation
        /// - Any 3-state linear system
        #[derive(Debug, Clone)]
        pub struct $name {
            state: [$ty; 3],
            p: [$ty; 9],
            q: [$ty; 9],
            r: $ty,
            last_innovation: Option<$ty>,
            last_innovation_var: Option<$ty>,
            count: u64,
            initial_state: [$ty; 3],
            initial_p: [$ty; 9],
        }

        /// Builder for [`
        #[doc = stringify!($name)]
        /// `].
        #[derive(Debug, Clone)]
        pub struct $builder {
            process_noise: Option<[[$ty; 3]; 3]>,
            measurement_noise: Option<$ty>,
            initial_state: [$ty; 3],
            initial_covariance: [[$ty; 3]; 3],
        }

        impl $name {
            /// Creates a builder.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    process_noise: Option::None,
                    measurement_noise: Option::None,
                    initial_state: [0.0 as $ty; 3],
                    initial_covariance: [
                        [1.0 as $ty, 0.0 as $ty, 0.0 as $ty],
                        [0.0 as $ty, 1.0 as $ty, 0.0 as $ty],
                        [0.0 as $ty, 0.0 as $ty, 1.0 as $ty],
                    ],
                }
            }

            /// Adds process noise to the covariance: P = P + Q.
            ///
            /// Call this before `update` to model the passage of time
            /// and the associated uncertainty growth.
            #[inline]
            pub fn predict(&mut self) {
                for i in 0..3 {
                    for j in 0..3 {
                        self.p[i * 3 + j] += self.q[i * 3 + j];
                    }
                }
            }

            /// Predict with custom state transition matrix F.
            pub fn predict_with_dynamics(&mut self, f: [[$ty; 3]; 3]) {
                // x_new = F * x
                let mut new_state = [0.0 as $ty; 3];
                for i in 0..3 {
                    for k in 0..3 {
                        new_state[i] += f[i][k] * self.state[k];
                    }
                }
                self.state = new_state;

                // FP = F * P
                let mut fp = [0.0 as $ty; 9];
                for i in 0..3 {
                    for j in 0..3 {
                        for k in 0..3 {
                            fp[i * 3 + j] += f[i][k] * self.p[k * 3 + j];
                        }
                    }
                }

                // P_new = FP * F' + Q
                let mut new_p = [0.0 as $ty; 9];
                for i in 0..3 {
                    for j in 0..3 {
                        for k in 0..3 {
                            new_p[i * 3 + j] += fp[i * 3 + k] * f[j][k];
                        }
                        new_p[i * 3 + j] += self.q[i * 3 + j];
                    }
                }
                self.p = new_p;
            }

            /// Incorporates a scalar observation with observation model H.
            ///
            /// The observation is modeled as:
            /// `z = h[0]*state[0] + h[1]*state[1] + h[2]*state[2] + noise`.
            ///
            /// # Arguments
            /// - `observation` — the measured scalar value
            /// - `h` — the 3-element observation vector [h0, h1, h2]
            ///
            /// # Errors
            ///
            /// Returns `DataError::NotANumber` if the observation is NaN, or
            /// `DataError::Infinite` if the observation is infinite.
            #[inline]
            pub fn update(
                &mut self,
                observation: $ty,
                h: [$ty; 3],
            ) -> Result<(), crate::DataError> {
                check_finite!(observation);
                debug_assert!(h.iter().all(|v| v.is_finite()), "h must be finite");
                // Innovation: y = obs - H*x
                let mut hx = 0.0 as $ty;
                for i in 0..3 {
                    hx += h[i] * self.state[i];
                }
                let y = observation - hx;

                // Innovation covariance: S = H*P*H' + R
                // Epsilon floor prevents NaN if P degrades numerically.
                let mut s = self.r;
                for i in 0..3 {
                    for j in 0..3 {
                        s += h[i] * self.p[i * 3 + j] * h[j];
                    }
                }
                s = s.max(<$ty>::EPSILON);

                // Kalman gain: K = P*H' / S
                let mut k = [0.0 as $ty; 3];
                for i in 0..3 {
                    let mut ph = 0.0 as $ty;
                    for j in 0..3 {
                        ph += self.p[i * 3 + j] * h[j];
                    }
                    k[i] = ph / s;
                }

                // State update: x = x + K*y
                for i in 0..3 {
                    self.state[i] += k[i] * y;
                }

                // Covariance update: P = (I - K*H) * P
                let old_p = self.p;
                for i in 0..3 {
                    for j in 0..3 {
                        let mut sum = 0.0 as $ty;
                        for m in 0..3 {
                            let ikh = if i == m { 1.0 as $ty } else { 0.0 as $ty } - k[i] * h[m];
                            sum += ikh * old_p[m * 3 + j];
                        }
                        self.p[i * 3 + j] = sum;
                    }
                }

                self.last_innovation = Option::Some(y);
                self.last_innovation_var = Option::Some(s);
                self.count += 1;
                Ok(())
            }

            /// Returns the current state estimate [x0, x1, x2].
            #[inline]
            #[must_use]
            pub fn state(&self) -> [$ty; 3] {
                self.state
            }

            /// Returns the current covariance as a 3x3 matrix.
            #[inline]
            #[must_use]
            pub fn covariance(&self) -> [[$ty; 3]; 3] {
                [
                    [self.p[0], self.p[1], self.p[2]],
                    [self.p[3], self.p[4], self.p[5]],
                    [self.p[6], self.p[7], self.p[8]],
                ]
            }

            /// Returns the last innovation (measurement residual), or `None`
            /// if no updates have been performed.
            #[inline]
            #[must_use]
            pub fn innovation(&self) -> Option<$ty> {
                self.last_innovation
            }

            /// Returns the last innovation variance (S), or `None`
            /// if no updates have been performed.
            #[inline]
            #[must_use]
            pub fn innovation_variance(&self) -> Option<$ty> {
                self.last_innovation_var
            }

            /// Number of updates performed.
            #[inline]
            #[must_use]
            pub fn count(&self) -> u64 {
                self.count
            }

            /// Resets to initial state and covariance.
            #[inline]
            pub fn reset(&mut self) {
                self.state = self.initial_state;
                self.p = self.initial_p;
                self.last_innovation = Option::None;
                self.last_innovation_var = Option::None;
                self.count = 0;
            }
        }

        impl $builder {
            /// Sets the 3x3 process noise matrix Q (required).
            #[inline]
            #[must_use]
            pub fn process_noise(mut self, q: [[$ty; 3]; 3]) -> Self {
                self.process_noise = Option::Some(q);
                self
            }

            /// Sets the scalar measurement noise variance R (required, must be > 0).
            #[inline]
            #[must_use]
            pub fn measurement_noise(mut self, r: $ty) -> Self {
                self.measurement_noise = Option::Some(r);
                self
            }

            /// Sets the initial state estimate. Default: [0, 0, 0].
            #[inline]
            #[must_use]
            pub fn initial_state(mut self, state: [$ty; 3]) -> Self {
                self.initial_state = state;
                self
            }

            /// Sets the initial covariance matrix. Default: identity.
            #[inline]
            #[must_use]
            pub fn initial_covariance(mut self, p: [[$ty; 3]; 3]) -> Self {
                self.initial_covariance = p;
                self
            }

            /// Builds the filter.
            ///
            /// # Errors
            ///
            /// - `process_noise` and `measurement_noise` must be set.
            /// - `measurement_noise` must be positive.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let q_mat = self
                    .process_noise
                    .ok_or(crate::ConfigError::Missing("process_noise"))?;
                let r = self
                    .measurement_noise
                    .ok_or(crate::ConfigError::Missing("measurement_noise"))?;

                if r <= 0.0 as $ty {
                    return Err(crate::ConfigError::Invalid(
                        "measurement_noise must be positive",
                    ));
                }

                let mut q = [0.0 as $ty; 9];
                let mut p = [0.0 as $ty; 9];
                for i in 0..3 {
                    for j in 0..3 {
                        q[i * 3 + j] = q_mat[i][j];
                        p[i * 3 + j] = self.initial_covariance[i][j];
                    }
                }

                Ok($name {
                    state: self.initial_state,
                    p,
                    q,
                    r,
                    last_innovation: Option::None,
                    last_innovation_var: Option::None,
                    count: 0,
                    initial_state: self.initial_state,
                    initial_p: p,
                })
            }
        }
    };
}

impl_kalman3d!(Kalman3dF64, Kalman3dF64Builder, f64);
impl_kalman3d!(Kalman3dF32, Kalman3dF32Builder, f32);

#[cfg(test)]
mod tests {
    use super::*;

    fn diagonal_q() -> [[f64; 3]; 3] {
        [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.01]]
    }

    fn diagonal_q_f32() -> [[f32; 3]; 3] {
        [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.01]]
    }

    #[test]
    fn constant_signal_converges() {
        let mut kf = Kalman3dF64::builder()
            .process_noise(diagonal_q())
            .measurement_noise(1.0)
            .build()
            .unwrap();

        for _ in 0..100 {
            kf.predict();
            kf.update(50.0, [1.0, 0.0, 0.0]).unwrap();
        }

        let s = kf.state();
        assert!(
            (s[0] - 50.0).abs() < 1.0,
            "state[0] = {}, expected ~50.0",
            s[0]
        );
    }

    #[test]
    fn covariance_shrinks() {
        // Observe all 3 states to ensure all covariances shrink
        let mut kf = Kalman3dF64::builder()
            .process_noise([[0.001, 0.0, 0.0], [0.0, 0.001, 0.0], [0.0, 0.0, 0.001]])
            .measurement_noise(1.0)
            .initial_covariance([[100.0, 0.0, 0.0], [0.0, 100.0, 0.0], [0.0, 0.0, 100.0]])
            .build()
            .unwrap();

        kf.predict();
        kf.update(50.0, [1.0, 0.0, 0.0]).unwrap();
        kf.update(25.0, [0.0, 1.0, 0.0]).unwrap();
        kf.update(10.0, [0.0, 0.0, 1.0]).unwrap();
        let cov1 = kf.covariance();
        let trace1 = cov1[0][0] + cov1[1][1] + cov1[2][2];

        for _ in 0..50 {
            kf.predict();
            kf.update(50.0, [1.0, 0.0, 0.0]).unwrap();
            kf.update(25.0, [0.0, 1.0, 0.0]).unwrap();
            kf.update(10.0, [0.0, 0.0, 1.0]).unwrap();
        }

        let cov2 = kf.covariance();
        let trace2 = cov2[0][0] + cov2[1][1] + cov2[2][2];

        assert!(
            trace2 < trace1,
            "covariance trace should decrease: {trace1} -> {trace2}"
        );
    }

    #[test]
    fn innovation_stored() {
        let mut kf = Kalman3dF64::builder()
            .process_noise(diagonal_q())
            .measurement_noise(1.0)
            .build()
            .unwrap();

        assert!(kf.innovation().is_none());
        assert!(kf.innovation_variance().is_none());

        kf.predict();
        kf.update(10.0, [1.0, 0.0, 0.0]).unwrap();

        assert!(kf.innovation().is_some());
        assert!(kf.innovation_variance().is_some());
        assert!(kf.innovation_variance().unwrap() > 0.0);
    }

    #[test]
    fn reset_restores_initial() {
        let mut kf = Kalman3dF64::builder()
            .process_noise(diagonal_q())
            .measurement_noise(1.0)
            .initial_state([5.0, 3.0, 1.0])
            .build()
            .unwrap();

        for _ in 0..50 {
            kf.predict();
            kf.update(100.0, [1.0, 0.0, 0.0]).unwrap();
        }

        kf.reset();
        assert_eq!(kf.count(), 0);
        assert_eq!(kf.state(), [5.0, 3.0, 1.0]);
        assert!(kf.innovation().is_none());
    }

    #[test]
    fn f32_basic() {
        let mut kf = Kalman3dF32::builder()
            .process_noise(diagonal_q_f32())
            .measurement_noise(1.0)
            .build()
            .unwrap();

        for _ in 0..100 {
            kf.predict();
            kf.update(50.0, [1.0, 0.0, 0.0]).unwrap();
        }

        let s = kf.state();
        assert!(
            (s[0] - 50.0).abs() < 2.0,
            "state[0] = {}, expected ~50.0",
            s[0]
        );
    }

    #[test]
    fn builder_missing_process_noise() {
        let result = Kalman3dF64::builder().measurement_noise(1.0).build();
        assert!(matches!(
            result,
            Err(crate::ConfigError::Missing("process_noise"))
        ));
    }

    #[test]
    fn builder_missing_measurement_noise() {
        let result = Kalman3dF64::builder().process_noise(diagonal_q()).build();
        assert!(matches!(
            result,
            Err(crate::ConfigError::Missing("measurement_noise"))
        ));
    }

    #[test]
    fn builder_invalid_measurement_noise() {
        let result = Kalman3dF64::builder()
            .process_noise(diagonal_q())
            .measurement_noise(0.0)
            .build();
        assert!(matches!(result, Err(crate::ConfigError::Invalid(_))));

        let result = Kalman3dF64::builder()
            .process_noise(diagonal_q())
            .measurement_noise(-1.0)
            .build();
        assert!(matches!(result, Err(crate::ConfigError::Invalid(_))));
    }

    #[test]
    fn three_state_tracking() {
        // Observe position only, H = [1, 0, 0].
        // True signal: position grows linearly.
        let mut kf = Kalman3dF64::builder()
            .process_noise([[0.1, 0.0, 0.0], [0.0, 0.1, 0.0], [0.0, 0.0, 0.1]])
            .measurement_noise(1.0)
            .build()
            .unwrap();

        for i in 0..200 {
            kf.predict();
            kf.update(i as f64, [1.0, 0.0, 0.0]).unwrap();
        }

        let s = kf.state();
        assert!(
            (s[0] - 199.0).abs() < 5.0,
            "position = {}, expected ~199",
            s[0]
        );
    }

    #[test]
    fn multi_observation_model() {
        // H = [0.5, 0.5, 0.0] — observe average of first two states.
        let mut kf = Kalman3dF64::builder()
            .process_noise(diagonal_q())
            .measurement_noise(0.1)
            .build()
            .unwrap();

        for _ in 0..200 {
            kf.predict();
            // Observe 10.0 = 0.5*x0 + 0.5*x1
            kf.update(10.0, [0.5, 0.5, 0.0]).unwrap();
        }

        let s = kf.state();
        // x0 + x1 should be ~20.0
        let sum = s[0] + s[1];
        assert!((sum - 20.0).abs() < 2.0, "x0 + x1 = {sum}, expected ~20.0");
    }

    #[test]
    fn rejects_nan_and_inf() {
        let mut kf = Kalman3dF64::builder()
            .process_noise(diagonal_q())
            .measurement_noise(1.0)
            .build()
            .unwrap();
        assert_eq!(
            kf.update(f64::NAN, [1.0, 0.0, 0.0]),
            Err(crate::DataError::NotANumber)
        );
        assert_eq!(
            kf.update(f64::INFINITY, [1.0, 0.0, 0.0]),
            Err(crate::DataError::Infinite)
        );
        assert_eq!(kf.count(), 0);
    }
}