alice-analytics 0.3.0

High-performance telemetry & probabilistic statistical estimation — HyperLogLog++, DDSketch, Count-Min Sketch, local differential privacy, streaming anomaly detection
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
//! Streaming Anomaly Detection
//!
//! Real-time outlier detection using robust statistics.
//! Designed for telemetry streams where batch processing is not feasible.

use crate::math::u64_f64;
#[cfg(not(feature = "std"))]
use crate::math::FloatExt;

// ============================================================================
// Streaming Median (for MAD calculation)
// ============================================================================

/// Default window size for streaming algorithms
pub const DEFAULT_WINDOW: usize = 100;

/// Streaming median using Sorted Rolling Window algorithm
///
/// Maintains a sorted array that is incrementally updated with O(N) memmove
/// operations instead of O(N log N) sorting on each access.
///
/// - `push()`: O(N) - binary search + memmove
/// - `median()`: O(1) - direct array access
#[derive(Clone, Debug)]
pub struct StreamingMedian {
    /// Circular buffer of recent values (insertion order)
    buffer: [f64; DEFAULT_WINDOW],
    /// Sorted array maintained incrementally
    sorted: [f64; DEFAULT_WINDOW],
    /// Current write position in circular buffer
    pos: usize,
    /// Number of values seen (saturates at window size)
    count: usize,
}

impl StreamingMedian {
    /// Window size
    pub const WINDOW: usize = DEFAULT_WINDOW;

    /// Create a new streaming median estimator
    #[must_use]
    pub const fn new() -> Self {
        Self {
            buffer: [0.0; DEFAULT_WINDOW],
            sorted: [0.0; DEFAULT_WINDOW],
            pos: 0,
            count: 0,
        }
    }

