nexus-stats 2.1.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
use crate::math::MulAdd;
macro_rules! impl_welford {
    ($name:ident, $ty:ty) => {
        /// Welford — Online mean, variance, and standard deviation.
        ///
        /// Numerically stable single-pass computation using Welford's algorithm.
        /// No catastrophic cancellation. Supports merging partial results via
        /// Chan's algorithm for parallel aggregation.
        ///
        /// # Use Cases
        /// - Running statistics on latency, throughput, PnL
        /// - Z-score computation (combine with EMA for baseline)
        /// - Input to adaptive thresholds
        #[derive(Debug, Clone)]
        pub struct $name {
            count: u64,
            mean: $ty,
            m2: $ty,
        }

        impl $name {
            /// Creates a new empty accumulator.
            #[inline]
            #[must_use]
            pub const fn new() -> Self {
                Self {
                    count: 0,
                    mean: 0.0 as $ty,
                    m2: 0.0 as $ty,
                }
            }

            /// Creates an accumulator pre-loaded from known statistics.
            ///
            /// `m2` is the sum of squared deviations from the mean
            /// (`variance * (count - 1)` for sample variance).
            #[inline]
            #[must_use]
            pub const fn from_parts(count: u64, mean: $ty, m2: $ty) -> Self {
                Self { count, mean, m2 }
            }

            /// Feeds a sample.
            #[inline]
            pub fn update(&mut self, sample: $ty) {
                self.count += 1;
                let delta = sample - self.mean;
                self.mean += delta / self.count as $ty;
                let delta2 = sample - self.mean;
                self.m2 += delta * delta2;
            }

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

            /// Running mean, or `None` if empty.
            #[inline]
            #[must_use]
            pub fn mean(&self) -> Option<$ty> {
                if self.count == 0 {
                    Option::None
                } else {
                    Option::Some(self.mean)
                }
            }

            /// Sample variance (N-1 denominator), or `None` if < 2 samples.
            #[inline]
            #[must_use]
            pub fn variance(&self) -> Option<$ty> {
                if self.count < 2 {
                    Option::None
                } else {
                    Option::Some(self.m2 / (self.count - 1) as $ty)
                }
            }

            /// Population variance (N denominator), or `None` if empty.
            #[inline]
            #[must_use]
            pub fn population_variance(&self) -> Option<$ty> {
                if self.count == 0 {
                    Option::None
                } else {
                    Option::Some(self.m2 / self.count as $ty)
                }
            }

            /// Sample standard deviation, or `None` if < 2 samples.
            #[inline]
            #[must_use]
            #[cfg(any(feature = "std", feature = "libm"))]
            pub fn std_dev(&self) -> Option<$ty> {
                self.variance().map(|v| {
                    #[allow(clippy::cast_possible_truncation)]
                    {
                        crate::math::sqrt(v as f64) as $ty
                    }
                })
            }

            /// Merges another accumulator into this one (Chan's algorithm).
            ///
            /// After merging, `self` contains the statistics of the combined
            /// dataset. The other accumulator is unchanged.
            #[inline]
            pub fn merge(&mut self, other: &Self) {
                if other.count == 0 {
                    return;
                }
                if self.count == 0 {
                    self.count = other.count;
                    self.mean = other.mean;
                    self.m2 = other.m2;
                    return;
                }

                let combined_count = self.count + other.count;
                let delta = other.mean - self.mean;
                let weight = other.count as $ty / combined_count as $ty;
                let new_mean = delta.fma(weight, self.mean);
                let cross = self.count as $ty * other.count as $ty / combined_count as $ty;
                let new_m2 = delta.fma(delta * cross, self.m2 + other.m2);

                self.count = combined_count;
                self.mean = new_mean;
                self.m2 = new_m2;
            }

            /// Resets to empty state.
            #[inline]
            pub fn reset(&mut self) {
                self.count = 0;
                self.mean = 0.0 as $ty;
                self.m2 = 0.0 as $ty;
            }
        }

        impl Default for $name {
            #[inline]
            fn default() -> Self {
                Self::new()
            }
        }
    };
}

