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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Online Polynomial Regression — Sufficient Statistics + Normal Equations
//
// Accumulates sums of powers of x and cross-products with y.
// Solves normal equations via Gaussian elimination at query time.
// O(degree) per update, O(degree³) per query (bounded, max 9×9).
//
// degree and intercept are runtime-configured via builder.

// Normal equations with sums-of-powers can accumulate large values.
#![allow(clippy::suboptimal_flops)]

macro_rules! impl_coefficients {
    ($name:ident, $ty:ty) => {
        /// Polynomial coefficients returned by regression queries.
        ///
        /// With intercept: `values[0]` = constant (a₀), `values[1]` = x coefficient (a₁), etc.
        /// Without intercept: `values[0]` = x¹ coefficient, `values[1]` = x² coefficient, etc.
        #[derive(Debug, Clone, Copy)]
        pub struct $name {
            pub(crate) values: [$ty; 9],
            pub(crate) len: usize,
        }

        impl $name {
            /// Coefficients as a slice.
            #[inline]
            #[must_use]
            pub fn as_slice(&self) -> &[$ty] {
                &self.values[..self.len]
            }

            /// Number of coefficients.
            #[inline]
            #[must_use]
            pub fn len(&self) -> usize {
                self.len
            }

            /// Whether there are no coefficients (should never happen in practice).
            #[inline]
            #[must_use]
            pub fn is_empty(&self) -> bool {
                self.len == 0
            }

            /// Get the i-th coefficient, or `None` if out of range.
            #[inline]
            #[must_use]
            pub fn get(&self, i: usize) -> Option<$ty> {
                if i < self.len {
                    Option::Some(self.values[i])
                } else {
                    Option::None
                }
            }
        }

        impl core::ops::Index<usize> for $name {
            type Output = $ty;
            #[inline]
            fn index(&self, i: usize) -> &$ty {
                assert!(
                    i < self.len,
                    "coefficient index {i} out of range (len={})",
                    self.len
                );
                &self.values[i]
            }
        }
    };
}

impl_coefficients!(CoefficientsF64, f64);
impl_coefficients!(CoefficientsF32, f32);

/// Gaussian elimination with partial pivoting on a fixed-size system.
/// Returns `true` if the solve succeeded (non-singular).
/// On success, `rhs` contains the solution.
macro_rules! impl_gauss_solve {
    ($fn_name:ident, $ty:ty) => {
        pub(crate) fn $fn_name(dim: usize, a: &mut [[$ty; 9]; 9], b: &mut [$ty; 9]) -> bool {
            for col in 0..dim {
                let mut max_row = col;
                let mut max_val = if a[col][col] < 0.0 as $ty {
                    -(a[col][col])
                } else {
                    a[col][col]
                };
                for row in (col + 1)..dim {
                    let v = if a[row][col] < 0.0 as $ty {
                        -(a[row][col])
                    } else {
                        a[row][col]
                    };
                    if v > max_val {
                        max_val = v;
                        max_row = row;
                    }
                }
                if max_val < 1e-14 as $ty {
                    return false;
                }
                if max_row != col {
                    a.swap(col, max_row);
                    b.swap(col, max_row);
                }
                for row in (col + 1)..dim {
                    let factor = a[row][col] / a[col][col];
                    for j in col..dim {
                        a[row][j] -= factor * a[col][j];
                    }
                    b[row] -= factor * b[col];
                }
            }
            for i in (0..dim).rev() {
                for j in (i + 1)..dim {
                    b[i] -= a[i][j] * b[j];
                }
                b[i] /= a[i][i];
            }
            true
        }
    };
}

impl_gauss_solve!(gauss_solve_f64, f64);
impl_gauss_solve!(gauss_solve_f32, f32);

