nexus-stats 2.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
use crate::math::MulAdd;
macro_rules! impl_kalman1d {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// 1D Kalman filter with constant-velocity model.
        ///
        /// Tracks position and velocity from noisy measurements.
        /// Automatically balances process noise (system uncertainty) against
        /// measurement noise (sensor uncertainty).
        ///
        /// # Timing assumption
        ///
        /// This filter assumes **dt = 1** between consecutive measurements.
        /// For variable-interval data, either:
        /// - Scale `process_noise` proportionally to the actual interval
        /// - Pre-normalize timestamps so samples arrive at uniform intervals
        ///
        /// # Use Cases
        /// - Smoothing noisy position/latency measurements
        /// - Estimating rate of change (velocity) from noisy data
        /// - Predictive filtering (forecast next value)
        #[derive(Debug, Clone)]
        pub struct $name {
            // State: [position, velocity]
            x0: $ty,
            x1: $ty,
            // Covariance: symmetric 2x2 → 3 values (P00, P01, P11)
            p00: $ty,
            p01: $ty,
            p11: $ty,
            // Noise parameters
            q: $ty, // process noise
            r: $ty, // measurement noise
            count: u64,
            min_samples: u64,
            initialized: bool,
        }

        /// Builder for [`
        #[doc = stringify!($name)]
        /// `].
        #[derive(Debug, Clone)]
        pub struct $builder {
            q: Option<$ty>,
            r: Option<$ty>,
            min_samples: u64,
            seed_pos: Option<$ty>,
            seed_vel: Option<$ty>,
        }

        impl $name {
            /// Creates a builder.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    q: Option::None,
                    r: Option::None,
                    min_samples: 1,
                    seed_pos: Option::None,
                    seed_vel: Option::None,
                }
            }

            /// Feeds a measurement. Returns `(position, velocity)` once primed.
            ///
            /// Assumes dt = 1 between measurements. For variable dt, scale
            /// the process noise or pre-process timestamps.
            #[inline]
            #[must_use]
            pub fn update(&mut self, measurement: $ty) -> Option<($ty, $ty)> {
                self.count += 1;

                if !self.initialized {
                    // Initialize from first measurement
                    self.x0 = measurement;
                    self.x1 = 0.0 as $ty;
                    self.p00 = self.r;
                    self.p01 = 0.0 as $ty;
                    self.p11 = 1.0 as $ty;
                    self.initialized = true;

                    return if self.count >= self.min_samples {
                        Option::Some((self.x0, self.x1))
                    } else {
                        Option::None
                    };
                }

                // Predict step (constant velocity model, dt=1)
                // x_pred = F * x = [x0 + x1, x1]
                let pred_x0 = self.x0 + self.x1;
                let pred_x1 = self.x1;

                // P_pred = F * P * F' + Q
                let pred_p00 = (2.0 as $ty).fma(self.p01, self.p00) + self.p11 + self.q;
                let pred_p01 = self.p01 + self.p11;
                let pred_p11 = self.p11 + self.q;

                // Update step
                // Innovation: y = z - H * x_pred (H = [1, 0])
                let y = measurement - pred_x0;

                // Innovation covariance: S = H * P_pred * H' + R = P00 + R
                let s = pred_p00 + self.r;

                // Kalman gain: K = P_pred * H' / S = [P00/S, P01/S]
                let k0 = pred_p00 / s;
                let k1 = pred_p01 / s;

                // State update: x = x_pred + K * y
                self.x0 = k0.fma(y, pred_x0);
                self.x1 = k1.fma(y, pred_x1);

                // Covariance update: P = (I - K*H) * P_pred
                self.p00 = (1.0 as $ty - k0) * pred_p00;
                self.p01 = (1.0 as $ty - k0) * pred_p01;
                self.p11 = pred_p11 - k1 * pred_p01;

                if self.count >= self.min_samples {
                    Option::Some((self.x0, self.x1))
                } else {
                    Option::None
                }
            }

            /// Estimated position, or `None` if not primed.
            #[inline]
            #[must_use]
            pub fn position(&self) -> Option<$ty> {
                if self.count >= self.min_samples {
                    Option::Some(self.x0)
                } else {
                    Option::None
                }
            }

            /// Estimated velocity, or `None` if not primed.
            #[inline]
            #[must_use]
            pub fn velocity(&self) -> Option<$ty> {
                if self.count >= self.min_samples {
                    Option::Some(self.x1)
                } else {
                    Option::None
                }
            }

            /// Position uncertainty (P00).
            #[inline]
            #[must_use]
            pub fn uncertainty(&self) -> $ty {
                self.p00
            }

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

            /// Whether the filter has reached `min_samples`.
            #[inline]
            #[must_use]
            pub fn is_primed(&self) -> bool {
                self.count >= self.min_samples
            }

            /// Resets to uninitialized state.
            #[inline]
            pub fn reset(&mut self) {
                self.x0 = 0.0 as $ty;
                self.x1 = 0.0 as $ty;
                self.p00 = 1.0 as $ty;
                self.p01 = 0.0 as $ty;
                self.p11 = 1.0 as $ty;
                self.count = 0;
                self.initialized = false;
            }
        }

        impl $builder {
            /// Process noise variance. Higher = more reactive to changes.
            ///
            /// The filter assumes dt=1 between samples. For variable-interval
            /// data, scale this value proportionally to the actual interval.
            #[inline]
            #[must_use]
            pub fn process_noise(mut self, q: $ty) -> Self {
                self.q = Option::Some(q);
                self
            }

            /// Measurement noise variance. Higher = smoother output.
            #[inline]
            #[must_use]
            pub fn measurement_noise(mut self, r: $ty) -> Self {
                self.r = Option::Some(r);
                self
            }

            /// Minimum measurements before output is valid. Default: 1.
            #[inline]
            #[must_use]
            pub fn min_samples(mut self, min: u64) -> Self {
                self.min_samples = min;
                self
            }

            /// Pre-load position and velocity from calibration.
            #[inline]
            #[must_use]
            pub fn seed(mut self, position: $ty, velocity: $ty) -> Self {
                self.seed_pos = Option::Some(position);
                self.seed_vel = Option::Some(velocity);
                self
            }

            /// Builds the Kalman filter.
            ///
            /// # Errors
            ///
            /// - process_noise and measurement_noise must have been set.
            /// - Both must be positive.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let q = self.q.ok_or(crate::ConfigError::Missing("process_noise"))?;
                let r = self
                    .r
                    .ok_or(crate::ConfigError::Missing("measurement_noise"))?;
                if q <= 0.0 as $ty {
                    return Err(crate::ConfigError::Invalid(
                        "process_noise must be positive",
                    ));
                }
                if r <= 0.0 as $ty {
                    return Err(crate::ConfigError::Invalid(
                        "measurement_noise must be positive",
                    ));
                }

                let (x0, x1, count, initialized) =
                    if let (Some(pos), Some(vel)) = (self.seed_pos, self.seed_vel) {
                        (pos, vel, self.min_samples, true)
                    } else {
                        (0.0 as $ty, 0.0 as $ty, 0, false)
                    };

                Ok($name {
                    x0,
                    x1,
                    p00: 1.0 as $ty,
                    p01: 0.0 as $ty,
                    p11: 1.0 as $ty,
                    q,
                    r,
                    count,
                    min_samples: self.min_samples,
                    initialized,
                })
            }
        }
    };
}