impl_welford!(WelfordF64, f64);
impl_welford!(WelfordF32, f32);

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

    // =========================================================================
    // Basic correctness
    // =========================================================================

    #[test]
    fn empty_returns_none() {
        let w = WelfordF64::new();
        assert_eq!(w.count(), 0);
        assert!(w.mean().is_none());
        assert!(w.variance().is_none());
        assert!(w.population_variance().is_none());
        assert!(w.std_dev().is_none());
    }

    #[test]
    fn single_sample() {
        let mut w = WelfordF64::new();
        w.update(42.0);

        assert_eq!(w.count(), 1);
        assert_eq!(w.mean(), Some(42.0));
        // Variance needs at least 2 samples
        assert!(w.variance().is_none());
        // Population variance with 1 sample is 0
        assert_eq!(w.population_variance(), Some(0.0));
    }

    #[test]
    fn known_values() {
        let mut w = WelfordF64::new();

        // Dataset: [2, 4, 4, 4, 5, 5, 7, 9]
        for &x in &[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0] {
            w.update(x);
        }

        assert_eq!(w.count(), 8);

        // Mean = 40/8 = 5.0
        let mean = w.mean().unwrap();
        assert!((mean - 5.0).abs() < 1e-10, "mean should be 5.0, got {mean}");

        // Population variance = 4.0
        let pop_var = w.population_variance().unwrap();
        assert!(
            (pop_var - 4.0).abs() < 1e-10,
            "pop variance should be 4.0, got {pop_var}"
        );

        // Sample variance = 32/7 ≈ 4.571428
        let var = w.variance().unwrap();
        assert!(
            (var - 32.0 / 7.0).abs() < 1e-10,
            "sample variance should be 32/7, got {var}"
        );

        // Std dev = sqrt(32/7) ≈ 2.138
        let sd = w.std_dev().unwrap();
        assert!(
            (sd - (32.0_f64 / 7.0).sqrt()).abs() < 1e-6,
            "std dev got {sd}"
        );
    }

    #[test]
    fn two_samples() {
        let mut w = WelfordF64::new();
        w.update(10.0);
        w.update(20.0);

        assert_eq!(w.count(), 2);
        assert!((w.mean().unwrap() - 15.0).abs() < 1e-10);
        // Sample variance of [10, 20] = 50.0
        assert!((w.variance().unwrap() - 50.0).abs() < 1e-10);
        // Pop variance = 25.0
        assert!((w.population_variance().unwrap() - 25.0).abs() < 1e-10);
    }

    // =========================================================================
    // Numerical stability
    // =========================================================================

    #[test]
    fn numerical_stability_large_offset() {
        // Classic failure case for naive variance: large mean, small deltas
        let mut w = WelfordF64::new();
        let base = 1e8;

        for i in 0..1000 {
            w.update((i as f64).fma(0.001, base));
        }

        let var = w.variance().unwrap();
        // Variance of 0, 0.001, 0.002, ..., 0.999 ≈ 0.08341...
        // (doesn't matter exactly — just check it's positive and reasonable)
        assert!(var > 0.0, "variance should be positive, got {var}");
        assert!(var < 1.0, "variance should be small, got {var}");
    }

    // =========================================================================
    // Merge (Chan's algorithm)
    // =========================================================================

    #[test]
    fn merge_empty_into_empty() {
        let mut a = WelfordF64::new();
        let b = WelfordF64::new();
        a.merge(&b);
        assert_eq!(a.count(), 0);
        assert!(a.mean().is_none());
    }

    #[test]
    fn merge_into_empty() {
        let mut a = WelfordF64::new();
        let mut b = WelfordF64::new();
        b.update(10.0);
        b.update(20.0);

        a.merge(&b);
        assert_eq!(a.count(), 2);
        assert!((a.mean().unwrap() - 15.0).abs() < 1e-10);
    }

    #[test]
    fn merge_empty_into_existing() {
        let mut a = WelfordF64::new();
        a.update(10.0);
        a.update(20.0);
        let b = WelfordF64::new();

        a.merge(&b);
        assert_eq!(a.count(), 2);
        assert!((a.mean().unwrap() - 15.0).abs() < 1e-10);
    }

    #[test]
    fn merge_matches_single_accumulator() {
        let data = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];

        // Single accumulator
        let mut single = WelfordF64::new();
        for &x in &data {
            single.update(x);
        }

        // Split into two halves and merge
        let mut first = WelfordF64::new();
        let mut second = WelfordF64::new();
        for &x in &data[..4] {
            first.update(x);
        }
        for &x in &data[4..] {
            second.update(x);
        }
        first.merge(&second);

        assert_eq!(first.count(), single.count());
        assert!((first.mean().unwrap() - single.mean().unwrap()).abs() < 1e-10);
        assert!((first.variance().unwrap() - single.variance().unwrap()).abs() < 1e-10);
    }

    #[test]
    fn merge_uneven_split() {
        let mut single = WelfordF64::new();
        let mut a = WelfordF64::new();
        let mut b = WelfordF64::new();

        for i in 0..100 {
            let x = i as f64;
            single.update(x);
            if i < 7 {
                a.update(x);
            } else {
                b.update(x);
            }
        }
        a.merge(&b);

        assert_eq!(a.count(), 100);
        assert!((a.mean().unwrap() - single.mean().unwrap()).abs() < 1e-10);
        assert!((a.variance().unwrap() - single.variance().unwrap()).abs() < 1e-6);
    }

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

    #[test]
    fn reset_clears_state() {
        let mut w = WelfordF64::new();
        for i in 0..100 {
            w.update(i as f64);
        }

        w.reset();
        assert_eq!(w.count(), 0);
        assert!(w.mean().is_none());
        assert!(w.variance().is_none());
    }

    // =========================================================================
    // Default
    // =========================================================================

    #[test]
    fn default_is_empty() {
        let w = WelfordF64::default();
        assert_eq!(w.count(), 0);
    }

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

    // =========================================================================
    // from_parts
    // =========================================================================

    #[test]
    fn from_parts_round_trip() {
        let mut w = WelfordF64::new();
        for &x in &[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0] {
            w.update(x);
        }

        let count = w.count();
        let mean = w.mean().unwrap();
        // m2 = variance * (count - 1)
        let m2 = w.variance().unwrap() * (count - 1) as f64;

        let w2 = WelfordF64::from_parts(count, mean, m2);
        assert_eq!(w2.count(), count);
        assert!((w2.mean().unwrap() - mean).abs() < 1e-10);
        assert!((w2.variance().unwrap() - w.variance().unwrap()).abs() < 1e-10);
    }

    #[test]
    fn f32_basic() {
        let mut w = WelfordF32::new();
        w.update(10.0);
        w.update(20.0);

        assert_eq!(w.count(), 2);
        assert!((w.mean().unwrap() - 15.0).abs() < 1e-5);
    }

    #[test]
    fn f32_default() {
        let w = WelfordF32::default();
        assert_eq!(w.count(), 0);
    }
}