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
use crate::Direction;
macro_rules! impl_cusum {
($name:ident, $builder:ident, $ty:ty, min_slack = $min_slack:expr) => {
/// CUSUM — Cumulative Sum change detector (Page, 1954).
///
/// Detects persistent shifts in the mean of a streaming process
/// in either direction. Signals when cumulative deviation from a
/// target exceeds a threshold.
///
/// Supports asymmetric slack and threshold parameters for different
/// sensitivity to upward vs downward shifts.
///
/// # Use Cases
/// - Exchange ack latency degradation (detect shift up)
/// - Recovery detection (detect shift back down)
/// - Market data feed quality monitoring
#[derive(Debug, Clone)]
pub struct $name {
target: $ty,
slack_upper: $ty,
slack_lower: $ty,
threshold_upper: $ty,
threshold_lower: $ty,
upper: $ty,
lower: $ty,
count: u64,
min_samples: u64,
// Track whether user explicitly set slack/threshold so
// reset_with_target knows whether to recompute defaults.
slack_upper_explicit: bool,
slack_lower_explicit: bool,
threshold_upper_explicit: bool,
threshold_lower_explicit: bool,
}
/// Builder for [`
#[doc = stringify!($name)]
/// `].
///
/// # Example
///
/// ```
/// use nexus_stats::*;
#[doc = concat!("let mut cusum = ", stringify!($name), "::builder(100 as ", stringify!($ty), ")")]
/// .slack(5 as _)
/// .threshold(50 as _)
/// .min_samples(20)
/// .build()
/// .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct $builder {
target: $ty,
slack_upper: Option<$ty>,
slack_lower: Option<$ty>,
threshold_upper: Option<$ty>,
threshold_lower: Option<$ty>,
min_samples: u64,
seed_upper: Option<$ty>,
seed_lower: Option<$ty>,
}
impl $name {
/// Creates a builder with the target (expected baseline mean).
#[inline]
#[must_use]
pub fn builder(target: $ty) -> $builder {
$builder {
target,
slack_upper: Option::None,
slack_lower: Option::None,
threshold_upper: Option::None,
threshold_lower: Option::None,
min_samples: 0,
seed_upper: Option::None,
seed_lower: Option::None,
}
}
/// Feeds a sample. Returns shift direction once primed.
///
/// Returns `None` until `min_samples` have been processed.
/// After priming, returns `Some(Direction::Rising)`, `Some(Direction::Falling)`,
/// or `Some(Direction::Neutral)`.
#[inline]
#[must_use]
pub fn update(&mut self, sample: $ty) -> Option<Direction> {
self.count += 1;
let diff = sample - self.target;
// S_high = max(0, S_high + (x - target) - slack_upper)
// .max(0) compiles to branchless maxsd (float) / cmov (int)
let s_high = self.upper + diff - self.slack_upper;
self.upper = s_high.max(0 as $ty);
// S_low = max(0, S_low + (target - x) - slack_lower)
let s_low = self.lower - diff - self.slack_lower;
self.lower = s_low.max(0 as $ty);
if self.count < self.min_samples {
return Option::None;
}
if self.upper > self.threshold_upper {
Option::Some(Direction::Rising)
} else if self.lower > self.threshold_lower {
Option::Some(Direction::Falling)
} else {
Option::Some(Direction::Neutral)
}
}
/// Upper cumulative sum (tracks upward drift).
#[inline]
#[must_use]
pub fn upper(&self) -> $ty {
self.upper
}
/// Lower cumulative sum (tracks downward drift).
#[inline]
#[must_use]
pub fn lower(&self) -> $ty {
self.lower
}
/// Number of samples processed.
#[inline]
#[must_use]
pub fn count(&self) -> u64 {
self.count
}
/// Whether the detector has reached `min_samples`.
#[inline]
#[must_use]
pub fn is_primed(&self) -> bool {
self.count >= self.min_samples
}
/// Resets cumulative sums and count to zero. Parameters unchanged.
#[inline]
pub fn reset(&mut self) {
self.upper = 0 as $ty;
self.lower = 0 as $ty;
self.count = 0;
}
/// Resets and updates the target mean.
///
/// If slack or threshold were not explicitly set by the user,
/// they are recomputed from the new target using the defaults
/// (5% and 50% of target respectively).
#[inline]
pub fn reset_with_target(&mut self, new_target: $ty) {
self.target = new_target;
self.upper = 0 as $ty;
self.lower = 0 as $ty;
self.count = 0;
if !self.slack_upper_explicit {
self.slack_upper = $builder::default_slack(new_target);
}
if !self.slack_lower_explicit {
self.slack_lower = $builder::default_slack(new_target);
}
if !self.threshold_upper_explicit {
self.threshold_upper = $builder::default_threshold(new_target);
}
if !self.threshold_lower_explicit {
self.threshold_lower = $builder::default_threshold(new_target);
}
}
/// The target (expected baseline mean).
#[inline]
#[must_use]
pub fn target(&self) -> $ty {
self.target
}
/// Upper slack parameter.
#[inline]
#[must_use]
pub fn slack_upper(&self) -> $ty {
self.slack_upper
}
/// Lower slack parameter.
#[inline]
#[must_use]
pub fn slack_lower(&self) -> $ty {
self.slack_lower
}
/// Upper threshold parameter.
#[inline]
#[must_use]
pub fn threshold_upper(&self) -> $ty {
self.threshold_upper
}
/// Lower threshold parameter.
#[inline]
#[must_use]
pub fn threshold_lower(&self) -> $ty {
self.threshold_lower
}
/// Minimum samples required before detection activates.
#[inline]
#[must_use]
pub fn min_samples(&self) -> u64 {
self.min_samples
}
/// Updates all tuning parameters without resetting cumulative sums or count.
///
/// # Errors
///
/// - Slack values must be non-negative.
/// - Threshold values must be positive.
#[inline]
pub fn reconfigure(
&mut self,
target: $ty,
slack_upper: $ty,
slack_lower: $ty,
threshold_upper: $ty,
threshold_lower: $ty,
) -> Result<(), crate::ConfigError> {
if slack_upper < (0 as $ty) {
return Err(crate::ConfigError::Invalid("slack_upper must be non-negative"));
}
if slack_lower < (0 as $ty) {
return Err(crate::ConfigError::Invalid("slack_lower must be non-negative"));
}
if threshold_upper <= (0 as $ty) {
return Err(crate::ConfigError::Invalid("threshold_upper must be positive"));
}
if threshold_lower <= (0 as $ty) {
return Err(crate::ConfigError::Invalid("threshold_lower must be positive"));
}
self.target = target;
self.slack_upper = slack_upper;
self.slack_lower = slack_lower;
self.threshold_upper = threshold_upper;
self.threshold_lower = threshold_lower;
self.slack_upper_explicit = true;
self.slack_lower_explicit = true;
self.threshold_upper_explicit = true;
self.threshold_lower_explicit = true;
Ok(())
}
}
impl $builder {
#[inline]
fn default_slack(target: $ty) -> $ty {
// 5% of target magnitude, floored to $min_slack
let abs_target = if target < (0 as $ty) { (0 as $ty) - target } else { target };
let slack = abs_target / (20 as $ty);
if slack < ($min_slack as $ty) { $min_slack as $ty } else { slack }
}
#[inline]
fn default_threshold(target: $ty) -> $ty {
// 50% of target magnitude
let abs_target = if target < (0 as $ty) { (0 as $ty) - target } else { target };
abs_target / (2 as $ty)
}
/// Sets both upper and lower slack (symmetric sensitivity).
///
/// Slack controls sensitivity — smaller values detect smaller shifts
/// but increase false alarm rate. Typically set to half the minimum
/// shift you want to detect.
#[inline]
#[must_use]
pub fn slack(mut self, slack: $ty) -> Self {
self.slack_upper = Option::Some(slack);
self.slack_lower = Option::Some(slack);
self
}
/// Sets the upper slack independently.
///
/// Controls sensitivity to upward shifts only.
#[inline]
#[must_use]
pub fn slack_upper(mut self, slack: $ty) -> Self {
self.slack_upper = Option::Some(slack);
self
}
/// Sets the lower slack independently.
///
/// Controls sensitivity to downward shifts only.
#[inline]
#[must_use]
pub fn slack_lower(mut self, slack: $ty) -> Self {
self.slack_lower = Option::Some(slack);
self
}
/// Sets both upper and lower thresholds (symmetric decision boundary).
///
/// Larger thresholds mean fewer false alarms but slower detection.
#[inline]
#[must_use]
pub fn threshold(mut self, threshold: $ty) -> Self {
self.threshold_upper = Option::Some(threshold);
self.threshold_lower = Option::Some(threshold);
self
}
/// Sets the upper threshold independently.
///
/// Decision boundary for upward shift detection only.
#[inline]
#[must_use]
pub fn threshold_upper(mut self, threshold: $ty) -> Self {
self.threshold_upper = Option::Some(threshold);
self
}
/// Sets the lower threshold independently.
///
/// Decision boundary for downward shift detection only.
#[inline]
#[must_use]
pub fn threshold_lower(mut self, threshold: $ty) -> Self {
self.threshold_lower = Option::Some(threshold);
self
}
/// Minimum samples before detection activates. Default: 0.
#[inline]
#[must_use]
pub fn min_samples(mut self, min: u64) -> Self {
self.min_samples = min;
self
}
/// Pre-loads the upper cumulative sum from calibration data.
///
/// When seeded, `is_primed()` returns true immediately.
#[inline]
#[must_use]
pub fn seed_upper(mut self, val: $ty) -> Self {
self.seed_upper = Option::Some(val);
self
}
/// Pre-loads the lower cumulative sum from calibration data.
///
/// When seeded, `is_primed()` returns true immediately.
#[inline]
#[must_use]
pub fn seed_lower(mut self, val: $ty) -> Self {
self.seed_lower = Option::Some(val);
self
}
/// Builds the detector.
///
/// # Errors
///
/// - Slack values must be non-negative.
/// - Threshold values must be positive.
#[inline]
pub fn build(self) -> Result<$name, crate::ConfigError> {
let slack_upper_explicit = self.slack_upper.is_some();
let slack_lower_explicit = self.slack_lower.is_some();
let threshold_upper_explicit = self.threshold_upper.is_some();
let threshold_lower_explicit = self.threshold_lower.is_some();
let slack_upper = self.slack_upper.unwrap_or_else(|| Self::default_slack(self.target));
let slack_lower = self.slack_lower.unwrap_or_else(|| Self::default_slack(self.target));
let threshold_upper = self.threshold_upper.unwrap_or_else(|| Self::default_threshold(self.target));
let threshold_lower = self.threshold_lower.unwrap_or_else(|| Self::default_threshold(self.target));
if slack_upper < (0 as $ty) {
return Err(crate::ConfigError::Invalid("slack_upper must be non-negative"));
}
if slack_lower < (0 as $ty) {
return Err(crate::ConfigError::Invalid("slack_lower must be non-negative"));
}
if threshold_upper <= (0 as $ty) {
return Err(crate::ConfigError::Invalid("threshold_upper must be positive"));
}
if threshold_lower <= (0 as $ty) {
return Err(crate::ConfigError::Invalid("threshold_lower must be positive"));
}
let seeded = self.seed_upper.is_some() || self.seed_lower.is_some();
let initial_count = if seeded { self.min_samples } else { 0 };
Ok($name {
target: self.target,
slack_upper,
slack_lower,
threshold_upper,
threshold_lower,
upper: self.seed_upper.unwrap_or(0 as $ty),
lower: self.seed_lower.unwrap_or(0 as $ty),
count: initial_count,
min_samples: self.min_samples,
slack_upper_explicit,
slack_lower_explicit,
threshold_upper_explicit,
threshold_lower_explicit,
})
}
}
};
}
impl_cusum!(CusumF64, CusumF64Builder, f64, min_slack = 0.0);
impl_cusum!(CusumF32, CusumF32Builder, f32, min_slack = 0.0);
impl_cusum!(CusumI64, CusumI64Builder, i64, min_slack = 1);
impl_cusum!(CusumI32, CusumI32Builder, i32, min_slack = 1);
impl_cusum!(CusumI128, CusumI128Builder, i128, min_slack = 1);
#[cfg(test)]
mod tests {
use super::*;
// =========================================================================
// Basic shift detection
// =========================================================================
#[test]
fn detects_upward_shift() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
// Feed normal samples — should not trigger
for _ in 0..10 {
let result = cusum.update(100.0);
assert_eq!(result, Some(Direction::Neutral));
}
// Feed elevated samples — should eventually trigger upper
let mut triggered = false;
for _ in 0..100 {
if cusum.update(120.0) == Some(Direction::Rising) {
triggered = true;
break;
}
}
assert!(triggered, "should have detected upward shift");
}
#[test]
fn detects_downward_shift() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
// Feed depressed samples — should eventually trigger lower
let mut triggered = false;
for _ in 0..100 {
if cusum.update(80.0) == Some(Direction::Falling) {
triggered = true;
break;
}
}
assert!(triggered, "should have detected downward shift");
}
#[test]
fn no_false_positive_at_target() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
for _ in 0..1000 {
assert_eq!(cusum.update(100.0), Some(Direction::Neutral));
}
}
// =========================================================================
// Priming behavior
// =========================================================================
#[test]
fn returns_none_before_primed() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.min_samples(10)
.build()
.unwrap();
for _ in 0..9 {
assert_eq!(cusum.update(200.0), None);
}
assert!(!cusum.is_primed());
// 10th sample should be primed
let result = cusum.update(200.0);
assert!(result.is_some());
assert!(cusum.is_primed());
}
#[test]
fn primed_immediately_with_zero_min_samples() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
assert_eq!(cusum.min_samples(), 0);
// First sample should return Some
assert!(cusum.update(100.0).is_some());
}
// =========================================================================
// Reset
// =========================================================================
#[test]
#[allow(clippy::float_cmp)]
fn reset_clears_state() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
for _ in 0..10 {
let _ = cusum.update(120.0);
}
assert!(cusum.upper() > 0.0);
assert!(cusum.count() > 0);
cusum.reset();
assert_eq!(cusum.upper(), 0.0);
assert_eq!(cusum.lower(), 0.0);
assert_eq!(cusum.count(), 0);
}
#[test]
fn reset_with_target_updates_defaults() {
let mut cusum = CusumF64::builder(100.0).build().unwrap();
// Defaults based on 100.0
let original_slack = cusum.slack_upper();
let original_threshold = cusum.threshold_upper();
cusum.reset_with_target(200.0);
// Defaults should scale with new target
assert!(cusum.slack_upper() > original_slack);
assert!(cusum.threshold_upper() > original_threshold);
}
#[test]
#[allow(clippy::float_cmp)]
fn reset_with_target_preserves_explicit_params() {
let mut cusum = CusumF64::builder(100.0)
.slack(10.0)
.threshold(75.0)
.build()
.unwrap();
cusum.reset_with_target(200.0);
// Explicit values should not change
assert_eq!(cusum.slack_upper(), 10.0);
assert_eq!(cusum.slack_lower(), 10.0);
assert_eq!(cusum.threshold_upper(), 75.0);
assert_eq!(cusum.threshold_lower(), 75.0);
}
// =========================================================================
// Asymmetric slack and threshold
// =========================================================================
#[test]
fn asymmetric_slack() {
// Tight upper slack (sensitive to increases), loose lower slack
let mut cusum = CusumF64::builder(100.0)
.slack_upper(2.0)
.slack_lower(10.0)
.threshold(50.0)
.build()
.unwrap();
// Small upward deviation should accumulate faster than downward
for _ in 0..10 {
let _ = cusum.update(110.0);
}
let upper_after = cusum.upper();
cusum.reset();
for _ in 0..10 {
let _ = cusum.update(90.0);
}
let lower_after = cusum.lower();
// Upper should accumulate more (slack_upper=2 eats less of the deviation)
assert!(
upper_after > lower_after,
"upper ({upper_after}) should accumulate faster than lower ({lower_after}) with tighter slack"
);
}
#[test]
fn asymmetric_threshold() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold_upper(20.0) // trigger fast on increases
.threshold_lower(500.0) // very slow to trigger on decreases
.build()
.unwrap();
// Upward shift should trigger quickly
let mut upper_triggered = false;
for _ in 0..20 {
if cusum.update(120.0) == Some(Direction::Rising) {
upper_triggered = true;
break;
}
}
assert!(upper_triggered);
// Downward shift should NOT trigger with same number of samples
// deviation per sample: 15, over 20 samples = 300 < 500
cusum.reset();
let mut lower_triggered = false;
for _ in 0..20 {
if cusum.update(80.0) == Some(Direction::Falling) {
lower_triggered = true;
break;
}
}
assert!(
!lower_triggered,
"lower should not trigger with high threshold"
);
}
#[test]
#[allow(clippy::float_cmp)]
fn symmetric_slack_sets_both() {
let cusum = CusumF64::builder(100.0).slack(7.5).build().unwrap();
assert_eq!(cusum.slack_upper(), 7.5);
assert_eq!(cusum.slack_lower(), 7.5);
}
#[test]
#[allow(clippy::float_cmp)]
fn symmetric_threshold_sets_both() {
let cusum = CusumF64::builder(100.0).threshold(42.0).build().unwrap();
assert_eq!(cusum.threshold_upper(), 42.0);
assert_eq!(cusum.threshold_lower(), 42.0);
}
// =========================================================================
// Builder validation
// =========================================================================
#[test]
fn rejects_negative_slack_upper() {
let result = CusumF64::builder(100.0).slack_upper(-1.0).build();
assert!(matches!(
result,
Err(crate::ConfigError::Invalid(
"slack_upper must be non-negative"
))
));
}
#[test]
fn rejects_negative_slack_lower() {
let result = CusumF64::builder(100.0).slack_lower(-1.0).build();
assert!(matches!(
result,
Err(crate::ConfigError::Invalid(
"slack_lower must be non-negative"
))
));
}
#[test]
fn rejects_zero_threshold() {
let result = CusumF64::builder(100.0).threshold(0.0).build();
assert!(matches!(
result,
Err(crate::ConfigError::Invalid(
"threshold_upper must be positive"
))
));
}
#[test]
fn rejects_negative_threshold_lower() {
let result = CusumF64::builder(100.0).threshold_lower(-1.0).build();
assert!(matches!(
result,
Err(crate::ConfigError::Invalid(
"threshold_lower must be positive"
))
));
}
// =========================================================================
// Integer variants
// =========================================================================
#[test]
fn i64_detects_upward_shift() {
let mut cusum = CusumI64::builder(1000)
.slack(50)
.threshold(500)
.build()
.unwrap();
let mut triggered = false;
for _ in 0..100 {
if cusum.update(1200) == Some(Direction::Rising) {
triggered = true;
break;
}
}
assert!(triggered);
}
#[test]
fn i32_basic() {
let mut cusum = CusumI32::builder(100)
.slack(5)
.threshold(50)
.build()
.unwrap();
assert_eq!(cusum.update(100), Some(Direction::Neutral));
}
#[test]
fn f32_basic() {
let mut cusum = CusumF32::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
assert_eq!(cusum.update(100.0), Some(Direction::Neutral));
}
// =========================================================================
// Edge cases
// =========================================================================
#[test]
fn count_increments() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
assert_eq!(cusum.count(), 0);
let _ = cusum.update(100.0);
assert_eq!(cusum.count(), 1);
let _ = cusum.update(100.0);
assert_eq!(cusum.count(), 2);
}
#[test]
#[allow(clippy::float_cmp)]
fn upper_and_lower_start_at_zero() {
let cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
assert_eq!(cusum.upper(), 0.0);
assert_eq!(cusum.lower(), 0.0);
}
#[test]
#[allow(clippy::float_cmp)]
fn cusum_at_exactly_slack_no_accumulation() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
// Deviation exactly equals slack — S_high = max(0, 0 + 5 - 5) = 0
let _ = cusum.update(105.0);
assert_eq!(cusum.upper(), 0.0);
}
// =========================================================================
// Reconfigure
// =========================================================================
#[test]
#[allow(clippy::float_cmp)]
fn reconfigure_changes_params_preserves_state() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
// Accumulate some state
for _ in 0..5 {
let _ = cusum.update(120.0);
}
let upper_before = cusum.upper();
let count_before = cusum.count();
assert!(upper_before > 0.0);
// Reconfigure
cusum.reconfigure(200.0, 10.0, 10.0, 100.0, 100.0).unwrap();
// Parameters changed
assert_eq!(cusum.target(), 200.0);
assert_eq!(cusum.slack_upper(), 10.0);
assert_eq!(cusum.slack_lower(), 10.0);
assert_eq!(cusum.threshold_upper(), 100.0);
assert_eq!(cusum.threshold_lower(), 100.0);
// State preserved
assert_eq!(cusum.upper(), upper_before);
assert_eq!(cusum.count(), count_before);
}
#[test]
fn reconfigure_validates() {
let mut cusum = CusumF64::builder(100.0)
.slack(5.0)
.threshold(50.0)
.build()
.unwrap();
assert!(cusum.reconfigure(100.0, -1.0, 0.0, 1.0, 1.0).is_err());
assert!(cusum.reconfigure(100.0, 0.0, -1.0, 1.0, 1.0).is_err());
assert!(cusum.reconfigure(100.0, 0.0, 0.0, 0.0, 1.0).is_err());
assert!(cusum.reconfigure(100.0, 0.0, 0.0, 1.0, 0.0).is_err());
}
#[test]
fn i128_basic() {
let mut cusum = CusumI128::builder(100)
.slack(5)
.threshold(50)
.build()
.unwrap();
assert_eq!(cusum.update(100), Some(Direction::Neutral));
}
#[test]
fn integer_default_slack_floor() {
// target=10, 10/20 = 0 would truncate, but floor is 1
// Ensures at least 1 unit of noise tolerance for integer types
let cusum = CusumI64::builder(10).threshold(5).build().unwrap();
assert_eq!(cusum.slack_upper(), 1);
assert_eq!(cusum.slack_lower(), 1);
// Larger target: 100/20 = 5, no floor needed
let cusum = CusumI64::builder(100).threshold(50).build().unwrap();
assert_eq!(cusum.slack_upper(), 5);
}
}