impl_kalman1d!(Kalman1dF64, Kalman1dF64Builder, f64);
impl_kalman1d!(Kalman1dF32, Kalman1dF32Builder, f32);

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

    #[test]
    fn converges_on_constant() {
        let mut kf = Kalman1dF64::builder()
            .process_noise(0.01)
            .measurement_noise(1.0)
            .build()
            .unwrap();

        for _ in 0..100 {
            let _ = kf.update(50.0);
        }

        let pos = kf.position().unwrap();
        assert!(
            (pos - 50.0).abs() < 1.0,
            "should converge to ~50, got {pos}"
        );
    }

    #[test]
    fn tracks_linear_trend() {
        let mut kf = Kalman1dF64::builder()
            .process_noise(0.1)
            .measurement_noise(1.0)
            .build()
            .unwrap();

        for i in 0..100 {
            let _ = kf.update(i as f64 * 10.0);
        }

        let vel = kf.velocity().unwrap();
        assert!(
            (vel - 10.0).abs() < 2.0,
            "velocity should be ~10, got {vel}"
        );
    }

    #[test]
    fn high_process_noise_reactive() {
        let mut reactive = Kalman1dF64::builder()
            .process_noise(10.0)
            .measurement_noise(1.0)
            .build()
            .unwrap();
        let mut smooth = Kalman1dF64::builder()
            .process_noise(0.001)
            .measurement_noise(1.0)
            .build()
            .unwrap();

        for _ in 0..20 {
            let _ = reactive.update(100.0);
            let _ = smooth.update(100.0);
        }
        // Both at 100. Now jump.
        let _ = reactive.update(200.0);
        let _ = smooth.update(200.0);

        let r_pos = reactive.position().unwrap();
        let s_pos = smooth.position().unwrap();
        assert!(
            r_pos > s_pos,
            "reactive ({r_pos}) should track faster than smooth ({s_pos})"
        );
    }

    #[test]
    fn uncertainty_decreases() {
        let mut kf = Kalman1dF64::builder()
            .process_noise(0.01)
            .measurement_noise(1.0)
            .build()
            .unwrap();

        let _ = kf.update(50.0);
        let u1 = kf.uncertainty();

        for _ in 0..50 {
            let _ = kf.update(50.0);
        }
        let u2 = kf.uncertainty();

        assert!(u2 < u1, "uncertainty should decrease, was {u1} now {u2}");
    }

    #[test]
    fn seeded_startup() {
        let kf = Kalman1dF64::builder()
            .process_noise(0.01)
            .measurement_noise(1.0)
            .seed(100.0, 5.0)
            .build()
            .unwrap();

        assert!(kf.is_primed());
        let pos = kf.position().unwrap();
        assert!((pos - 100.0).abs() < 1e-10);
    }

    #[test]
    fn reset() {
        let mut kf = Kalman1dF64::builder()
            .process_noise(0.01)
            .measurement_noise(1.0)
            .build()
            .unwrap();

        for _ in 0..50 {
            let _ = kf.update(100.0);
        }
        kf.reset();
        assert_eq!(kf.count(), 0);
    }

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

        let _ = kf.update(50.0);
        assert!(kf.position().is_some());
    }

    #[test]
    fn seed_zero_zero_works() {
        let mut kf = Kalman1dF64::builder()
            .process_noise(0.01)
            .measurement_noise(1.0)
            .seed(0.0, 0.0)
            .build()
            .unwrap();

        assert!(kf.is_primed());
        // First update should apply predict+update, not re-initialize
        let (pos, _vel) = kf.update(10.0).unwrap();
        assert!(pos > 0.0, "should track toward 10, got {pos}");
    }

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