Skip to main content

anofox_forecast/monitor/
sequential.rs

1//! Sequential CUSUM detector for monitoring forecast errors.
2//!
3//! Port of `cptSeqCUSUM` / `updateForecast` from the R package
4//! [`changepoint.forecast`](https://github.com/grundy95/changepoint.forecast)
5//! by Thomas Grundy (Lancaster University), MIT License.
6//!
7//! The detector consumes a stream of forecast errors, treats the first `m`
8//! observations as a training window that defines the "healthy" mean and
9//! variance, and then monitors the CUSUM of subsequent errors against a
10//! time-varying threshold. The first index where the CUSUM crosses the
11//! threshold is the detection time `τ`.
12//!
13//! See [Fremdt (2014)](https://doi.org/10.1080/02331888.2014.921899) for the
14//! Page's CUSUM detector and the asymptotic limit distributions.
15
16use super::sequential_crit::{simulate_critical_value, CriticalValue};
17use super::sequential_table::lookup_critical_value;
18use crate::core::TimeSeries;
19use crate::error::{ForecastError, Result};
20use crate::models::Forecaster;
21use crate::utils::cross_validation::{rolling_forecast, RollingForecastConfig};
22
23// ---------------------------------------------------------------------------
24// Core enums
25// ---------------------------------------------------------------------------
26
27/// Which CUSUM detector to use.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub enum Detector {
31    /// Original CUSUM, two-sided alternative.
32    ///
33    /// `cusum_k = |Σ_{i=1}^{k} (X_{m+i} − μ̂_m)|`.
34    Cusum,
35    /// Original CUSUM, one-sided alternative (detects positive drift).
36    ///
37    /// `cusum_k = Σ_{i=1}^{k} (X_{m+i} − μ̂_m)`.
38    Cusum1,
39    /// Page's CUSUM, two-sided alternative (recommended default).
40    ///
41    /// Runs two running maxima and takes the maximum.
42    #[default]
43    PageCusum,
44    /// Page's CUSUM, one-sided alternative.
45    PageCusum1,
46}
47
48/// Which transformation of the errors to monitor.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51pub enum ForecastErrorType {
52    /// Monitor the raw errors only (detects mean changes).
53    Raw,
54    /// Monitor the centred squared errors only (detects variance changes).
55    Squared,
56    /// Monitor both streams in parallel (default).
57    #[default]
58    Both,
59}
60
61// ---------------------------------------------------------------------------
62// Weight function
63// ---------------------------------------------------------------------------
64
65/// Weight function used to rescale the detector threshold over time.
66///
67/// `w(m, k, γ) = √m · (1 + k/m) · (k / (k + m))^γ` with `0 ≤ γ < 0.5`.
68///
69/// Ports `weightFun` from R. Larger `γ` pushes detection earlier at the cost
70/// of a higher false-alarm rate near the start of monitoring.
71#[inline]
72pub fn weight(m: usize, k: usize, gamma: f64) -> f64 {
73    let m_f = m as f64;
74    let k_f = k as f64;
75    m_f.sqrt() * (1.0 + k_f / m_f) * (k_f / (k_f + m_f)).powf(gamma)
76}
77
78// ---------------------------------------------------------------------------
79// Configuration
80// ---------------------------------------------------------------------------
81
82/// Configuration for a [`SequentialDetector`].
83#[derive(Debug, Clone)]
84#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
85pub struct SequentialConfig {
86    /// Length of the training window (the first `m` errors are assumed
87    /// changepoint-free and define the baseline mean/variance).
88    pub m: usize,
89    /// Which CUSUM detector to use. Default: `PageCusum`.
90    pub detector: Detector,
91    /// Which error transformation(s) to monitor. Default: `Both`.
92    pub error_type: ForecastErrorType,
93    /// Weight-function tuning parameter, `0 ≤ γ < 0.5`. Default: `0.0`.
94    pub gamma: f64,
95    /// Nominal type-I error rate in `(0, 1)`. Default: `0.05`.
96    pub alpha: f64,
97    /// How to obtain the critical value. Default: `Lookup` (consult the
98    /// baked table; fall through to simulation when off-grid).
99    pub critical_value: CriticalValue,
100    /// Optional override for the training-window variance.
101    ///
102    /// R uses `var(X[1:m])` which assumes independence. For autocorrelated
103    /// residuals, pass a long-run variance estimate via
104    /// [`SequentialConfig::with_sigma2`].
105    pub sigma2: Option<f64>,
106}
107
108impl Default for SequentialConfig {
109    fn default() -> Self {
110        Self {
111            m: 50,
112            detector: Detector::default(),
113            error_type: ForecastErrorType::default(),
114            gamma: 0.0,
115            alpha: 0.05,
116            critical_value: CriticalValue::default(),
117            sigma2: None,
118        }
119    }
120}
121
122impl SequentialConfig {
123    /// Create a configuration with training-window length `m`.
124    pub fn new(m: usize) -> Self {
125        Self {
126            m,
127            ..Default::default()
128        }
129    }
130
131    /// Set the training-window length.
132    pub fn m(mut self, m: usize) -> Self {
133        self.m = m;
134        self
135    }
136
137    /// Set the detector.
138    pub fn detector(mut self, detector: Detector) -> Self {
139        self.detector = detector;
140        self
141    }
142
143    /// Set the error transformation.
144    pub fn error_type(mut self, error_type: ForecastErrorType) -> Self {
145        self.error_type = error_type;
146        self
147    }
148
149    /// Set the weight-function tuning parameter.
150    pub fn gamma(mut self, gamma: f64) -> Self {
151        self.gamma = gamma;
152        self
153    }
154
155    /// Set the nominal type-I error rate.
156    pub fn alpha(mut self, alpha: f64) -> Self {
157        self.alpha = alpha;
158        self
159    }
160
161    /// Set how the critical value is obtained.
162    pub fn critical_value(mut self, cv: CriticalValue) -> Self {
163        self.critical_value = cv;
164        self
165    }
166
167    /// Override the training-window variance.
168    ///
169    /// Use this when the forecast-error series has non-trivial
170    /// autocorrelation and you have a long-run variance estimate
171    /// (Newey–West, HAC, etc.).
172    pub fn with_sigma2(mut self, sigma2: f64) -> Self {
173        self.sigma2 = Some(sigma2);
174        self
175    }
176
177    fn validate(&self, n: usize) -> Result<()> {
178        if self.m < 2 || self.m >= n {
179            return Err(ForecastError::InvalidParameter(format!(
180                "training-window length m must satisfy 2 ≤ m < n (got m={}, n={})",
181                self.m, n
182            )));
183        }
184        if !(0.0..0.5).contains(&self.gamma) {
185            return Err(ForecastError::InvalidParameter(format!(
186                "gamma must be in [0, 0.5), got {}",
187                self.gamma
188            )));
189        }
190        if !(0.0..=1.0).contains(&self.alpha) {
191            return Err(ForecastError::InvalidParameter(format!(
192                "alpha must be in [0, 1], got {}",
193                self.alpha
194            )));
195        }
196        if let Some(s2) = self.sigma2 {
197            if !(s2.is_finite() && s2 > 0.0) {
198                return Err(ForecastError::InvalidParameter(format!(
199                    "sigma2 override must be a positive finite number, got {}",
200                    s2
201                )));
202            }
203        }
204        Ok(())
205    }
206}
207
208// ---------------------------------------------------------------------------
209// Detector state
210// ---------------------------------------------------------------------------
211
212/// Per-stream detector state (raw or squared errors).
213#[derive(Debug, Clone)]
214#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
215pub struct StreamState {
216    /// Sample mean of the training window.
217    pub train_mean: f64,
218    /// Sample variance used in the threshold (sample var on training window
219    /// unless overridden).
220    pub sigma2: f64,
221    /// Critical value for the chosen `(detector, gamma, alpha)`.
222    pub crit_value: f64,
223    /// Running CUSUM value for one-sided detectors, or the "upper" arm of
224    /// Page's two-sided detector.
225    pub cusum_a: f64,
226    /// "Lower" arm of Page's two-sided detector. Unused for the one-sided
227    /// variants.
228    pub cusum_b: f64,
229    /// History of CUSUM values emitted so far (one per monitored error).
230    pub cusum: Vec<f64>,
231    /// History of threshold values (matches `cusum` in length).
232    pub threshold: Vec<f64>,
233    /// Index (1-based, relative to the start of monitoring) of the first
234    /// exceedance, or `None` if the detector has not fired.
235    pub tau: Option<usize>,
236}
237
238impl StreamState {
239    /// Number of errors this stream has processed (post-training).
240    pub fn len(&self) -> usize {
241        self.cusum.len()
242    }
243
244    /// `true` if no errors have been processed yet.
245    pub fn is_empty(&self) -> bool {
246        self.cusum.is_empty()
247    }
248}
249
250/// Sequential CUSUM detector over a stream of forecast errors.
251#[derive(Debug, Clone)]
252#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
253pub struct SequentialDetector {
254    /// Configuration snapshot.
255    pub config: SequentialConfig,
256    /// Sample mean of the raw training window. Used to re-centre new errors
257    /// before feeding them into the squared stream during online updates.
258    pub train_mean_raw: f64,
259    /// Raw-error stream (present unless `error_type == Squared`).
260    pub raw: Option<StreamState>,
261    /// Squared-error stream (present if `error_type` is `Squared` or `Both`).
262    pub squared: Option<StreamState>,
263}
264
265impl SequentialConfig {
266    fn resolve_crit_value(&self) -> f64 {
267        match self.critical_value {
268            CriticalValue::Fixed(v) => v,
269            CriticalValue::Lookup => {
270                if let Some(v) = lookup_critical_value(self.detector, self.gamma, self.alpha) {
271                    v
272                } else {
273                    // Off-grid: fall through to simulation with a moderate
274                    // budget so the user gets a reasonable threshold without
275                    // configuring anything.
276                    simulate_critical_value(
277                        self.detector,
278                        self.gamma,
279                        self.alpha,
280                        2000,
281                        500,
282                        Some(42),
283                    )
284                }
285            }
286            CriticalValue::Simulate {
287                samples,
288                npts,
289                seed,
290            } => {
291                simulate_critical_value(self.detector, self.gamma, self.alpha, samples, npts, seed)
292            }
293        }
294    }
295}
296
297// ---------------------------------------------------------------------------
298// Public API
299// ---------------------------------------------------------------------------
300
301impl SequentialDetector {
302    /// Fit the detector on a complete error vector.
303    ///
304    /// The first `config.m` values define the training window; the remainder
305    /// are processed through the detector in order. If the detector crosses
306    /// its threshold, `tau` is set to the earliest exceedance index.
307    pub fn fit(errors: &[f64], config: SequentialConfig) -> Result<Self> {
308        if errors.is_empty() {
309            return Err(ForecastError::EmptyData);
310        }
311        if errors.iter().any(|v| !v.is_finite()) {
312            return Err(ForecastError::MissingValues);
313        }
314        config.validate(errors.len())?;
315
316        let train = &errors[..config.m];
317        let train_mean = mean(train);
318
319        // Raw stream
320        let raw = if matches!(
321            config.error_type,
322            ForecastErrorType::Raw | ForecastErrorType::Both
323        ) {
324            let sigma2 = config
325                .sigma2
326                .unwrap_or_else(|| sample_variance(train).max(f64::MIN_POSITIVE));
327            let crit_value = config.resolve_crit_value();
328            let mut state = StreamState {
329                train_mean,
330                sigma2,
331                crit_value,
332                cusum_a: 0.0,
333                cusum_b: 0.0,
334                cusum: Vec::new(),
335                threshold: Vec::new(),
336                tau: None,
337            };
338            run_stream(&mut state, &errors[config.m..], 0, &config);
339            Some(state)
340        } else {
341            None
342        };
343
344        // Squared stream uses centred squared errors: (e − train_mean)^2.
345        let squared = if matches!(
346            config.error_type,
347            ForecastErrorType::Squared | ForecastErrorType::Both
348        ) {
349            let sq_train: Vec<f64> = train.iter().map(|&e| (e - train_mean).powi(2)).collect();
350            let sq_train_mean = mean(&sq_train);
351            let sigma2 = config
352                .sigma2
353                .unwrap_or_else(|| sample_variance(&sq_train).max(f64::MIN_POSITIVE));
354            let crit_value = config.resolve_crit_value();
355            let mut state = StreamState {
356                train_mean: sq_train_mean,
357                sigma2,
358                crit_value,
359                cusum_a: 0.0,
360                cusum_b: 0.0,
361                cusum: Vec::new(),
362                threshold: Vec::new(),
363                tau: None,
364            };
365            let sq_stream: Vec<f64> = errors[config.m..]
366                .iter()
367                .map(|&e| (e - train_mean).powi(2))
368                .collect();
369            run_stream(&mut state, &sq_stream, 0, &config);
370            Some(state)
371        } else {
372            None
373        };
374
375        Ok(Self {
376            config,
377            train_mean_raw: train_mean,
378            raw,
379            squared,
380        })
381    }
382
383    /// Feed additional errors into the detector.
384    ///
385    /// Continues the CUSUM stream from its current state without re-examining
386    /// the training window — this is the online path used in production
387    /// monitoring. Passing an empty slice is a no-op.
388    pub fn update(&mut self, new_errors: &[f64]) -> Result<()> {
389        if new_errors.is_empty() {
390            return Ok(());
391        }
392        if new_errors.iter().any(|v| !v.is_finite()) {
393            return Err(ForecastError::MissingValues);
394        }
395
396        if let Some(state) = self.raw.as_mut() {
397            let offset = state.len();
398            run_stream(state, new_errors, offset, &self.config);
399        }
400
401        if let Some(state) = self.squared.as_mut() {
402            let offset = state.len();
403            let sq: Vec<f64> = new_errors
404                .iter()
405                .map(|&e| (e - self.train_mean_raw).powi(2))
406                .collect();
407            run_stream(state, &sq, offset, &self.config);
408        }
409
410        Ok(())
411    }
412
413    /// First detection in the raw stream (1-based index relative to monitoring start).
414    pub fn tau(&self) -> Option<usize> {
415        self.raw.as_ref().and_then(|s| s.tau)
416    }
417
418    /// First detection in the squared stream (1-based index relative to monitoring start).
419    pub fn tau_squared(&self) -> Option<usize> {
420        self.squared.as_ref().and_then(|s| s.tau)
421    }
422
423    /// Earliest detection across all active streams.
424    pub fn first_detection(&self) -> Option<usize> {
425        match (self.tau(), self.tau_squared()) {
426            (Some(a), Some(b)) => Some(a.min(b)),
427            (Some(a), None) => Some(a),
428            (None, Some(b)) => Some(b),
429            (None, None) => None,
430        }
431    }
432
433    /// `true` if any active stream has flagged a changepoint.
434    pub fn has_detected(&self) -> bool {
435        self.first_detection().is_some()
436    }
437
438    /// Full CUSUM history of the raw stream.
439    pub fn cusum(&self) -> &[f64] {
440        self.raw.as_ref().map(|s| s.cusum.as_slice()).unwrap_or(&[])
441    }
442
443    /// Full threshold history of the raw stream.
444    pub fn threshold(&self) -> &[f64] {
445        self.raw
446            .as_ref()
447            .map(|s| s.threshold.as_slice())
448            .unwrap_or(&[])
449    }
450
451    /// Full CUSUM history of the squared stream.
452    pub fn cusum_squared(&self) -> &[f64] {
453        self.squared
454            .as_ref()
455            .map(|s| s.cusum.as_slice())
456            .unwrap_or(&[])
457    }
458
459    /// Full threshold history of the squared stream.
460    pub fn threshold_squared(&self) -> &[f64] {
461        self.squared
462            .as_ref()
463            .map(|s| s.threshold.as_slice())
464            .unwrap_or(&[])
465    }
466}
467
468// ---------------------------------------------------------------------------
469// Forecaster integration helpers
470// ---------------------------------------------------------------------------
471
472/// Monitor a fitted forecaster's **in-sample residuals**.
473///
474/// Cheap but biased: because the model was trained on the same observations,
475/// the sample variance of its fitted residuals understates the true one-step
476/// innovation variance, so the detector runs slightly hotter than its nominal
477/// `alpha`. Prefer [`monitor_forecaster_cv`] when calibrated false-alarm
478/// rates matter.
479///
480/// Leading non-finite residuals (e.g. `NaN` warmup values that `Naive` and
481/// other models emit before they have a prior observation to subtract from)
482/// are skipped automatically. An interior `NaN` after the warmup region is
483/// still treated as an error.
484pub fn monitor_forecaster(
485    fc: &dyn Forecaster,
486    config: SequentialConfig,
487) -> Result<SequentialDetector> {
488    let residuals = fc.residuals().ok_or_else(|| ForecastError::FitRequired {
489        model: Some(fc.name().to_string()),
490    })?;
491    let first = residuals
492        .iter()
493        .position(|v| v.is_finite())
494        .ok_or(ForecastError::EmptyData)?;
495    SequentialDetector::fit(&residuals[first..], config)
496}
497
498/// Monitor a forecaster's **out-of-sample residuals** via rolling-origin CV.
499///
500/// Uses [`rolling_forecast`] under the hood to produce one-step-ahead
501/// forecast errors at every origin, then runs the sequential detector over
502/// the concatenated residual stream. This gives the detector an unbiased
503/// estimate of the innovation variance and calibrates the nominal `alpha`.
504///
505/// # Arguments
506/// * `factory` — creates a fresh unfitted forecaster for each window
507/// * `series` — the full series to evaluate on
508/// * `config` — sequential detector configuration (note: `config.m` is the
509///   training window *inside the residual stream*, not the CV's
510///   `initial_train_size`)
511/// * `cv_initial_train_size` — first training-window length for the CV
512/// * `cv_horizon` — forecast horizon at each CV origin (typically 1 for
513///   one-step residuals, which is what the detector expects)
514pub fn monitor_forecaster_cv<F, Factory>(
515    factory: Factory,
516    series: &TimeSeries,
517    config: SequentialConfig,
518    cv_initial_train_size: usize,
519    cv_horizon: usize,
520) -> Result<SequentialDetector>
521where
522    F: Forecaster + Send,
523    Factory: Fn() -> F + Sync,
524{
525    let cv_config =
526        RollingForecastConfig::new(cv_initial_train_size, cv_horizon).step_size(cv_horizon);
527    let result = rolling_forecast(series, &cv_config, factory)?;
528    let residuals: Vec<f64> = result
529        .all_actuals
530        .iter()
531        .zip(result.all_predictions.iter())
532        .map(|(a, p)| a - p)
533        .collect();
534    SequentialDetector::fit(&residuals, config)
535}
536
537// ---------------------------------------------------------------------------
538// Internals
539// ---------------------------------------------------------------------------
540
541#[inline]
542fn mean(xs: &[f64]) -> f64 {
543    if xs.is_empty() {
544        0.0
545    } else {
546        xs.iter().sum::<f64>() / xs.len() as f64
547    }
548}
549
550/// Sample variance with Bessel's correction; matches R's `var()`.
551#[inline]
552fn sample_variance(xs: &[f64]) -> f64 {
553    let n = xs.len();
554    if n < 2 {
555        return 0.0;
556    }
557    let m = mean(xs);
558    let sum_sq: f64 = xs.iter().map(|x| (x - m).powi(2)).sum();
559    sum_sq / (n - 1) as f64
560}
561
562/// Run the detector recurrence over `new_errors` for a single stream.
563///
564/// `offset` is the number of errors already processed by this stream — used
565/// to compute the weight-function index `k` for each new observation.
566fn run_stream(
567    state: &mut StreamState,
568    new_errors: &[f64],
569    offset: usize,
570    config: &SequentialConfig,
571) {
572    let mean = state.train_mean;
573    let m = config.m;
574    let gamma = config.gamma;
575    let sigma = state.sigma2.sqrt();
576    let crit = state.crit_value;
577    let scale = crit * sigma;
578
579    state.cusum.reserve(new_errors.len());
580    state.threshold.reserve(new_errors.len());
581
582    for (i, &x) in new_errors.iter().enumerate() {
583        let k = offset + i + 1; // 1-based index into the monitoring stream
584        let value = match config.detector {
585            Detector::PageCusum => {
586                state.cusum_a = (state.cusum_a + x - mean).max(0.0);
587                state.cusum_b = (state.cusum_b - x + mean).max(0.0);
588                state.cusum_a.max(state.cusum_b)
589            }
590            Detector::PageCusum1 => {
591                state.cusum_a = (state.cusum_a + x - mean).max(0.0);
592                state.cusum_a
593            }
594            Detector::Cusum => {
595                state.cusum_a += x - mean;
596                state.cusum_a.abs()
597            }
598            Detector::Cusum1 => {
599                state.cusum_a += x - mean;
600                state.cusum_a
601            }
602        };
603
604        let w = weight(m, k, gamma);
605        let thr = w * scale;
606
607        state.cusum.push(value);
608        state.threshold.push(thr);
609
610        if state.tau.is_none() && value > thr {
611            state.tau = Some(k);
612        }
613    }
614}
615
616// ---------------------------------------------------------------------------
617// Tests
618// ---------------------------------------------------------------------------
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623    use approx::assert_relative_eq;
624    use rand::rngs::StdRng;
625    use rand::{Rng, SeedableRng};
626
627    fn rng(seed: u64) -> StdRng {
628        StdRng::seed_from_u64(seed)
629    }
630
631    fn normal_sample<R: Rng>(rng: &mut R, mean: f64, sd: f64) -> f64 {
632        let u1: f64 = rng.gen::<f64>().max(f64::MIN_POSITIVE);
633        let u2: f64 = rng.gen();
634        mean + sd * (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos()
635    }
636
637    #[test]
638    fn weight_at_k_zero_is_sqrt_m() {
639        // w(m, 0, γ) = √m · 1 · 0^γ = 0 for γ>0, √m for γ=0
640        assert_relative_eq!(weight(100, 0, 0.0), 10.0, epsilon = 1e-10);
641        assert_relative_eq!(weight(100, 0, 0.25), 0.0, epsilon = 1e-10);
642    }
643
644    #[test]
645    fn weight_scaling() {
646        // w(m, m, 0) = √m · 2 · 0.5^0 = 2√m
647        assert_relative_eq!(weight(100, 100, 0.0), 20.0, epsilon = 1e-10);
648    }
649
650    #[test]
651    fn fit_empty_errors_rejects() {
652        let err = SequentialDetector::fit(&[], SequentialConfig::new(5)).unwrap_err();
653        assert_eq!(err, ForecastError::EmptyData);
654    }
655
656    #[test]
657    fn fit_nan_rejects() {
658        let errors = vec![0.0, 1.0, f64::NAN, 0.5, 1.0, 2.0];
659        let err = SequentialDetector::fit(&errors, SequentialConfig::new(3)).unwrap_err();
660        assert_eq!(err, ForecastError::MissingValues);
661    }
662
663    #[test]
664    fn fit_rejects_m_too_large() {
665        let errors: Vec<f64> = (0..10).map(|i| i as f64).collect();
666        let err = SequentialDetector::fit(&errors, SequentialConfig::new(10)).unwrap_err();
667        assert!(matches!(err, ForecastError::InvalidParameter(_)));
668    }
669
670    #[test]
671    fn no_change_series_tau_none() {
672        let mut rng = rng(1);
673        let errors: Vec<f64> = (0..500)
674            .map(|_| normal_sample(&mut rng, 0.0, 1.0))
675            .collect();
676        let cfg = SequentialConfig::new(200)
677            .detector(Detector::PageCusum)
678            .error_type(ForecastErrorType::Raw)
679            .critical_value(CriticalValue::Simulate {
680                samples: 2000,
681                npts: 500,
682                seed: Some(1),
683            });
684        let det = SequentialDetector::fit(&errors, cfg).unwrap();
685        // With α=0.05 and n=300 post-training observations, the detector
686        // *may* trigger a false alarm ~5% of the time. Seed 1 is benign.
687        assert!(
688            !det.has_detected(),
689            "unexpected detection at τ={:?}",
690            det.first_detection()
691        );
692    }
693
694    #[test]
695    fn page_cusum_detects_mean_shift() {
696        let mut rng = rng(11);
697        let mut errors: Vec<f64> = (0..400)
698            .map(|_| normal_sample(&mut rng, 0.0, 1.0))
699            .collect();
700        errors.extend((0..100).map(|_| normal_sample(&mut rng, 2.0, 1.0)));
701        let cfg = SequentialConfig::new(300)
702            .detector(Detector::PageCusum)
703            .error_type(ForecastErrorType::Raw)
704            .critical_value(CriticalValue::Simulate {
705                samples: 2000,
706                npts: 500,
707                seed: Some(1),
708            });
709        let det = SequentialDetector::fit(&errors, cfg).unwrap();
710        let tau = det.tau().expect("detector should fire");
711        // Shift starts at monitoring index 101 (400 - 300 + 1).
712        assert!(
713            tau >= 101,
714            "tau={} fired before the injected shift (<101)",
715            tau
716        );
717        assert!(tau < 200, "tau={} fired too late after shift", tau);
718    }
719
720    #[test]
721    fn page_cusum_detects_variance_shift_via_squared_stream() {
722        let mut rng = rng(7);
723        let mut errors: Vec<f64> = (0..400)
724            .map(|_| normal_sample(&mut rng, 0.0, 1.0))
725            .collect();
726        errors.extend((0..100).map(|_| normal_sample(&mut rng, 0.0, 3.0)));
727
728        let cfg = SequentialConfig::new(300)
729            .error_type(ForecastErrorType::Both)
730            .critical_value(CriticalValue::Simulate {
731                samples: 2000,
732                npts: 500,
733                seed: Some(1),
734            });
735        let det = SequentialDetector::fit(&errors, cfg).unwrap();
736        let tau_sq = det
737            .tau_squared()
738            .expect("squared stream should catch variance shift");
739        assert!(tau_sq >= 101, "tau_squared fired before shift: {}", tau_sq);
740        assert!(tau_sq < 200, "tau_squared fired too late: {}", tau_sq);
741    }
742
743    /// The key invariant: online updates must be equivalent to a full fit.
744    #[test]
745    fn online_update_matches_full_fit_page_cusum() {
746        let mut rng = rng(21);
747        let mut errors: Vec<f64> = (0..200)
748            .map(|_| normal_sample(&mut rng, 0.0, 1.0))
749            .collect();
750        errors.extend((0..50).map(|_| normal_sample(&mut rng, 1.5, 1.0)));
751
752        let full_cfg = SequentialConfig::new(100)
753            .detector(Detector::PageCusum)
754            .error_type(ForecastErrorType::Raw)
755            .critical_value(CriticalValue::Fixed(3.0));
756
757        let full = SequentialDetector::fit(&errors, full_cfg.clone()).unwrap();
758
759        // Online: fit on first 180 then update with remaining 70.
760        let mut online = SequentialDetector::fit(&errors[..180], full_cfg).unwrap();
761        online.update(&errors[180..]).unwrap();
762
763        let a = full.cusum();
764        let b = online.cusum();
765        assert_eq!(a.len(), b.len());
766        for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
767            assert_relative_eq!(*x, *y, epsilon = 1e-10, max_relative = 1e-10);
768            let _ = i;
769        }
770        assert_eq!(full.tau(), online.tau());
771    }
772
773    #[test]
774    fn online_update_matches_full_fit_cusum1() {
775        let mut rng = rng(33);
776        let errors: Vec<f64> = (0..250)
777            .map(|_| normal_sample(&mut rng, 0.0, 1.0))
778            .collect();
779
780        let cfg = SequentialConfig::new(100)
781            .detector(Detector::Cusum1)
782            .error_type(ForecastErrorType::Raw)
783            .critical_value(CriticalValue::Fixed(3.0));
784
785        let full = SequentialDetector::fit(&errors, cfg.clone()).unwrap();
786        let mut online = SequentialDetector::fit(&errors[..175], cfg).unwrap();
787        online.update(&errors[175..]).unwrap();
788
789        assert_eq!(full.cusum().len(), online.cusum().len());
790        for (x, y) in full.cusum().iter().zip(online.cusum()) {
791            assert_relative_eq!(*x, *y, epsilon = 1e-10);
792        }
793    }
794
795    #[test]
796    fn fixed_critical_value_used_verbatim() {
797        let errors: Vec<f64> = (0..100).map(|i| (i as f64) * 0.01).collect();
798        let cfg = SequentialConfig::new(30)
799            .error_type(ForecastErrorType::Raw)
800            .critical_value(CriticalValue::Fixed(7.5));
801        let det = SequentialDetector::fit(&errors, cfg).unwrap();
802        assert_relative_eq!(det.raw.as_ref().unwrap().crit_value, 7.5, epsilon = 1e-12);
803    }
804
805    #[test]
806    fn sigma2_override_respected() {
807        let errors: Vec<f64> = (0..100).map(|i| i as f64).collect();
808        let cfg = SequentialConfig::new(30)
809            .error_type(ForecastErrorType::Raw)
810            .critical_value(CriticalValue::Fixed(1.0))
811            .with_sigma2(4.0);
812        let det = SequentialDetector::fit(&errors, cfg).unwrap();
813        assert_relative_eq!(det.raw.as_ref().unwrap().sigma2, 4.0, epsilon = 1e-12);
814    }
815
816    #[test]
817    fn sample_variance_matches_r() {
818        // R: var(c(1, 2, 3, 4, 5)) = 2.5
819        assert_relative_eq!(
820            sample_variance(&[1.0, 2.0, 3.0, 4.0, 5.0]),
821            2.5,
822            epsilon = 1e-12
823        );
824    }
825}