macro_rules! impl_polynomial_regression {
    ($name:ident, $builder:ident, $coeff:ident, $solve_fn:ident, $ty:ty) => {
        /// Online polynomial regression via sufficient statistics.
        ///
        /// Accumulates sums of powers of x and cross-products with y.
        /// Solves the normal equations at query time via Gaussian elimination
        /// with partial pivoting.
        ///
        /// Degree and intercept are configured at construction via the builder.
        /// Supports degree 1 (linear) through 8 (octic).
        ///
        /// For best numerical stability with high-degree fits or large x ranges,
        /// center and scale your x values: `x_scaled = (x - x_mean) / x_std`.
        ///
        /// # Complexity
        /// - O(degree) per update, O(degree³) per coefficient query.
        /// - ~216 bytes state (f64), ~120 bytes (f32). Zero allocation.
        ///
        /// # Examples
        ///
        /// ```
        #[doc = concat!("use nexus_stats::regression::", stringify!($name), ";")]
        ///
        /// // Fit y = x² - 3x + 2 (quadratic)
        #[doc = concat!("let mut r = ", stringify!($name), "::builder().degree(2).build().unwrap();")]
        /// for x in -50..50i64 {
        #[doc = concat!("    let xf = x as ", stringify!($ty), ";")]
        #[doc = concat!("    r.update(xf, xf * xf - 3.0 as ", stringify!($ty), " * xf + 2.0 as ", stringify!($ty), ");")]
        /// }
        /// let c = r.coefficients().unwrap();
        /// assert_eq!(c.len(), 3); // [constant, x, x²]
        /// ```
        #[derive(Debug, Clone)]
        pub struct $name {
            sum_x: [$ty; 17],
            sum_xy: [$ty; 9],
            sum_y2: $ty,
            count: u64,
            degree: usize,
            intercept: bool,
        }

        /// Builder for [`
        #[doc = stringify!($name)]
        /// `].
        #[derive(Debug, Clone)]
        pub struct $builder {
            degree: Option<usize>,
            intercept: bool,
        }

        impl $name {
            /// Creates a builder.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    degree: Option::None,
                    intercept: true,
                }
            }

            /// System dimension.
            #[inline]
            fn dim(&self) -> usize {
                self.degree + self.intercept as usize
            }

            /// Configured polynomial degree.
            #[inline]
            #[must_use]
            pub fn degree(&self) -> usize {
                self.degree
            }

            /// Whether the intercept (constant term) is included.
            #[inline]
            #[must_use]
            pub fn has_intercept(&self) -> bool {
                self.intercept
            }

            /// Feeds an (x, y) observation.
            ///
            /// # Errors
            ///
            /// Returns `DataError::NotANumber` if either value is NaN, or
            /// `DataError::Infinite` if either value is infinite.
            #[inline]
            pub fn update(&mut self, x: $ty, y: $ty) -> Result<(), crate::DataError> {
                check_finite!(x);
                check_finite!(y);
                self.count += 1;
                self.sum_y2 += y * y;
                let mut x_pow = 1.0 as $ty;
                let max_pow = 2 * self.degree;
                for j in 0..=max_pow {
                    self.sum_x[j] += x_pow;
                    if j <= self.degree {
                        self.sum_xy[j] += x_pow * y;
                    }
                    x_pow *= x;
                }
                Ok(())
            }

            /// Solve for polynomial coefficients, or `None` if underdetermined.
            ///
            /// Returns coefficients indexed from constant term (a₀) to highest
            /// power (aₖ). Without intercept, the first coefficient corresponds
            /// to x¹.
            #[must_use]
            pub fn coefficients(&self) -> Option<$coeff> {
                let dim = self.dim();
                if (self.count as usize) < dim {
                    return Option::None;
                }

                let mut a = [[0.0 as $ty; 9]; 9];
                let mut b = [0.0 as $ty; 9];
                let offset: usize = if self.intercept { 0 } else { 1 };

                for i in 0..dim {
                    for j in 0..dim {
                        a[i][j] = self.sum_x[i + j + 2 * offset];
                    }
                    b[i] = self.sum_xy[i + offset];
                }

                if !$solve_fn(dim, &mut a, &mut b) {
                    return Option::None;
                }

                let mut coeffs = $coeff {
                    values: [0.0 as $ty; 9],
                    len: dim,
                };
                for i in 0..dim {
                    coeffs.values[i] = b[i];
                }
                Option::Some(coeffs)
            }

            /// R² goodness of fit, or `None` if not enough data.
            ///
            /// With intercept: centered R² = 1 - SS_res/SS_tot.
            /// Without intercept: uncentered R² = 1 - SS_res/Σy².
            #[must_use]
            pub fn r_squared(&self) -> Option<$ty> {
                let coeffs = self.coefficients()?;
                let n = self.count as $ty;
                let dim = self.dim();
                let offset: usize = if self.intercept { 0 } else { 1 };

                let mut beta_dot_rhs = 0.0 as $ty;
                for i in 0..dim {
                    beta_dot_rhs += coeffs.values[i] * self.sum_xy[i + offset];
                }
                let ss_res = self.sum_y2 - beta_dot_rhs;

                let ss_tot = if self.intercept {
                    let sum_y = self.sum_xy[0];
                    self.sum_y2 - sum_y * sum_y / n
                } else {
                    self.sum_y2
                };

                if ss_tot <= 0.0 as $ty {
                    return Option::None;
                }

                Option::Some(1.0 as $ty - ss_res / ss_tot)
            }

            /// Predict y for a given x using current coefficients.
            #[must_use]
            pub fn predict(&self, x: $ty) -> Option<$ty> {
                let coeffs = self.coefficients()?;
                let dim = self.dim();

                let mut y = 0.0 as $ty;
                let mut x_pow = if self.intercept { 1.0 as $ty } else { x };
                for i in 0..dim {
                    y += coeffs.values[i] * x_pow;
                    x_pow *= x;
                }
                Option::Some(y)
            }

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

            /// Whether enough data has been collected to solve (count >= dim).
            #[inline]
            #[must_use]
            pub fn is_primed(&self) -> bool {
                (self.count as usize) >= self.dim()
            }

            /// Resets to empty state. Degree and intercept unchanged.
            #[inline]
            pub fn reset(&mut self) {
                self.sum_x = [0.0 as $ty; 17];
                self.sum_xy = [0.0 as $ty; 9];
                self.sum_y2 = 0.0 as $ty;
                self.count = 0;
            }
        }

        impl $builder {
            /// Polynomial degree (1..=8). Required.
            #[inline]
            #[must_use]
            pub fn degree(mut self, degree: usize) -> Self {
                self.degree = Option::Some(degree);
                self
            }

            /// Whether to include the constant term. Default: `true`.
            ///
            /// `false` forces the fit through the origin.
            #[inline]
            #[must_use]
            pub fn intercept(mut self, intercept: bool) -> Self {
                self.intercept = intercept;
                self
            }

            /// Builds the regression estimator.
            ///
            /// # Errors
            ///
            /// Returns `ConfigError::Missing` if degree not set.
            /// Returns `ConfigError::Invalid` if degree not in 1..=8.
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let degree = self.degree
                    .ok_or(crate::ConfigError::Missing("degree"))?;
                if degree < 1 || degree > 8 {
                    return Err(crate::ConfigError::Invalid(
                        "degree must be in 1..=8",
                    ));
                }

                Ok($name {
                    sum_x: [0.0 as $ty; 17],
                    sum_xy: [0.0 as $ty; 9],
                    sum_y2: 0.0 as $ty,
                    count: 0,
                    degree,
                    intercept: self.intercept,
                })
            }
        }
    };
}

