nexus-stats-detection 1.2.0

Advanced change detection and signal analysis for nexus-stats
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
extern crate alloc;
use alloc::boxed::Box;
use alloc::vec;
use nexus_stats_core::DataError;

macro_rules! impl_predictive_info {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// Streaming mutual information estimator via binned MI.
        ///
        /// Estimates I(X; Y) from joint and marginal frequency counts
        /// over equi-width bins. Miller-Madow bias correction adjusts
        /// for finite-sample underestimation.
        ///
        /// O(K²) per query (K = bin count). O(1) per update.
        ///
        /// # Parameters
        ///
        /// - `bins` — number of bins per dimension (total cells = bins²)
        /// - `x_range` — `(min, max)` for the X variable
        /// - `y_range` — `(min, max)` for the Y variable
        ///
        /// # Examples
        ///
        /// ```
        /// use nexus_stats_detection::signal::PredictiveInfoBoundF64;
        ///
        /// let mut pib = PredictiveInfoBoundF64::builder()
        ///     .bins(10)
        ///     .x_range(0.0, 100.0)
        ///     .y_range(0.0, 100.0)
        ///     .build()
        ///     .unwrap();
        ///
        /// // Feed identical values → high MI
        /// for i in 0..1000 {
        ///     let x = (i % 100) as f64;
        ///     pib.update(x, x).unwrap();
        /// }
        /// assert!(pib.mutual_information().unwrap() > 0.0);
        /// ```
        #[derive(Debug, Clone)]
        pub struct $name {
            bins: usize,
            x_min: $ty,
            x_max: $ty,
            y_min: $ty,
            y_max: $ty,
            x_width: $ty,
            y_width: $ty,
            joint: Box<[u64]>,
            marginal_x: Box<[u64]>,
            marginal_y: Box<[u64]>,
            count: u64,
            min_samples: u64,
        }

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

        impl $name {
            /// Creates a builder.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    bins: Option::None,
                    x_range: Option::None,
                    y_range: Option::None,
                    min_samples: Option::None,
                }
            }

            /// Feeds an (x, y) observation.
            ///
            /// Values outside the configured range are clamped to the
            /// nearest bin (first or last).
            ///
            /// # 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<(), DataError> {
                check_finite!(x);
                check_finite!(y);

                let xi = self.bin_x(x);
                let yi = self.bin_y(y);

                self.joint[xi * self.bins + yi] += 1;
                self.marginal_x[xi] += 1;
                self.marginal_y[yi] += 1;
                self.count += 1;
                Ok(())
            }

            /// Mutual information I(X; Y) in nats, with Miller-Madow correction.
            ///
            /// Returns `None` if not primed.
            #[must_use]
            pub fn mutual_information(&self) -> Option<$ty> {
                if !self.is_primed() {
                    return Option::None;
                }
                let n = self.count as $ty;

                let mut mi = 0.0 as $ty;
                for xi in 0..self.bins {
                    let nx = self.marginal_x[xi];
                    if nx == 0 {
                        continue;
                    }
                    for yi in 0..self.bins {
                        let ny = self.marginal_y[yi];
                        let nxy = self.joint[xi * self.bins + yi];
                        if nxy == 0 || ny == 0 {
                            continue;
                        }
                        let p_xy = nxy as $ty / n;
                        let p_x = nx as $ty / n;
                        let p_y = ny as $ty / n;
                        #[allow(clippy::cast_possible_truncation)]
                        {
                            mi += p_xy
                                * nexus_stats_core::math::ln((p_xy / (p_x * p_y)) as f64) as $ty;
                        }
                    }
                }

                let occupied = self.count_occupied_cells() as $ty;
                let correction = (occupied - 1.0 as $ty) / (2.0 as $ty * n);
                Option::Some(mi + correction)
            }

            /// Mutual information in bits (log base 2).
            ///
            /// Returns `None` if not primed.
            #[inline]
            #[must_use]
            pub fn mutual_information_bits(&self) -> Option<$ty> {
                #[allow(clippy::cast_possible_truncation)]
                self.mutual_information()
                    .map(|mi| mi / nexus_stats_core::math::ln(2.0) as $ty)
            }

            /// Normalized MI: I(X;Y) / min(H(X), H(Y)). Range [0, 1].
            ///
            /// Returns `None` if not primed or if either marginal entropy is zero.
            #[must_use]
            pub fn normalized_mi(&self) -> Option<$ty> {
                let mi = self.mutual_information()?;
                let hx = self.marginal_entropy_x()?;
                let hy = self.marginal_entropy_y()?;
                let min_h = if hx < hy { hx } else { hy };
                if min_h <= 0.0 as $ty {
                    return Option::None;
                }
                let nmi = mi / min_h;
                let clamped = if nmi < 0.0 as $ty {
                    0.0 as $ty
                } else if nmi > 1.0 as $ty {
                    1.0 as $ty
                } else {
                    nmi
                };
                Option::Some(clamped)
            }

            fn marginal_entropy_x(&self) -> Option<$ty> {
                if self.count == 0 {
                    return Option::None;
                }
                let n = self.count as $ty;
                let mut h = 0.0 as $ty;
                for xi in 0..self.bins {
                    let c = self.marginal_x[xi];
                    if c > 0 {
                        let p = c as $ty / n;
                        #[allow(clippy::cast_possible_truncation)]
                        {
                            h -= p * nexus_stats_core::math::ln(p as f64) as $ty;
                        }
                    }
                }
                Option::Some(h)
            }

            fn marginal_entropy_y(&self) -> Option<$ty> {
                if self.count == 0 {
                    return Option::None;
                }
                let n = self.count as $ty;
                let mut h = 0.0 as $ty;
                for yi in 0..self.bins {
                    let c = self.marginal_y[yi];
                    if c > 0 {
                        let p = c as $ty / n;
                        #[allow(clippy::cast_possible_truncation)]
                        {
                            h -= p * nexus_stats_core::math::ln(p as f64) as $ty;
                        }
                    }
                }
                Option::Some(h)
            }

            fn count_occupied_cells(&self) -> u64 {
                self.joint.iter().filter(|&&c| c > 0).count() as u64
            }

            fn bin_x(&self, x: $ty) -> usize {
                let clamped = if x < self.x_min {
                    self.x_min
                } else if x > self.x_max {
                    self.x_max
                } else {
                    x
                };
                let idx = ((clamped - self.x_min) / self.x_width) as usize;
                if idx >= self.bins { self.bins - 1 } else { idx }
            }

            fn bin_y(&self, y: $ty) -> usize {
                let clamped = if y < self.y_min {
                    self.y_min
                } else if y > self.y_max {
                    self.y_max
                } else {
                    y
                };
                let idx = ((clamped - self.y_min) / self.y_width) as usize;
                if idx >= self.bins { self.bins - 1 } else { idx }
            }

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

            /// Whether enough samples have been observed.
            #[inline]
            #[must_use]
            pub fn is_primed(&self) -> bool {
                self.count >= self.min_samples
            }

            /// Resets counts. Configuration and allocation preserved.
            #[inline]
            pub fn reset(&mut self) {
                self.joint.fill(0);
                self.marginal_x.fill(0);
                self.marginal_y.fill(0);
                self.count = 0;
            }
        }

        impl $builder {
            /// Number of bins per dimension (required, 2..=256).
            #[inline]
            #[must_use]
            pub fn bins(mut self, bins: usize) -> Self {
                self.bins = Option::Some(bins);
                self
            }

            /// Range for the X variable (required, max > min).
            #[inline]
            #[must_use]
            pub fn x_range(mut self, min: $ty, max: $ty) -> Self {
                self.x_range = Option::Some((min, max));
                self
            }

            /// Range for the Y variable (required, max > min).
            #[inline]
            #[must_use]
            pub fn y_range(mut self, min: $ty, max: $ty) -> Self {
                self.y_range = Option::Some((min, max));
                self
            }

            /// Minimum samples before MI is valid. Default: bins².
            #[inline]
            #[must_use]
            pub fn min_samples(mut self, min: u64) -> Self {
                self.min_samples = Option::Some(min);
                self
            }

            /// Builds the mutual information estimator.
            ///
            /// # Errors
            ///
            /// - `bins` must be in [2, 256].
            /// - `x_range` and `y_range` must have `max > min`, both finite.
            pub fn build(self) -> Result<$name, nexus_stats_core::ConfigError> {
                let bins = self
                    .bins
                    .ok_or(nexus_stats_core::ConfigError::Missing("bins"))?;
                if bins < 2 {
                    return Err(nexus_stats_core::ConfigError::Invalid(
                        "PredictiveInfoBound bins must be >= 2",
                    ));
                }
                if bins > 256 {
                    return Err(nexus_stats_core::ConfigError::Invalid(
                        "PredictiveInfoBound bins must be <= 256",
                    ));
                }

                let (x_min, x_max) = self
                    .x_range
                    .ok_or(nexus_stats_core::ConfigError::Missing("x_range"))?;
                if x_max <= x_min || !x_min.is_finite() || !x_max.is_finite() {
                    return Err(nexus_stats_core::ConfigError::Invalid(
                        "x_range must have max > min, both finite",
                    ));
                }

                let (y_min, y_max) = self
                    .y_range
                    .ok_or(nexus_stats_core::ConfigError::Missing("y_range"))?;
                if y_max <= y_min || !y_min.is_finite() || !y_max.is_finite() {
                    return Err(nexus_stats_core::ConfigError::Invalid(
                        "y_range must have max > min, both finite",
                    ));
                }

                let x_width = (x_max - x_min) / bins as $ty;
                let y_width = (y_max - y_min) / bins as $ty;
                let min_samples = self.min_samples.unwrap_or((bins * bins) as u64);
                if min_samples < 1 {
                    return Err(nexus_stats_core::ConfigError::Invalid(
                        "PredictiveInfoBound min_samples must be >= 1",
                    ));
                }

                Ok($name {
                    bins,
                    x_min,
                    x_max,
                    y_min,
                    y_max,
                    x_width,
                    y_width,
                    joint: vec![0u64; bins * bins].into_boxed_slice(),
                    marginal_x: vec![0u64; bins].into_boxed_slice(),
                    marginal_y: vec![0u64; bins].into_boxed_slice(),
                    count: 0,
                    min_samples,
                })
            }
        }
    };
}