    /// Binary search for insertion point in sorted array
    #[inline]
    fn binary_search_insert(&self, value: f64, len: usize) -> usize {
        let mut left = 0;
        let mut right = len;
        while left < right {
            let mid = left + (right - left) / 2;
            if self.sorted[mid] < value {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        left
    }

    /// Binary search for removal point (finds exact match)
    #[inline]
    fn binary_search_remove(&self, value: f64, len: usize) -> Option<usize> {
        let mut left = 0;
        let mut right = len;
        while left < right {
            let mid = left + (right - left) / 2;
            if self.sorted[mid] < value {
                left = mid + 1;
            } else if self.sorted[mid] > value {
                right = mid;
            } else {
                return Some(mid);
            }
        }
        // Handle floating point equality - search nearby
        if left < len && (self.sorted[left] - value).abs() < f64::EPSILON {
            return Some(left);
        }
        if left > 0 && (self.sorted[left - 1] - value).abs() < f64::EPSILON {
            return Some(left - 1);
        }
        None
    }

    /// Add a new value with O(N) sorted array maintenance
    #[inline]
    pub fn push(&mut self, value: f64) {
        if self.count < DEFAULT_WINDOW {
            // Buffer not full: just insert into sorted array
            let insert_pos = self.binary_search_insert(value, self.count);

            // Shift elements right to make room (memmove)
            if insert_pos < self.count {
                self.sorted
                    .copy_within(insert_pos..self.count, insert_pos + 1);
            }
            self.sorted[insert_pos] = value;

            self.buffer[self.pos] = value;
            self.pos = (self.pos + 1) % DEFAULT_WINDOW;
            self.count += 1;
        } else {
            // Buffer full: remove old value, insert new value
            let old_value = self.buffer[self.pos];

            // Remove old value from sorted array
            if let Some(remove_pos) = self.binary_search_remove(old_value, self.count) {
                // Shift elements left (memmove)
                if remove_pos < self.count - 1 {
                    self.sorted
                        .copy_within(remove_pos + 1..self.count, remove_pos);
                }
            }

            // Insert new value into sorted array
            let insert_pos = self.binary_search_insert(value, self.count - 1);

            // Shift elements right to make room (memmove)
            if insert_pos < self.count - 1 {
                self.sorted
                    .copy_within(insert_pos..self.count - 1, insert_pos + 1);
            }
            self.sorted[insert_pos] = value;

            // Update circular buffer
            self.buffer[self.pos] = value;
            self.pos = (self.pos + 1) % DEFAULT_WINDOW;
        }
    }

    /// Get the current median estimate - O(1)
    #[inline]
    pub fn median(&mut self) -> f64 {
        if self.count == 0 {
            return 0.0;
        }

        let mid = self.count / 2;
        if self.count.is_multiple_of(2) {
            f64::midpoint(self.sorted[mid - 1], self.sorted[mid])
        } else {
            self.sorted[mid]
        }
    }

    /// Get count of values
    #[inline]
    #[must_use]
    pub const fn count(&self) -> usize {
        self.count
    }

    /// Check if buffer is full
    #[inline]
    #[must_use]
    pub const fn is_full(&self) -> bool {
        self.count >= DEFAULT_WINDOW
    }

    /// Clear the buffer
    pub const fn clear(&mut self) {
        self.buffer = [0.0; DEFAULT_WINDOW];
        self.sorted = [0.0; DEFAULT_WINDOW];
        self.pos = 0;
        self.count = 0;
    }
}

impl Default for StreamingMedian {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// MAD (Median Absolute Deviation) Detector
// ============================================================================

/// MAD-based anomaly detector
///
/// Uses Median Absolute Deviation for robust outlier detection.
/// MAD = `median(|X_i` - median(X)|)
///
/// An observation is anomalous if:
/// |x - median| > k * MAD * 1.4826
///
/// where 1.4826 is a scale factor for normal distributions,
/// and k is typically 3 (for 3-sigma equivalent).
///
/// # Example
/// ```
/// use alice_analytics::anomaly::MadDetector;
///
/// let mut detector = MadDetector::new(3.0);
///
/// // Train on normal data
/// for v in [10.0, 11.0, 9.0, 10.5, 9.5, 10.2, 10.8] {
///     detector.observe(v);
/// }
///
/// // Check for anomalies
/// assert!(!detector.is_anomaly(10.0)); // Normal
/// assert!(detector.is_anomaly(100.0)); // Anomaly!
/// ```
#[derive(Clone, Debug)]
pub struct MadDetector {
    /// Streaming median for values
    values_median: StreamingMedian,
    /// Streaming median for absolute deviations
    deviations_median: StreamingMedian,
    /// Recent values for deviation calculation
    recent_values: [f64; DEFAULT_WINDOW],
    /// Position in recent values
    pos: usize,
    /// Count of observations
    count: usize,
    /// Threshold multiplier (k)
    threshold_k: f64,
    /// Cached median value
    cached_median: f64,
    /// Cached MAD value
    cached_mad: f64,
    /// Whether cache is valid
    cache_valid: bool,
}

impl MadDetector {
    /// Scale factor for normal distribution (1/Phi^-1(0.75))
    const MAD_SCALE: f64 = 1.4826;

    /// Create a new MAD detector
    ///
    /// # Arguments
    /// * `threshold_k` - Number of MAD units for anomaly threshold (typically 3.0)
    #[must_use]
    pub const fn new(threshold_k: f64) -> Self {
        Self {
            values_median: StreamingMedian::new(),
            deviations_median: StreamingMedian::new(),
            recent_values: [0.0; DEFAULT_WINDOW],
            pos: 0,
            count: 0,
            threshold_k,
            cached_median: 0.0,
            cached_mad: 0.0,
            cache_valid: false,
        }
    }

    /// Observe a new value (updates statistics)
    pub fn observe(&mut self, value: f64) {
        // Store in recent values
        self.recent_values[self.pos] = value;
        self.pos = (self.pos + 1) % DEFAULT_WINDOW;
        if self.count < DEFAULT_WINDOW {
            self.count += 1;
        }

        // Update values median
        self.values_median.push(value);

        // Invalidate cache
        self.cache_valid = false;
    }

    /// Update cached statistics
    fn update_cache(&mut self) {
        if self.cache_valid {
            return;
        }

        // Get current median
        self.cached_median = self.values_median.median();

        // Calculate absolute deviations and their median
        self.deviations_median.clear();
        for i in 0..self.count {
            let dev = (self.recent_values[i] - self.cached_median).abs();
            self.deviations_median.push(dev);
        }
        self.cached_mad = self.deviations_median.median();

        self.cache_valid = true;
    }

    /// Check if a value is an anomaly
    pub fn is_anomaly(&mut self, value: f64) -> bool {
        if self.count < 3 {
            // Not enough data to determine anomalies
            return false;
        }

        self.update_cache();

        // Avoid division by zero
        if self.cached_mad < 1e-10 {
            // All values are the same, any different value is anomalous
            return (value - self.cached_median).abs() > 1e-10;
        }

        let deviation = (value - self.cached_median).abs();
        let threshold = self.threshold_k * self.cached_mad * Self::MAD_SCALE;

        deviation > threshold
    }

    /// Get the anomaly score (higher = more anomalous)
    ///
    /// Returns the number of MAD units from the median.
    pub fn anomaly_score(&mut self, value: f64) -> f64 {
        if self.count < 3 {
            return 0.0;
        }

        self.update_cache();

        if self.cached_mad < 1e-10 {
            return if (value - self.cached_median).abs() > 1e-10 {
                f64::INFINITY
            } else {
                0.0
            };
        }

        let inv_mad_scale = 1.0 / (self.cached_mad * Self::MAD_SCALE);
        (value - self.cached_median).abs() * inv_mad_scale
    }

    /// Get the current median
    pub fn median(&mut self) -> f64 {
        self.update_cache();
        self.cached_median
    }

    /// Get the current MAD
    pub fn mad(&mut self) -> f64 {
        self.update_cache();
        self.cached_mad
    }

    /// Get the threshold multiplier
    #[inline]
    #[must_use]
    pub const fn threshold_k(&self) -> f64 {
        self.threshold_k
    }

    /// Set the threshold multiplier
    #[inline]
    pub const fn set_threshold_k(&mut self, k: f64) {
        self.threshold_k = k;
    }

    /// Get count of observations
    #[inline]
    #[must_use]
    pub const fn count(&self) -> usize {
        self.count
    }

    /// Clear all observations
    pub const fn clear(&mut self) {
        self.values_median.clear();
        self.deviations_median.clear();
        self.recent_values = [0.0; DEFAULT_WINDOW];
        self.pos = 0;
        self.count = 0;
        self.cache_valid = false;
    }
}

// ============================================================================
// EWMA (Exponentially Weighted Moving Average) Detector
// ============================================================================

/// EWMA-based anomaly detector
///
/// Uses exponentially weighted moving average and standard deviation
/// for change point detection and anomaly flagging.
///
/// # Example
/// ```
/// use alice_analytics::anomaly::EwmaDetector;
///
/// let mut detector = EwmaDetector::new(0.1, 3.0);
///
/// // Feed normal values
/// for v in [10.0, 10.5, 9.5, 10.2, 9.8, 10.1] {
///     detector.observe(v);
/// }
///
/// // Check for anomalies
/// assert!(!detector.is_anomaly(10.0));
/// assert!(detector.is_anomaly(50.0));
/// ```
#[derive(Clone, Debug)]
pub struct EwmaDetector {
    /// Smoothing factor (0 < alpha <= 1)
    alpha: f64,
    /// Current EWMA
    ewma: f64,
    /// EWMA of squared deviations (for variance)
    ewma_var: f64,
    /// Threshold multiplier (number of std devs)
    threshold_k: f64,
    /// Whether initialized
    initialized: bool,
    /// Count of observations
    count: u64,
}

impl EwmaDetector {
    /// Create a new EWMA detector
    ///
    /// # Arguments
    /// * `alpha` - Smoothing factor in `(0.0, 1.0]`, higher = more reactive
    /// * `threshold_k` - Number of standard deviations for anomaly threshold
    ///
    /// # Panics
    ///
    /// `alpha` が `(0.0, 1.0]` の外 (`NaN` / 無限大を含む、どちらも比較が偽に
    /// なるので同じ assert で弾かれる) の場合
    ///
    /// 定義域の扱いは同 crate の
    /// [`ExponentialMovingAverage::new`](crate::streaming_ops::ExponentialMovingAverage::new)
    /// に合わせた (範囲外は黙って丸めず panic する) 2026-10-07 までは
    /// `alpha.clamp(0.001, 1.0)` だったので、`0.0` と負値が黙って `0.001` になり
    /// (⚠️ `-1.0` と `0.0` が同一結果になっていた)、**`NaN` は `clamp` が `NaN` を
    /// 返すので丸められずに残り**、以後 `ewma` / `std_dev` / `anomaly_score` が
    /// すべて `NaN` になって **`is_anomaly` が常に `false`** を返していた
    /// = 検出器が黙って無効化される 無限大の score は「異常」と読めるが、
    /// `false` は「正常」と読めるので、こちらの方が害が大きい
    #[must_use]
    pub const fn new(alpha: f64, threshold_k: f64) -> Self {
        assert!(
            alpha > 0.0 && alpha <= 1.0,
            "EwmaDetector alpha must be in (0.0, 1.0]"
        );
        Self {
            alpha,
            ewma: 0.0,
            ewma_var: 0.0,
            threshold_k,
            initialized: false,
            count: 0,
        }
    }

    /// Observe a new value and update statistics
    pub fn observe(&mut self, value: f64) {
        self.count += 1;

        if !self.initialized {
            self.ewma = value;
            self.ewma_var = 0.0;
            self.initialized = true;
            return;
        }

        // Update EWMA
        let deviation = value - self.ewma;
        self.ewma += self.alpha * deviation;

        // Update variance EWMA
        self.ewma_var =
            (1.0 - self.alpha) * (self.alpha * deviation).mul_add(deviation, self.ewma_var);
    }

    /// Check if a value is an anomaly (without updating)
    #[must_use]
    pub fn is_anomaly(&self, value: f64) -> bool {
        if !self.initialized || self.count < 3 {
            return false;
        }

        let std_dev = self.ewma_var.sqrt();
        if std_dev < 1e-10 {
            return (value - self.ewma).abs() > 1e-10;
        }

        let deviation = (value - self.ewma).abs();
        deviation > self.threshold_k * std_dev
    }

    /// Get anomaly score (number of standard deviations)
    ///
    /// 分散推定が 0 のとき (定数 stream、または `alpha = 1.0` で平滑化しない場合)
    /// は、`ewma` と一致する値に `0.0`、それ以外に `f64::INFINITY` を返す
    /// ⚠️ **これは `alpha = 1.0` の境界固有の挙動ではない**: `alpha = 0.3` でも
    /// 同じ値を 50 回入れれば `std_dev` は 0 になり、以後 `ewma` 以外は `inf` に
    /// なる (実測) 「散らばりが 0 の系列に対する逸脱は無限に異常」が契約で、
    /// `tests/panic_contract.rs` が値で固定する
    #[must_use]
    pub fn anomaly_score(&self, value: f64) -> f64 {
        if !self.initialized {
            return 0.0;
        }

        let std_dev = self.ewma_var.sqrt();
        if std_dev < 1e-10 {
            return if (value - self.ewma).abs() > 1e-10 {
                f64::INFINITY
            } else {
                0.0
            };
        }

        let inv_std = 1.0 / std_dev;
        (value - self.ewma).abs() * inv_std
    }

    /// Get current EWMA
    #[inline]
    #[must_use]
    pub const fn ewma(&self) -> f64 {
        self.ewma
    }

    /// Get current standard deviation estimate
    #[inline]
    #[must_use]
    pub fn std_dev(&self) -> f64 {
        self.ewma_var.sqrt()
    }

    /// Get smoothing factor
    #[inline]
    #[must_use]
    pub const fn alpha(&self) -> f64 {
        self.alpha
    }

    /// Set smoothing factor
    ///
    /// # Panics
    ///
    /// [`Self::new`] と同じ条件 (`alpha` が `(0.0, 1.0]` の外) setter が丸めたままだと
    /// 構築時の assert を後から回避できるので、同じ検査を置く
    #[inline]
    pub const fn set_alpha(&mut self, alpha: f64) {
        assert!(
            alpha > 0.0 && alpha <= 1.0,
            "EwmaDetector alpha must be in (0.0, 1.0]"
        );
        self.alpha = alpha;
    }

    /// Get threshold multiplier
    #[inline]
    #[must_use]
    pub const fn threshold_k(&self) -> f64 {
        self.threshold_k
    }

    /// Set threshold multiplier
    #[inline]
    pub const fn set_threshold_k(&mut self, k: f64) {
        self.threshold_k = k;
    }

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

    /// Reset the detector
    pub const fn reset(&mut self) {
        self.ewma = 0.0;
        self.ewma_var = 0.0;
        self.initialized = false;
        self.count = 0;
    }
}

// ============================================================================
// Z-Score Detector (Simple threshold-based)
// ============================================================================

/// Simple Z-score based anomaly detector
///
/// Maintains running mean and variance, flags values that exceed
/// a threshold number of standard deviations.
#[derive(Clone, Debug)]
pub struct ZScoreDetector {
    /// Running mean
    mean: f64,
    /// Running variance (using Welford's algorithm)
    m2: f64,
    /// Count of observations
    count: u64,
    /// Threshold (number of standard deviations)
    threshold_k: f64,
}

impl ZScoreDetector {
    /// Create a new Z-score detector
    #[must_use]
    pub const fn new(threshold_k: f64) -> Self {
        Self {
            mean: 0.0,
            m2: 0.0,
            count: 0,
            threshold_k,
        }
    }

    /// Observe a new value (updates running statistics)
    pub fn observe(&mut self, value: f64) {
        self.count += 1;
        let inv_count = 1.0 / u64_f64(self.count);
        let delta = value - self.mean;
        self.mean += delta * inv_count;
        let delta2 = value - self.mean;
        self.m2 += delta * delta2;
    }

    /// Get the variance
    #[inline]
    #[must_use]
    pub fn variance(&self) -> f64 {
        if self.count < 2 {
            0.0
        } else {
            self.m2 / u64_f64(self.count - 1)
        }
    }

    /// Get the standard deviation
    #[inline]
    #[must_use]
    pub fn std_dev(&self) -> f64 {
        self.variance().sqrt()
    }

    /// Check if a value is an anomaly
    #[must_use]
    pub fn is_anomaly(&self, value: f64) -> bool {
        if self.count < 3 {
            return false;
        }

        let std_dev = self.std_dev();
        if std_dev < 1e-10 {
            return (value - self.mean).abs() > 1e-10;
        }

        let inv_std = 1.0 / std_dev;
        let z_score = (value - self.mean).abs() * inv_std;
        z_score > self.threshold_k
    }

    /// Get the Z-score for a value
    #[must_use]
    pub fn z_score(&self, value: f64) -> f64 {
        let std_dev = self.std_dev();
        if std_dev < 1e-10 {
            return if (value - self.mean).abs() > 1e-10 {
                f64::INFINITY
            } else {
                0.0
            };
        }
        let inv_std = 1.0 / std_dev;
        (value - self.mean) * inv_std
    }

    /// Get current mean
    #[inline]
    #[must_use]
    pub const fn mean(&self) -> f64 {
        self.mean
    }

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

    /// Reset the detector
    pub const fn reset(&mut self) {
        self.mean = 0.0;
        self.m2 = 0.0;
        self.count = 0;
    }
}

// ============================================================================
// Anomaly Event
// ============================================================================

/// Represents a detected anomaly
#[derive(Clone, Debug)]
pub struct AnomalyEvent {
    /// The anomalous value
    pub value: f64,
    /// Anomaly score (e.g., number of MAD/std devs)
    pub score: f64,
    /// Expected value (median or mean)
    pub expected: f64,
    /// Timestamp (if applicable)
    pub timestamp: u64,
    /// Metric identifier
    pub metric_id: u64,
}

/// Callback for anomaly detection
pub trait AnomalyCallback {
    /// Called when an anomaly is detected
    fn on_anomaly(&mut self, event: AnomalyEvent);
}

// ============================================================================
// Composite Anomaly Detector
// ============================================================================

/// Composite detector that combines multiple detection methods
///
/// An observation is flagged as anomalous if ANY detector flags it.
#[derive(Clone, Debug)]
pub struct CompositeDetector {
    /// MAD-based detector
    pub mad: MadDetector,
    /// EWMA-based detector
    pub ewma: EwmaDetector,
    /// Z-score detector
    pub zscore: ZScoreDetector,
    /// Whether to require all detectors to agree
    pub require_consensus: bool,
}

impl CompositeDetector {
    /// Create a new composite detector with default settings
    #[must_use]
    pub const fn new() -> Self {
        Self {
            mad: MadDetector::new(3.0),
            ewma: EwmaDetector::new(0.1, 3.0),
            zscore: ZScoreDetector::new(3.0),
            require_consensus: false,
        }
    }

    /// Create with custom thresholds
    ///
    /// # Panics
    ///
    /// `ewma_alpha` が `(0.0, 1.0]` の外の場合 ([`EwmaDetector::new`] にそのまま渡す)
    #[must_use]
    pub const fn with_thresholds(mad_k: f64, ewma_alpha: f64, ewma_k: f64, zscore_k: f64) -> Self {
        Self {
            mad: MadDetector::new(mad_k),
            ewma: EwmaDetector::new(ewma_alpha, ewma_k),
            zscore: ZScoreDetector::new(zscore_k),
            require_consensus: false,
        }
    }

    /// Observe a new value (updates all detectors)
    pub fn observe(&mut self, value: f64) {
        self.mad.observe(value);
        self.ewma.observe(value);
        self.zscore.observe(value);
    }

    /// Check if a value is an anomaly
    pub fn is_anomaly(&mut self, value: f64) -> bool {
        let mad_anomaly = self.mad.is_anomaly(value);
        let ewma_anomaly = self.ewma.is_anomaly(value);
        let zscore_anomaly = self.zscore.is_anomaly(value);

        if self.require_consensus {
            // All must agree
            mad_anomaly && ewma_anomaly && zscore_anomaly
        } else {
            // Any detector flags it
            mad_anomaly || ewma_anomaly || zscore_anomaly
        }
    }

    /// Get combined anomaly score (max of all scores)
    pub fn anomaly_score(&mut self, value: f64) -> f64 {
        let mad_score = self.mad.anomaly_score(value);
        let ewma_score = self.ewma.anomaly_score(value);
        let zscore_score = self.zscore.z_score(value).abs();

        mad_score.max(ewma_score).max(zscore_score)
    }

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

    /// Reset all detectors
    pub const fn reset(&mut self) {
        self.mad.clear();
        self.ewma.reset();
        self.zscore.reset();
    }
}

impl Default for CompositeDetector {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
    use super::*;
    use crate::math::usize_f64;

    #[test]
    fn test_streaming_median() {
        let mut sm = StreamingMedian::new();

        for v in [5.0, 2.0, 8.0, 1.0, 9.0] {
            sm.push(v);
        }

        let median = sm.median();
        assert_eq!(median, 5.0); // Sorted: 1, 2, 5, 8, 9 -> median = 5
    }

    #[test]
    fn test_streaming_median_even() {
        let mut sm = StreamingMedian::new();

        for v in [1.0, 2.0, 3.0, 4.0] {
            sm.push(v);
        }

        let median = sm.median();
        assert_eq!(median, 2.5); // Sorted: 1, 2, 3, 4 -> median = (2+3)/2 = 2.5
    }

    #[test]
    fn test_mad_detector_normal() {
        let mut detector = MadDetector::new(3.0);

        // Add normal data centered around 10
        for v in [10.0, 10.5, 9.5, 10.2, 9.8, 10.1, 9.9, 10.3, 9.7, 10.4] {
            detector.observe(v);
        }

        // Normal values should not be anomalies
        assert!(!detector.is_anomaly(10.0));
        assert!(!detector.is_anomaly(10.5));
        assert!(!detector.is_anomaly(9.5));

        // Extreme values should be anomalies
        assert!(detector.is_anomaly(100.0));
        assert!(detector.is_anomaly(-50.0));
    }

    #[test]
    fn test_ewma_detector() {
        let mut detector = EwmaDetector::new(0.1, 3.0);

        // Train on values with some variance
        for i in 0..100 {
            let value = 10.0 + f64::from(i % 3) - 1.0; // 9, 10, 11
            detector.observe(value);
        }

        // Should be close to 10
        assert!((detector.ewma() - 10.0).abs() < 1.0);

        // Normal values (within trained range)
        assert!(!detector.is_anomaly(10.0));
        assert!(!detector.is_anomaly(11.0));

        // Anomaly (far outside trained range)
        assert!(detector.is_anomaly(50.0));
    }

    #[test]
    fn test_zscore_detector() {
        let mut detector = ZScoreDetector::new(3.0);

        // Add normal data
        for v in [10.0, 11.0, 9.0, 10.5, 9.5, 10.2, 9.8, 10.1, 9.9, 10.3] {
            detector.observe(v);
        }

        assert!((detector.mean() - 10.03).abs() < 0.01);

        // Normal values
        assert!(!detector.is_anomaly(10.0));

        // Anomaly
        assert!(detector.is_anomaly(100.0));
    }

    #[test]
    fn test_composite_detector() {
        let mut detector = CompositeDetector::new();

        // Train on normal data
        for v in [10.0, 10.5, 9.5, 10.2, 9.8, 10.1, 9.9, 10.3, 9.7, 10.4] {
            detector.observe(v);
        }

        // Normal
        assert!(!detector.is_anomaly(10.0));

        // Anomaly
        assert!(detector.is_anomaly(100.0));

        let score = detector.anomaly_score(100.0);
        assert!(score > 3.0);
    }

    #[test]
    fn test_mad_detector_constant() {
        let mut detector = MadDetector::new(3.0);

        // All same values
        for _ in 0..10 {
            detector.observe(5.0);
        }

        // Same value is not anomaly
        assert!(!detector.is_anomaly(5.0));

        // Different value is anomaly (MAD = 0)
        assert!(detector.is_anomaly(5.1));
    }

    #[test]
    fn test_streaming_median_default() {
        let sm = StreamingMedian::default();
        assert_eq!(sm.count(), 0);
        assert!(!sm.is_full());
    }

    #[test]
    fn test_streaming_median_empty() {
        let mut sm = StreamingMedian::new();
        assert_eq!(sm.median(), 0.0);
    }

    #[test]
    fn test_streaming_median_clear() {
        let mut sm = StreamingMedian::new();
        sm.push(1.0);
        sm.push(2.0);
        assert_eq!(sm.count(), 2);
        sm.clear();
        assert_eq!(sm.count(), 0);
    }

    #[test]
    fn test_streaming_median_full() {
        let mut sm = StreamingMedian::new();
        for i in 0..DEFAULT_WINDOW {
            sm.push(usize_f64(i));
        }
        assert!(sm.is_full());
        assert_eq!(sm.count(), DEFAULT_WINDOW);
    }

    #[test]
    fn test_streaming_median_wrap() {
        let mut sm = StreamingMedian::new();
        // Fill and then wrap
        for i in 0..(DEFAULT_WINDOW + 10) {
            sm.push(usize_f64(i));
        }
        assert_eq!(sm.count(), DEFAULT_WINDOW);
        let median = sm.median();
        assert!(median > 0.0);
    }

    #[test]
    fn test_mad_detector_insufficient_data() {
        let mut detector = MadDetector::new(3.0);
        detector.observe(10.0);
        detector.observe(20.0);
        // Less than 3 observations: never anomaly
        assert!(!detector.is_anomaly(1000.0));
    }

    #[test]
    fn test_mad_detector_count() {
        let mut detector = MadDetector::new(3.0);
        assert_eq!(detector.count(), 0);
        detector.observe(1.0);
        assert_eq!(detector.count(), 1);
    }

    #[test]
    fn test_mad_detector_threshold_k() {
        let detector = MadDetector::new(5.0);
        assert!((detector.threshold_k() - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_mad_detector_set_threshold() {
        let mut detector = MadDetector::new(3.0);
        detector.set_threshold_k(5.0);
        assert!((detector.threshold_k() - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_mad_detector_clear() {
        let mut detector = MadDetector::new(3.0);
        for v in [10.0, 11.0, 9.0, 10.5] {
            detector.observe(v);
        }
        detector.clear();
        assert_eq!(detector.count(), 0);
    }

    #[test]
    fn test_mad_detector_anomaly_score() {
        let mut detector = MadDetector::new(3.0);
        for v in [10.0, 10.5, 9.5, 10.2, 9.8] {
            detector.observe(v);
        }
        let score_normal = detector.anomaly_score(10.0);
        let score_extreme = detector.anomaly_score(100.0);
        assert!(score_extreme > score_normal);
    }

    #[test]
    fn test_mad_detector_median_and_mad() {
        let mut detector = MadDetector::new(3.0);
        for v in [1.0, 2.0, 3.0, 4.0, 5.0] {
            detector.observe(v);
        }
        let median = detector.median();
        assert!((median - 3.0).abs() < 0.01);
        let mad = detector.mad();
        assert!(mad > 0.0);
    }

    #[test]
    fn test_ewma_detector_not_initialized() {
        let detector = EwmaDetector::new(0.1, 3.0);
        assert!(!detector.is_anomaly(100.0));
        assert_eq!(detector.anomaly_score(100.0), 0.0);
    }

    #[test]
    fn test_ewma_detector_count() {
        let mut detector = EwmaDetector::new(0.1, 3.0);
        assert_eq!(detector.count(), 0);
        detector.observe(10.0);
        assert_eq!(detector.count(), 1);
    }

    #[test]
    fn test_ewma_detector_alpha() {
        let detector = EwmaDetector::new(0.2, 3.0);
        assert!((detector.alpha() - 0.2).abs() < f64::EPSILON);
    }

    #[test]
    fn test_ewma_detector_set_alpha() {
        let mut detector = EwmaDetector::new(0.1, 3.0);
        detector.set_alpha(0.5);
        assert!((detector.alpha() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_ewma_detector_set_threshold() {
        let mut detector = EwmaDetector::new(0.1, 3.0);
        detector.set_threshold_k(5.0);
        assert!((detector.threshold_k() - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_ewma_detector_std_dev() {
        let mut detector = EwmaDetector::new(0.1, 3.0);
        for v in [10.0, 20.0, 30.0, 40.0, 50.0] {
            detector.observe(v);
        }
        assert!(detector.std_dev() > 0.0);
    }

    #[test]
    fn test_ewma_detector_reset() {
        let mut detector = EwmaDetector::new(0.1, 3.0);
        detector.observe(10.0);
        detector.observe(20.0);
        detector.reset();
        assert_eq!(detector.count(), 0);
    }

    #[test]
    fn test_zscore_detector_insufficient_data() {
        let mut detector = ZScoreDetector::new(3.0);
        detector.observe(10.0);
        assert!(!detector.is_anomaly(1000.0));
    }

    #[test]
    fn test_zscore_detector_variance() {
        let mut detector = ZScoreDetector::new(3.0);
        for v in [10.0, 20.0, 30.0] {
            detector.observe(v);
        }
        assert!(detector.variance() > 0.0);
        assert!(detector.std_dev() > 0.0);
    }

    #[test]
    fn test_zscore_detector_z_score() {
        let mut detector = ZScoreDetector::new(3.0);
        for v in [10.0, 10.0, 10.0, 10.0, 10.0] {
            detector.observe(v);
        }
        // All same values, z_score for 10.0 should be 0
        let z = detector.z_score(10.0);
        assert!(z.abs() < f64::EPSILON || z == 0.0);
    }

    #[test]
    fn test_zscore_detector_count() {
        let mut detector = ZScoreDetector::new(3.0);
        detector.observe(1.0);
        detector.observe(2.0);
        assert_eq!(detector.count(), 2);
    }

    #[test]
    fn test_zscore_detector_reset() {
        let mut detector = ZScoreDetector::new(3.0);
        detector.observe(1.0);
        detector.observe(2.0);
        detector.reset();
        assert_eq!(detector.count(), 0);
        assert_eq!(detector.mean(), 0.0);
    }

    #[test]
    fn test_composite_detector_default() {
        let detector = CompositeDetector::default();
        assert_eq!(detector.count(), 0);
    }

    #[test]
    fn test_composite_detector_with_thresholds() {
        let detector = CompositeDetector::with_thresholds(2.0, 0.2, 2.5, 2.0);
        assert!((detector.mad.threshold_k() - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_composite_detector_consensus() {
        let mut detector = CompositeDetector::new();
        detector.require_consensus = true;
        for v in [10.0, 10.5, 9.5, 10.2, 9.8, 10.1, 9.9] {
            detector.observe(v);
        }
        // With consensus, borderline values less likely flagged
        assert!(!detector.is_anomaly(10.0));
    }

    #[test]
    fn test_composite_detector_reset() {
        let mut detector = CompositeDetector::new();
        detector.observe(10.0);
        detector.observe(20.0);
        detector.reset();
        assert_eq!(detector.count(), 0);
    }

    #[test]
    fn test_anomaly_event_clone() {
        let event = AnomalyEvent {
            value: 100.0,
            score: 5.0,
            expected: 10.0,
            timestamp: 12345,
            metric_id: 1,
        };
        let cloned = event;
        assert_eq!(cloned.value, 100.0);
        assert_eq!(cloned.metric_id, 1);
    }

    // `format!` / `Vec` / the entropy-seeded constructors are `std`-only,
    // so this case cannot run on the `no_std` build
    #[cfg(feature = "std")]
    #[test]
    fn test_anomaly_event_debug() {
        let event = AnomalyEvent {
            value: 100.0,
            score: 5.0,
            expected: 10.0,
            timestamp: 0,
            metric_id: 0,
        };
        let s = format!("{event:?}");
        assert!(s.contains("value"));
    }
}