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
#![allow(
    clippy::suboptimal_flops,
    clippy::float_cmp,
    clippy::neg_cmp_op_on_partial_ord
)]

macro_rules! impl_beta_binomial {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// Bayesian success rate estimator using the Beta-Binomial conjugate prior.
        ///
        /// Maintains a Beta(alpha, beta) posterior updated by observing binary
        /// outcomes. The posterior mean is a natural shrinkage estimator —
        /// with few observations, it stays near the prior; with many, it
        /// converges to the observed rate.
        ///
        /// # Use Cases
        /// - Fill rate estimation (what fraction of orders fill?)
        /// - Exchange reliability scoring
        /// - A/B testing with early stopping
        /// - Any binary outcome where you want uncertainty quantification
        #[derive(Debug, Clone)]
        pub struct $name {
            alpha: $ty,
            beta: $ty,
            prior_alpha: $ty,
            prior_beta: $ty,
        }

        /// Builder for [`
        #[doc = stringify!($name)]
        /// `].
        #[derive(Debug, Clone)]
        pub struct $builder {
            alpha: $ty,
            beta: $ty,
        }

        impl $name {
            /// Creates a new estimator with a uniform (uninformative) prior.
            ///
            /// Beta(1, 1) is the uniform distribution on [0, 1].
            #[inline]
            #[must_use]
            pub const fn new() -> Self {
                Self {
                    alpha: 1.0 as $ty,
                    beta: 1.0 as $ty,
                    prior_alpha: 1.0 as $ty,
                    prior_beta: 1.0 as $ty,
                }
            }

            /// Creates an estimator with a specified prior.
            ///
            /// Higher alpha biases toward success, higher beta toward failure.
            /// `Beta(10, 1)` expresses strong prior belief in ~91% success rate.
            ///
            /// # Errors
            ///
            /// Both alpha and beta must be positive.
            #[inline]
            pub fn with_prior(alpha: $ty, beta: $ty) -> Result<Self, crate::ConfigError> {
                if !(alpha > 0.0 as $ty) {
                    return Err(crate::ConfigError::Invalid("alpha must be positive"));
                }
                if !(beta > 0.0 as $ty) {
                    return Err(crate::ConfigError::Invalid("beta must be positive"));
                }
                Ok(Self {
                    alpha,
                    beta,
                    prior_alpha: alpha,
                    prior_beta: beta,
                })
            }

            /// Creates a builder with defaults of alpha=1.0, beta=1.0.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    alpha: 1.0 as $ty,
                    beta: 1.0 as $ty,
                }
            }

            /// Updates with a single binary outcome.
            #[inline]
            pub fn update(&mut self, success: bool) {
                if success {
                    self.alpha += 1.0 as $ty;
                } else {
                    self.beta += 1.0 as $ty;
                }
            }

            /// Updates with a batch of outcomes.
            #[inline]
            pub fn update_batch(&mut self, successes: u64, failures: u64) {
                self.alpha += successes as $ty;
                self.beta += failures as $ty;
            }

            /// Posterior mean: the expected success rate.
            ///
            /// This is the Bayes estimator under squared error loss.
            #[inline]
            #[must_use]
            pub fn mean(&self) -> $ty {
                self.alpha / (self.alpha + self.beta)
            }

            /// Posterior variance.
            #[inline]
            #[must_use]
            pub fn variance(&self) -> $ty {
                let sum = self.alpha + self.beta;
                (self.alpha * self.beta) / (sum * sum * (sum + 1.0 as $ty))
            }

            /// Posterior mode, or `None` if alpha <= 1 or beta <= 1.
            ///
            /// The mode is undefined for the uniform prior (1, 1) and
            /// degenerate when either parameter is at or below 1.
            #[inline]
            #[must_use]
            pub fn mode(&self) -> Option<$ty> {
                if self.alpha <= 1.0 as $ty || self.beta <= 1.0 as $ty {
                    Option::None
                } else {
                    Option::Some((self.alpha - 1.0 as $ty) / (self.alpha + self.beta - 2.0 as $ty))
                }
            }

            /// Approximate credible interval using normal approximation.
            ///
            /// Returns `(lower, upper)` bounds for the given confidence level
            /// (e.g., 0.95 for a 95% interval). Uses the Abramowitz & Stegun
            /// rational approximation (26.2.23) for the inverse normal CDF.
            ///
            /// Returns `None` if no observations have been made.
            #[inline]
            #[must_use]
            #[cfg(any(feature = "std", feature = "libm"))]
            pub fn credible_interval(&self, confidence: $ty) -> Option<($ty, $ty)> {
                if self.total() == 0.0 as $ty {
                    return Option::None;
                }
                if !(confidence > 0.0 as $ty && confidence < 1.0 as $ty) {
                    return Option::None;
                }

                let tail = (1.0 as $ty - confidence) / 2.0 as $ty;

                // Abramowitz & Stegun 26.2.23 rational approximation
                #[allow(clippy::cast_possible_truncation)]
                let t = crate::math::sqrt((-2.0 as f64) * crate::math::ln(tail as f64)) as $ty;
                let z = t
                    - (2.515517 as $ty + 0.802853 as $ty * t + 0.010328 as $ty * t * t)
                        / (1.0 as $ty
                            + 1.432788 as $ty * t
                            + 0.189269 as $ty * t * t
                            + 0.001308 as $ty * t * t * t);

                let mean = self.mean();
                #[allow(clippy::cast_possible_truncation)]
                let std_dev = crate::math::sqrt(self.variance() as f64) as $ty;
                let half_width = z * std_dev;

                // Clamp to [0, 1] since we're estimating a probability.
                let lower = if mean - half_width < 0.0 as $ty {
                    0.0 as $ty
                } else {
                    mean - half_width
                };
                let upper = if mean + half_width > 1.0 as $ty {
                    1.0 as $ty
                } else {
                    mean + half_width
                };

                Option::Some((lower, upper))
            }

            /// Number of observed successes (excluding prior).
            #[inline]
            #[must_use]
            pub fn successes(&self) -> $ty {
                self.alpha - self.prior_alpha
            }

            /// Number of observed failures (excluding prior).
            #[inline]
            #[must_use]
            pub fn failures(&self) -> $ty {
                self.beta - self.prior_beta
            }

            /// Total number of observations (excluding prior).
            #[inline]
            #[must_use]
            pub fn total(&self) -> $ty {
                self.successes() + self.failures()
            }

            /// Total observations as an integer.
            #[inline]
            #[must_use]
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            pub fn count(&self) -> u64 {
                self.total() as u64
            }

            /// Whether any observations have been made.
            #[inline]
            #[must_use]
            pub fn is_primed(&self) -> bool {
                self.total() > 0.0 as $ty
            }

            /// Resets to the original prior, discarding all observations.
            #[inline]
            pub fn reset(&mut self) {
                self.alpha = self.prior_alpha;
                self.beta = self.prior_beta;
            }
        }

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

        impl $builder {
            /// Sets the alpha (success) prior parameter.
            #[inline]
            #[must_use]
            pub fn alpha(mut self, alpha: $ty) -> Self {
                self.alpha = alpha;
                self
            }

            /// Sets the beta (failure) prior parameter.
            #[inline]
            #[must_use]
            pub fn beta(mut self, beta: $ty) -> Self {
                self.beta = beta;
                self
            }

            /// Builds the estimator.
            ///
            /// # Errors
            ///
            /// Both alpha and beta must be positive.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                if !(self.alpha > 0.0 as $ty) {
                    return Err(crate::ConfigError::Invalid("alpha must be positive"));
                }
                if !(self.beta > 0.0 as $ty) {
                    return Err(crate::ConfigError::Invalid("beta must be positive"));
                }
                Ok($name {
                    alpha: self.alpha,
                    beta: self.beta,
                    prior_alpha: self.alpha,
                    prior_beta: self.beta,
                })
            }
        }
    };
}