impl_predictive_info!(PredictiveInfoBoundF64, PredictiveInfoBoundF64Builder, f64);
impl_predictive_info!(PredictiveInfoBoundF32, PredictiveInfoBoundF32Builder, f32);

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

    #[test]
    fn independent_variables() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(10)
            .x_range(0.0, 10.0)
            .y_range(0.0, 10.0)
            .min_samples(10)
            .build()
            .unwrap();

        // X cycles 0..10 sequentially, Y uses a co-prime stride that
        // produces a uniform marginal over bins, independent of X.
        // With 10 bins and stride 7 (coprime to 10), every (x,y) cell
        // is hit equally over a full 100-step cycle.
        for i in 0..10_000u64 {
            let x = (i % 10) as f64 + 0.5;
            let y = ((i / 10) % 10) as f64 + 0.5;
            pib.update(x, y).unwrap();
        }

        let mi = pib.mutual_information().unwrap();
        assert!(
            mi.abs() < 0.1,
            "independent variables should have MI ≈ 0, got {mi}"
        );
    }

    #[test]
    fn identical_variables() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(10)
            .x_range(0.0, 10.0)
            .y_range(0.0, 10.0)
            .min_samples(10)
            .build()
            .unwrap();

        for i in 0..1000 {
            let x = (i % 10) as f64 + 0.5;
            pib.update(x, x).unwrap();
        }

        let mi = pib.mutual_information().unwrap();
        let hx = pib.marginal_entropy_x().unwrap();
        assert!(
            (mi - hx).abs() < 0.2,
            "identical variables: MI ({mi}) should ≈ H(X) ({hx})"
        );
    }

    #[test]
    fn linear_relationship() {
        let mut pib_tight = PredictiveInfoBoundF64::builder()
            .bins(10)
            .x_range(0.0, 10.0)
            .y_range(0.0, 20.0)
            .min_samples(10)
            .build()
            .unwrap();

        for i in 0..1000 {
            let x = (i % 10) as f64 + 0.5;
            let y = 2.0 * x;
            pib_tight.update(x, y).unwrap();
        }

        let mi_tight = pib_tight.mutual_information().unwrap();
        assert!(
            mi_tight > 0.5,
            "tight linear relationship should have high MI, got {mi_tight}"
        );
    }

    #[test]
    fn clamping() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(5)
            .x_range(0.0, 10.0)
            .y_range(0.0, 10.0)
            .min_samples(2)
            .build()
            .unwrap();

        pib.update(-5.0, 15.0).unwrap();
        pib.update(100.0, -100.0).unwrap();
        assert_eq!(pib.count(), 2);
    }

    #[test]
    fn miller_madow_correction() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(4)
            .x_range(0.0, 4.0)
            .y_range(0.0, 4.0)
            .min_samples(2)
            .build()
            .unwrap();

        for i in 0..20 {
            let x = (i % 4) as f64 + 0.5;
            pib.update(x, x).unwrap();
        }

        let mi = pib.mutual_information().unwrap();
        assert!(mi > 0.0, "MI with correction should be positive, got {mi}");
    }

    #[test]
    fn bits_vs_nats() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(5)
            .x_range(0.0, 5.0)
            .y_range(0.0, 5.0)
            .min_samples(5)
            .build()
            .unwrap();

        for i in 0..500 {
            let x = (i % 5) as f64 + 0.5;
            pib.update(x, x).unwrap();
        }

        let nats = pib.mutual_information().unwrap();
        let bits = pib.mutual_information_bits().unwrap();
        let ratio = bits / nats;
        let expected_ratio = 1.0 / (2.0_f64).ln();
        assert!(
            (ratio - expected_ratio).abs() < 0.01,
            "bits/nats ratio should be 1/ln(2), got {ratio}"
        );
    }

    #[test]
    fn normalized_mi_range() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(5)
            .x_range(0.0, 5.0)
            .y_range(0.0, 5.0)
            .min_samples(5)
            .build()
            .unwrap();

        for i in 0..500 {
            let x = (i % 5) as f64 + 0.5;
            pib.update(x, x).unwrap();
        }

        let nmi = pib.normalized_mi().unwrap();
        assert!(
            (0.0..=1.0).contains(&nmi),
            "normalized MI should be in [0, 1], got {nmi}"
        );
    }

    #[test]
    fn reset_clears() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(5)
            .x_range(0.0, 5.0)
            .y_range(0.0, 5.0)
            .min_samples(5)
            .build()
            .unwrap();

        for i in 0..100 {
            let x = (i % 5) as f64 + 0.5;
            pib.update(x, x).unwrap();
        }

        pib.reset();
        assert_eq!(pib.count(), 0);
        assert!(pib.mutual_information().is_none());
    }

    #[test]
    fn nan_rejected() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(5)
            .x_range(0.0, 5.0)
            .y_range(0.0, 5.0)
            .build()
            .unwrap();
        assert!(matches!(
            pib.update(f64::NAN, 1.0),
            Err(DataError::NotANumber)
        ));
        assert!(matches!(
            pib.update(1.0, f64::NAN),
            Err(DataError::NotANumber)
        ));
    }

    #[test]
    fn inf_rejected() {
        let mut pib = PredictiveInfoBoundF64::builder()
            .bins(5)
            .x_range(0.0, 5.0)
            .y_range(0.0, 5.0)
            .build()
            .unwrap();
        assert!(matches!(
            pib.update(f64::INFINITY, 1.0),
            Err(DataError::Infinite)
        ));
    }

    #[test]
    fn builder_validation() {
        assert!(matches!(
            PredictiveInfoBoundF64::builder()
                .x_range(0.0, 10.0)
                .y_range(0.0, 10.0)
                .build(),
            Err(nexus_stats_core::ConfigError::Missing("bins"))
        ));

        assert!(matches!(
            PredictiveInfoBoundF64::builder()
                .bins(1)
                .x_range(0.0, 10.0)
                .y_range(0.0, 10.0)
                .build(),
            Err(nexus_stats_core::ConfigError::Invalid(_))
        ));

        assert!(matches!(
            PredictiveInfoBoundF64::builder()
                .bins(257)
                .x_range(0.0, 10.0)
                .y_range(0.0, 10.0)
                .build(),
            Err(nexus_stats_core::ConfigError::Invalid(_))
        ));

        assert!(matches!(
            PredictiveInfoBoundF64::builder()
                .bins(10)
                .x_range(10.0, 0.0)
                .y_range(0.0, 10.0)
                .build(),
            Err(nexus_stats_core::ConfigError::Invalid(_))
        ));

        assert!(matches!(
            PredictiveInfoBoundF64::builder()
                .bins(10)
                .x_range(0.0, 10.0)
                .y_range(10.0, 0.0)
                .build(),
            Err(nexus_stats_core::ConfigError::Invalid(_))
        ));
    }
}