impl_polynomial_regression!(
    PolynomialRegressionF64,
    PolynomialRegressionF64Builder,
    CoefficientsF64,
    gauss_solve_f64,
    f64
);
impl_polynomial_regression!(
    PolynomialRegressionF32,
    PolynomialRegressionF32Builder,
    CoefficientsF32,
    gauss_solve_f32,
    f32
);

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

    fn quadratic() -> PolynomialRegressionF64 {
        PolynomialRegressionF64::builder()
            .degree(2)
            .build()
            .unwrap()
    }

    fn cubic() -> PolynomialRegressionF64 {
        PolynomialRegressionF64::builder()
            .degree(3)
            .build()
            .unwrap()
    }

    // =========================================================================
    // Quadratic regression (y = ax² + bx + c)
    // =========================================================================

    #[test]
    fn quadratic_exact_fit() {
        let mut r = quadratic();
        for x in -50..50 {
            let xf = x as f64;
            r.update(xf, xf * xf - 3.0 * xf + 2.0).unwrap();
        }
        let c = r.coefficients().unwrap();
        assert!((c[0] - 2.0).abs() < 1e-6, "c0 = {}", c[0]);
        assert!((c[1] - (-3.0)).abs() < 1e-6, "c1 = {}", c[1]);
        assert!((c[2] - 1.0).abs() < 1e-6, "c2 = {}", c[2]);
    }

    #[test]
    fn quadratic_predict() {
        let mut r = quadratic();
        for x in -50..50 {
            let xf = x as f64;
            r.update(xf, xf * xf).unwrap();
        }
        let y = r.predict(10.0).unwrap();
        assert!((y - 100.0).abs() < 1e-4, "predict(10) = {y}");
    }

    // =========================================================================
    // Cubic
    // =========================================================================

    #[test]
    fn cubic_exact_fit() {
        let mut r = cubic();
        for x in -20..20 {
            let xf = x as f64;
            let y = 0.5 * xf * xf * xf - 2.0 * xf * xf + xf - 1.0;
            r.update(xf, y).unwrap();
        }
        let c = r.coefficients().unwrap();
        assert!((c[0] - (-1.0)).abs() < 1e-4, "c0 = {}", c[0]);
        assert!((c[1] - 1.0).abs() < 1e-4, "c1 = {}", c[1]);
        assert!((c[2] - (-2.0)).abs() < 1e-4, "c2 = {}", c[2]);
        assert!((c[3] - 0.5).abs() < 1e-4, "c3 = {}", c[3]);
    }

    // =========================================================================
    // Builder
    // =========================================================================

    #[test]
    fn builder_degree_4() {
        let mut r = PolynomialRegressionF64::builder()
            .degree(4)
            .build()
            .unwrap();
        for x in -20..20 {
            let xf = x as f64;
            r.update(xf, xf * xf * xf * xf).unwrap();
        }
        assert!(r.is_primed());
        assert_eq!(r.degree(), 4);
        assert!(r.has_intercept());
    }

    #[test]
    fn builder_no_intercept() {
        let mut r = PolynomialRegressionF64::builder()
            .degree(1)
            .intercept(false)
            .build()
            .unwrap();
        for x in 1..100 {
            r.update(x as f64, 5.0 * x as f64).unwrap();
        }
        let c = r.coefficients().unwrap();
        assert_eq!(c.len(), 1);
        assert!((c[0] - 5.0).abs() < 1e-8, "slope = {}", c[0]);
    }

    #[test]
    fn builder_rejects_degree_0() {
        assert!(
            PolynomialRegressionF64::builder()
                .degree(0)
                .build()
                .is_err()
        );
    }

    #[test]
    fn builder_rejects_degree_9() {
        assert!(
            PolynomialRegressionF64::builder()
                .degree(9)
                .build()
                .is_err()
        );
    }

    #[test]
    fn builder_rejects_missing_degree() {
        assert!(PolynomialRegressionF64::builder().build().is_err());
    }

    // =========================================================================
    //    // =========================================================================

    #[test]
    fn r_squared_perfect() {
        let mut r = quadratic();
        for x in -50..50 {
            let xf = x as f64;
            r.update(xf, xf * xf - 3.0 * xf + 2.0).unwrap();
        }
        let r2 = r.r_squared().unwrap();
        assert!((r2 - 1.0).abs() < 1e-10, "R² = {r2}");
    }

    // =========================================================================
    // Priming / edge cases
    // =========================================================================

    #[test]
    fn quadratic_needs_3_points() {
        let mut r = quadratic();
        r.update(1.0, 1.0).unwrap();
        r.update(2.0, 4.0).unwrap();
        assert!(!r.is_primed());
        r.update(3.0, 9.0).unwrap();
        assert!(r.is_primed());
    }

    // =========================================================================
    // Heterogeneous storage
    // =========================================================================

    #[test]
    fn different_degrees_same_type() {
        let models: [PolynomialRegressionF64; 2] = [
            PolynomialRegressionF64::builder()
                .degree(2)
                .build()
                .unwrap(),
            PolynomialRegressionF64::builder()
                .degree(3)
                .build()
                .unwrap(),
        ];
        assert_eq!(models[0].degree(), 2);
        assert_eq!(models[1].degree(), 3);
    }

    // =========================================================================
    // Reset
    // =========================================================================

    #[test]
    fn reset_clears_state() {
        let mut r = quadratic();
        for x in 0..100 {
            r.update(x as f64, x as f64).unwrap();
        }
        r.reset();
        assert_eq!(r.count(), 0);
        assert!(r.coefficients().is_none());
        assert_eq!(r.degree(), 2);
    }

    // =========================================================================
    // f32 variant
    // =========================================================================

    #[test]
    fn f32_quadratic() {
        let mut r = PolynomialRegressionF32::builder()
            .degree(2)
            .build()
            .unwrap();
        for x in -20..20i32 {
            let xf = x as f32;
            r.update(xf, xf * xf).unwrap();
        }
        assert!(r.coefficients().is_some());
    }

    // =========================================================================
    // Coefficients struct
    // =========================================================================

    #[test]
    fn coefficients_indexing() {
        let mut r = quadratic();
        for x in -10..10 {
            let xf = x as f64;
            r.update(xf, xf * xf).unwrap();
        }
        let c = r.coefficients().unwrap();
        assert_eq!(c.len(), 3);
        assert!(!c.is_empty());
        assert!(c.get(0).is_some());
        assert!(c.get(3).is_none());
        assert_eq!(c.as_slice().len(), 3);
    }

    #[test]
    fn rejects_nan_and_inf() {
        let mut r = quadratic();
        assert_eq!(r.update(f64::NAN, 1.0), Err(crate::DataError::NotANumber));
        assert_eq!(
            r.update(1.0, f64::INFINITY),
            Err(crate::DataError::Infinite)
        );
        assert_eq!(r.count(), 0);
    }
}