impl_beta_binomial!(BetaBinomialF64, BetaBinomialF64Builder, f64);
impl_beta_binomial!(BetaBinomialF32, BetaBinomialF32Builder, f32);

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

    #[test]
    fn uniform_prior_balanced_observations() {
        let mut bb = BetaBinomialF64::new();
        for _ in 0..50 {
            bb.update(true);
            bb.update(false);
        }
        // Beta(51, 51) → mean = 0.5
        let mean = bb.mean();
        assert!((mean - 0.5).abs() < 0.01, "expected ~0.5, got {mean}");
    }

    #[test]
    fn informative_prior() {
        let bb = BetaBinomialF64::with_prior(10.0, 1.0).unwrap();
        // Beta(10, 1) → mean = 10/11 ≈ 0.909
        let mean = bb.mean();
        assert!(
            (mean - 10.0 / 11.0).abs() < 1e-10,
            "expected ~0.909, got {mean}"
        );
    }

    #[test]
    fn variance_decreases_with_observations() {
        let mut bb = BetaBinomialF64::new();
        let initial_var = bb.variance();

        for _ in 0..100 {
            bb.update(true);
        }
        let final_var = bb.variance();
        assert!(
            final_var < initial_var,
            "variance should decrease: {initial_var} → {final_var}"
        );
    }

    #[test]
    fn mode_none_for_uniform_prior() {
        let bb = BetaBinomialF64::new();
        assert!(bb.mode().is_none(), "mode undefined for Beta(1, 1)");
    }

    #[test]
    fn mode_some_for_informative_prior() {
        let bb = BetaBinomialF64::with_prior(10.0, 10.0).unwrap();
        // Beta(10, 10) → mode = 9/18 = 0.5
        let mode = bb.mode().unwrap();
        assert!((mode - 0.5).abs() < 1e-10, "expected 0.5, got {mode}");
    }

    #[cfg(any(feature = "std", feature = "libm"))]
    #[test]
    fn credible_interval_narrows() {
        let mut bb = BetaBinomialF64::with_prior(2.0, 2.0).unwrap();
        for _ in 0..10 {
            bb.update(true);
            bb.update(false);
        }
        let (lo1, hi1) = bb.credible_interval(0.95).unwrap();
        let width1 = hi1 - lo1;

        for _ in 0..200 {
            bb.update(true);
            bb.update(false);
        }
        let (lo2, hi2) = bb.credible_interval(0.95).unwrap();
        let width2 = hi2 - lo2;

        assert!(
            width2 < width1,
            "interval should narrow: {width1:.4} → {width2:.4}"
        );
    }

    #[test]
    fn observe_batch_equivalence() {
        let mut single = BetaBinomialF64::new();
        for _ in 0..30 {
            single.update(true);
        }
        for _ in 0..20 {
            single.update(false);
        }

        let mut batch = BetaBinomialF64::new();
        batch.update_batch(30, 20);

        assert!(
            (single.mean() - batch.mean()).abs() < 1e-10,
            "single={} batch={}",
            single.mean(),
            batch.mean()
        );
        assert_eq!(single.count(), batch.count());
    }

    #[test]
    fn reset_restores_prior() {
        let mut bb = BetaBinomialF64::with_prior(5.0, 3.0).unwrap();
        let mean_before = bb.mean();

        for _ in 0..100 {
            bb.update(true);
        }
        bb.reset();

        assert!(
            (bb.mean() - mean_before).abs() < 1e-10,
            "reset should restore prior mean"
        );
        assert_eq!(bb.count(), 0);
        assert!(!bb.is_primed());
    }

    #[test]
    fn f32_variant() {
        let mut bb = BetaBinomialF32::new();
        bb.update(true);
        bb.update(false);
        // Beta(2, 2) → mean = 0.5
        let mean = bb.mean();
        assert!((mean - 0.5).abs() < 1e-5, "expected ~0.5, got {mean}");
    }

    #[test]
    fn default_is_new() {
        let a = BetaBinomialF64::new();
        let b = BetaBinomialF64::default();
        assert!(
            (a.mean() - b.mean()).abs() < 1e-10,
            "default and new should be identical"
        );
    }

    #[test]
    fn with_prior_validation() {
        assert!(BetaBinomialF64::with_prior(0.0, 1.0).is_err());
        assert!(BetaBinomialF64::with_prior(1.0, 0.0).is_err());
        assert!(BetaBinomialF64::with_prior(-1.0, 1.0).is_err());
        assert!(BetaBinomialF64::with_prior(1.0, -1.0).is_err());
        assert!(BetaBinomialF64::with_prior(0.5, 0.5).is_ok());
    }
}