diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b238b7..d788be0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,24 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ### Fixed +- Phase 5 transient detection scored each sample against a centred + 30-sample window, so a box or step entered its own baseline. With the + Phase 5 defaults, 0 of 200 boxes were detected at any amplitude up to + 1000 sigma. `transient_segments` now uses a trailing median/MAD baseline + with a guard gap (default `min_length`), freezes the baseline at onset, + and leaves detected samples out of later baselines. A segment opens after + `min_length` samples in a row beyond the threshold and closes when most + of the next `min_length` samples are back inside; NaN samples are + skipped. Samples with fewer than 15 trailing samples (the first 22 with + the defaults) are not scored. A 10 sigma box is detected in 200 of 200 + draws; white noise gives no segment in 200 draws. A `UserWarning` is + issued when the residual lag-1 autocorrelation outside the segments + exceeds 0.3. `ljung_box_test` and `detect_anomalies` accept `n_fitted`. + `AnomalyReport.to_dict` now includes `metadata`. `transient_segments` now + requires `rolling_window >= 2` (it raises `ValueError` for 1) and integer + `min_length`, `rolling_window` and `guard`, and `ljung_box_test` requires integer `n_fitted` (both raise + `TypeError` otherwise). `rolling_zscore` is unchanged. (C4) + - Enlarge the calibration table, preserve nonzero Monte Carlo standard errors, correct abstract percent formatting, and keep the running title within the page margin. (FIG-03, FMT-01) diff --git a/KNOWN_ISSUES.md b/KNOWN_ISSUES.md index 57e6f92..b3b4d72 100644 --- a/KNOWN_ISSUES.md +++ b/KNOWN_ISSUES.md @@ -128,3 +128,35 @@ matrix size manageable. If you pass a model whose last layer is unrealistically thin (i.e., not actually a half-space), you will get unexpected truncation. Always make the last layer thick (~50 km is conventional in the example configs). + +--- + +## Phase 5 transient threshold assumes independent residuals + +`anomaly.detection.transient_segments` flags runs of at least 7 samples +beyond 3 sigma of a trailing median/MAD baseline. The threshold is fixed. +It holds for white residuals: no segment in 200 white-noise series of +600 or 2920 samples. It over-flags correlated residuals: 600-sample AR(1) +series with no transient are flagged in 2 of 200 draws at phi 0.5 and in +115 of 200 at phi 0.8 (seed 12345). The centred detector it replaced +flagged none of these, because it could not detect anything. Daily dv/v +residuals are often this correlated, so a default Phase 5 run on them +will report noise as transients, with only the warning to say so. The +detector warns when the lag-1 autocorrelation outside the detected +segments exceeds 0.3. It does not yet calibrate the threshold +empirically, for example by a block bootstrap of pre-event residuals. +Until it does, treat segments from correlated residuals as candidates. + +## Phase 5 cannot test the first samples of a record + +`transient_segments` needs 15 samples of history (`rolling_window // 2`) +that end `guard` samples (7) before the sample under test, so the first +22 samples of a gap-free series are not scored. A transient that starts +between samples 15 and 22 is reported from sample 22. One that starts +before sample 15 fills the first baseline and is taken as the reference +level: a step there is not detected, and the end of a box there is +reported as a transient of the opposite sign that runs to the end of the +record. + +A 5 sigma step mid-record is still missed in 3 to 5 % of draws and split +in two in 2 to 4 % (seed 12, 100 draws; seed 2026, 200 draws). diff --git a/docs/workflow.md b/docs/workflow.md index 2fdaaf2..b823c88 100644 --- a/docs/workflow.md +++ b/docs/workflow.md @@ -111,8 +111,14 @@ v0.2. **Input:** Phase 4 residuals. -**Computation:** Ljung–Box whiteness test (default 30 lags), rolling -z-score transient detection, and a structured anomaly report. +**Computation:** Ljung–Box whiteness test (default 20 lags), transient +detection, and a structured anomaly report. A transient is a run of at +least 7 samples more than 3 sigma from a trailing baseline: the median of +the previous 30 samples, with a MAD scale, ending 7 samples before the +sample under test. The segment closes when most of the next 7 samples +are back inside 3 sigma; the first 22 samples are not scored. A warning is issued when the residual lag-1 +autocorrelation outside the detected segments exceeds 0.3, because the +fixed threshold then over-flags. **Output:** `AnomalyReport` containing the whiteness p-value, transient segments, and a dict serialisable to JSON. diff --git a/src/codameter/anomaly/detection.py b/src/codameter/anomaly/detection.py index 5525be5..9edb135 100644 --- a/src/codameter/anomaly/detection.py +++ b/src/codameter/anomaly/detection.py @@ -7,8 +7,13 @@ p-value (e.g. <0.01) indicates that the residual contains structure the forward model failed to capture. 2. **Transient detection** — segments of contiguous samples where the - rolling z-score of the residual exceeds a threshold (default 3 sigma) for - a minimum duration (default 7 samples). Each segment is summarised by + residual departs from a trailing robust baseline by more than a + threshold (default 3 sigma) for a minimum duration (default 7 samples). + The baseline is the median of the previous ``rolling_window`` samples, + with a MAD scale, and it stops ``guard`` samples before the sample + under test. A segment closes when most of the next ``min_length`` + samples are back inside the threshold. Samples inside a detected + segment are left out of later baselines. Each segment is summarised by onset time, amplitude, and duration. Outputs are bundled in :class:`AnomalyReport`, which also records the @@ -23,6 +28,9 @@ """ from __future__ import annotations +import math +import operator +import warnings from dataclasses import dataclass, field from typing import Any @@ -30,6 +38,24 @@ import pandas as pd from scipy import stats +#: Factor converting a median absolute deviation to a Gaussian sigma. +_MAD_TO_SIGMA = 1.4826 + +#: Lag-1 residual autocorrelation above which :func:`transient_segments` +#: warns that a fixed z threshold over-flags. With the defaults, 600-sample +#: AR(1) series with no transient are flagged in 2 of 200 draws at +#: phi = 0.5 and in 115 of 200 draws at phi = 0.8 (seed 12345). +LAG1_AUTOCORR_WARN = 0.3 + + +def _json_value(v: Any) -> Any: + """``v`` as a JSON-native value: numpy scalars to Python, NaN to None.""" + if isinstance(v, np.generic): + v = v.item() + if isinstance(v, float) and not math.isfinite(v): + return None + return v + @dataclass class TransientSegment: @@ -83,6 +109,7 @@ def to_dict(self) -> dict[str, Any]: } for t in self.transients ], + "metadata": {k: _json_value(v) for k, v in self.metadata.items()}, } @@ -90,13 +117,15 @@ def ljung_box_test( residuals: np.ndarray, *, n_lags: int = 20, + n_fitted: int = 0, ) -> tuple[float, float]: r"""Compute the Ljung-Box Q statistic and its p-value. .. math:: Q = n(n+2) \sum_{k=1}^{m} \frac{\hat\rho_k^2}{n-k} - Under :math:`H_0` (residuals are white), :math:`Q \sim \chi^2_m`. + Under :math:`H_0` (residuals are white), + :math:`Q \sim \chi^2_{m - n_{\rm fitted}}`. Parameters ---------- @@ -104,18 +133,29 @@ def ljung_box_test( 1-D residual series. n_lags Number of autocorrelation lags to include. + n_fitted + Number of time-series model parameters estimated from the series + itself, for example ``p + q`` for an ARMA(p, q) noise model + (Ljung & Box, 1978). The chi-square degrees of freedom are + ``n_lags - n_fitted``. Leave at 0 for residuals of a regression on + external forcings; the regression coefficients are not ARMA + parameters. Returns ------- (Q, pvalue) """ + n_fitted = _as_count("n_fitted", n_fitted) + if not 0 <= n_fitted < n_lags: + raise ValueError( + f"n_fitted must satisfy 0 <= n_fitted < n_lags ({n_lags}); " + f"got {n_fitted}" + ) r = np.asarray(residuals, dtype=float) r = r[np.isfinite(r)] n = len(r) if n < 2 * n_lags: - raise ValueError( - f"Need at least 2 * n_lags samples ({2 * n_lags}); got {n}" - ) + raise ValueError(f"Need at least 2 * n_lags samples ({2 * n_lags}); got {n}") r = r - r.mean() var = np.dot(r, r) if var == 0: @@ -125,7 +165,7 @@ def ljung_box_test( rho_k = float(np.dot(r[k:], r[:-k]) / var) Q += rho_k**2 / (n - k) Q *= n * (n + 2) - p = float(1.0 - stats.chi2.cdf(Q, df=n_lags)) + p = float(1.0 - stats.chi2.cdf(Q, df=n_lags - n_fitted)) return float(Q), p @@ -138,6 +178,11 @@ def rolling_zscore( """Rolling z-score: ``(x - mean_w) / std_w``. Edges are NaN-padded with the global stats. Handles all-zero windows. + + The window is centred, so a step or a box lasting more than a few + samples enters its own mean and standard deviation and its z-score + stays below 3. Do not use it to detect transients; + :func:`transient_segments` uses a trailing baseline instead. """ s = pd.Series(np.asarray(series, dtype=float)) if min_periods is None: @@ -150,51 +195,288 @@ def rolling_zscore( return ((s - mu) / sd).to_numpy() -def transient_segments( - residuals: np.ndarray | pd.Series, +def _robust_location_scale(x: np.ndarray) -> tuple[float, float]: + """Median and MAD-based sigma of the finite samples of ``x``. + + The scale falls back to the standard deviation, then to 1.0, when the + MAD is zero. + """ + x = x[np.isfinite(x)] + if x.size == 0: + return 0.0, 1.0 + med = float(np.median(x)) + scale = _MAD_TO_SIGMA * float(np.median(np.abs(x - med))) + if not scale > 0: + scale = float(np.std(x)) if x.size > 1 else 0.0 + return med, (scale if scale > 0 else 1.0) + + +def _trailing_baseline( + x: np.ndarray, + clean: np.ndarray, *, - z_threshold: float = 3.0, - min_length: int = 7, - rolling_window: int = 30, - timestamps: pd.DatetimeIndex | None = None, -) -> list[TransientSegment]: - """Find contiguous excursions above ``z_threshold`` lasting at least - ``min_length`` samples. + window: int, + guard: int, + min_periods: int, + fallback_scale: float, +) -> tuple[np.ndarray, np.ndarray]: + """Trailing median and MAD-sigma for every sample of ``x``. - Each excursion is summarised as a :class:`TransientSegment`. Adjacent - segments of the same sign are not merged (their boundaries are kept as - detected); merging is left to the user since it depends on the physical - process being attributed. + The baseline of sample ``k`` is built from the last ``window`` samples + with ``clean`` True and index ``<= k - guard - 1``. Where fewer than + ``min_periods`` such samples exist, the median and scale are NaN and + the sample is not scored. A zero MAD is replaced by ``fallback_scale``. """ - r = np.asarray(residuals, dtype=float) - z = rolling_zscore(r, window=rolling_window) - above = np.abs(z) >= z_threshold + n = len(x) + idx = np.flatnonzero(clean) + y = x[idx] + m = len(y) + med_c = np.full(m, np.nan) + sc_c = np.full(m, np.nan) + # Partial windows at the start of the clean series. + for p in range(min(min_periods - 1, m), min(window - 1, m)): + w = y[: p + 1] + med_c[p] = np.median(w) + sc_c[p] = _MAD_TO_SIGMA * np.median(np.abs(w - med_c[p])) + # Full windows, vectorised. + if m >= window: + sw = np.lib.stride_tricks.sliding_window_view(y, window) + med_full = np.median(sw, axis=1) + med_c[window - 1 :] = med_full + sc_c[window - 1 :] = _MAD_TO_SIGMA * np.median( + np.abs(sw - med_full[:, None]), axis=1 + ) + # Number of clean samples with index <= k - guard - 1. + count = np.searchsorted(idx, np.arange(n) - guard, side="left") + med = np.full(n, np.nan) + scale = np.full(n, np.nan) + ok = count >= min_periods + med[ok] = med_c[count[ok] - 1] + scale[ok] = sc_c[count[ok] - 1] + scale[ok & ~(scale > 0)] = fallback_scale + return med, scale + + +def _lag1_autocorr(x: np.ndarray) -> float: + """Lag-1 sample autocorrelation of ``x``, ignoring non-finite samples. + + Only pairs of adjacent finite samples enter, so a gap does not join + the samples on either side of it. Deviations are taken from the mean + of all finite samples, and the lag-1 sum is divided by the root of the + two sums of squares over the same pairs, which keeps the value in + [-1, 1] however many samples the gaps remove. + """ + x = np.asarray(x, dtype=float) + ok = np.isfinite(x) + if ok.sum() < 3: + return float("nan") + d = np.where(ok, x - x[ok].mean(), 0.0) + pair = ok[1:] & ok[:-1] + lead, lag = d[1:][pair], d[:-1][pair] + den = float(np.sqrt(np.dot(lead, lead) * np.dot(lag, lag))) + if den == 0: + return 0.0 + return float(np.dot(lead, lag) / den) + + +def _background(r: np.ndarray, segments: list[TransientSegment]) -> np.ndarray: + """Copy of ``r`` with the samples of ``segments`` set to NaN.""" + bg = np.array(r, dtype=float) + for seg in segments: + bg[seg.onset_index : seg.end_index + 1] = np.nan + return bg + + +def _as_count(name: str, value: Any) -> int: + """``value`` as a Python int; floats and bools are rejected.""" + if isinstance(value, bool | np.bool_): + raise TypeError(f"{name} must be an integer; got {value!r}") + try: + return operator.index(value) + except TypeError: + raise TypeError(f"{name} must be an integer; got {value!r}") from None + + +def _warn_if_correlated(rho1: float, stacklevel: int) -> None: + """Warn when the background lag-1 autocorrelation is above the limit.""" + if rho1 > LAG1_AUTOCORR_WARN: + warnings.warn( + f"Residual lag-1 autocorrelation outside the detected segments " + f"is {rho1:.2f}, above {LAG1_AUTOCORR_WARN}. The fixed z " + "threshold assumes roughly independent samples and over-flags " + "transients in correlated residuals. Treat the segments as " + "candidates and calibrate the threshold on pre-event residuals.", + UserWarning, + stacklevel=stacklevel + 1, + ) + + +def _find_segments( + r: np.ndarray, + *, + z_threshold: float, + min_length: int, + rolling_window: int, + timestamps: pd.DatetimeIndex | None, + guard: int | None, +) -> tuple[list[TransientSegment], int, float]: + """Segments, the guard used and the background lag-1 autocorrelation. + + See :func:`transient_segments` for the algorithm. Issues no warning. + """ + min_length = _as_count("min_length", min_length) + rolling_window = _as_count("rolling_window", rolling_window) + guard = min_length if guard is None else _as_count("guard", guard) + if min_length < 1: + raise ValueError(f"min_length must be >= 1; got {min_length}") + if guard < 0: + raise ValueError(f"guard must be >= 0; got {guard}") + if rolling_window < 2: + raise ValueError(f"rolling_window must be >= 2; got {rolling_window}") + min_periods = max(rolling_window // 2, 2) + + fallback_scale = _robust_location_scale(r)[1] + clean = np.isfinite(r) + finite = np.flatnonzero(clean) + n_finite = len(finite) + n = len(r) + + def baseline() -> tuple[np.ndarray, np.ndarray, np.ndarray]: + med, scale = _trailing_baseline( + r, + clean, + window=rolling_window, + guard=guard, + min_periods=min_periods, + fallback_scale=fallback_scale, + ) + with np.errstate(invalid="ignore"): + above = np.abs(r - med) / scale >= z_threshold + return med, scale, above + + med, scale, above = baseline() segments: list[TransientSegment] = [] i = 0 - n = len(above) while i < n: if not above[i]: i += 1 continue - j = i - while j < n and above[j]: - j += 1 - if j - i >= min_length: - sub = r[i:j] - zsub = z[i:j] - i_peak = int(np.argmax(np.abs(zsub))) - seg = TransientSegment( + m0, s0 = med[i], scale[i] + sgn = 1.0 if r[i] > m0 else -1.0 + # Walk the finite samples from the onset; NaN samples are skipped. + # A sample beyond the threshold on the side of the onset extends + # the segment. The first min_length finite samples must all be + # beyond. After that, at a sample that is not, the segment + # continues only if most of the next min_length finite samples, + # that one included, are beyond. + p = int(np.searchsorted(finite, i)) + last = int(i) + n_beyond = 0 + while p < n_finite: + k = finite[p] + if sgn * (r[k] - m0) / s0 >= z_threshold: + last = int(k) + n_beyond += 1 + elif n_beyond < min_length: + break + else: + ahead = r[finite[p : p + min_length]] + n_ahead = int(np.count_nonzero(sgn * (ahead - m0) / s0 >= z_threshold)) + if 2 * n_ahead <= len(ahead): + break + p += 1 + if n_beyond < min_length: + i += 1 + continue + sub = r[i : last + 1] + zsub = (sub - m0) / s0 + i_peak = int(np.nanargmax(sgn * zsub)) + segments.append( + TransientSegment( onset_index=i, - end_index=j - 1, + end_index=last, onset_time=(timestamps[i] if timestamps is not None else None), - end_time=(timestamps[j - 1] if timestamps is not None else None), - duration_samples=int(j - i), + end_time=(timestamps[last] if timestamps is not None else None), + duration_samples=int(last - i + 1), peak_amplitude=float(sub[i_peak]), peak_zscore=float(zsub[i_peak]), - sign=int(np.sign(zsub[i_peak])), + sign=int(sgn), ) - segments.append(seg) - i = j + ) + clean[i : last + 1] = False + med, scale, above = baseline() + i = last + 1 + + rho1 = _lag1_autocorr(_background(r, segments)) + return segments, guard, rho1 + + +def transient_segments( + residuals: np.ndarray | pd.Series, + *, + z_threshold: float = 3.0, + min_length: int = 7, + rolling_window: int = 30, + timestamps: pd.DatetimeIndex | None = None, + guard: int | None = None, +) -> list[TransientSegment]: + """Find excursions beyond ``z_threshold`` lasting at least + ``min_length`` samples. + + Each sample is scored against a trailing robust baseline: the median + of the last ``rolling_window`` samples that end ``guard`` samples + before it, with sigma = 1.4826 * MAD. A candidate opens at the first + sample with ``|z| >= z_threshold``. Its baseline is then frozen, and + it becomes a segment once ``min_length`` samples in a row lie + ``z_threshold`` sigma from that baseline on the same side. After that, + at each sample that falls back inside the threshold (or crosses to the + other side), the next ``min_length`` finite samples, that one included + (fewer at the end of the series), are counted: the segment continues + if more than half of them are beyond the threshold on the side of the + onset, and otherwise closes at the last sample beyond it. With + ``min_length=7`` an isolated dip of up to 3 samples does not split one + event, while a dip of 4 or more closes the segment. NaN samples are + skipped: they neither open, extend nor close a segment. Samples of a + kept segment are left out of every later baseline, so the return to + the pre-event level after a box is not flagged as a second, opposite + transient. A permanent step is reported as one segment that runs to + the end of the series. + + A sample is scored only when at least ``max(rolling_window // 2, 2)`` + finite samples (15 with the defaults) precede it by more than + ``guard`` samples. With the defaults the first 22 samples of a gap-free + series are never scored. A transient that starts there is reported + from the first scored sample; one that starts before sample 15 fills + the first baseline and is not detected. + + The threshold assumes roughly independent samples. If the lag-1 + autocorrelation of the residual outside the detected segments exceeds + :data:`LAG1_AUTOCORR_WARN`, a ``UserWarning`` is issued: fixed + thresholds then over-flag, and the segments should be treated as + candidates and the threshold calibrated on pre-event residuals. + + Each excursion is summarised as a :class:`TransientSegment`. Separate + segments of the same sign are not merged; merging is left to the user + since it depends on the physical process being attributed. + + Parameters + ---------- + guard + Gap, in samples, between the sample under test and the end of its + baseline window. Defaults to ``min_length``, so that any shift + lasting ``min_length`` samples is tested against a baseline it + has not entered. + """ + r = np.asarray(residuals, dtype=float) + segments, _, rho1 = _find_segments( + r, + z_threshold=z_threshold, + min_length=min_length, + rolling_window=rolling_window, + timestamps=timestamps, + guard=guard, + ) + _warn_if_correlated(rho1, stacklevel=2) return segments @@ -205,6 +487,8 @@ def detect_anomalies( z_threshold: float = 3.0, min_transient_length: int = 7, rolling_window: int = 30, + guard: int | None = None, + n_fitted: int = 0, ) -> AnomalyReport: """Run whiteness + transient detection and bundle into a report. @@ -214,8 +498,10 @@ def detect_anomalies( Output of :class:`~codameter.inverse.LinearFitResult.residuals`. If a ``pandas.Series`` is passed, the index is used to label transient onset times. - n_lags, z_threshold, min_transient_length, rolling_window - Pass-through parameters to the underlying tests. + n_lags, z_threshold, min_transient_length, rolling_window, guard, n_fitted + Pass-through parameters to :func:`ljung_box_test` and + :func:`transient_segments`. ``guard`` defaults to + ``min_transient_length``. Returns ------- @@ -228,14 +514,17 @@ def detect_anomalies( ts = None r = np.asarray(residuals, dtype=float) - Q, p = ljung_box_test(r, n_lags=n_lags) - segments = transient_segments( + r = np.asarray(r, dtype=float) + Q, p = ljung_box_test(r, n_lags=n_lags, n_fitted=n_fitted) + segments, guard, rho1 = _find_segments( r, z_threshold=z_threshold, min_length=min_transient_length, rolling_window=rolling_window, timestamps=ts, + guard=guard, ) + _warn_if_correlated(rho1, stacklevel=2) report = AnomalyReport( whiteness_pvalue=p, whiteness_lags=n_lags, @@ -247,6 +536,10 @@ def detect_anomalies( "z_threshold": z_threshold, "min_transient_length": min_transient_length, "rolling_window": rolling_window, + "guard": guard, + "baseline": "trailing_median_mad", + "n_fitted": n_fitted, + "residual_lag1_autocorr": rho1, }, ) return report diff --git a/tests/test_anomaly_detection.py b/tests/test_anomaly_detection.py new file mode 100644 index 0000000..e92dbce --- /dev/null +++ b/tests/test_anomaly_detection.py @@ -0,0 +1,276 @@ +"""Phase 5 transient detector and Ljung-Box test. + +The detector used to score each sample against a centred rolling window. +A box or a step then entered its own mean and standard deviation, and with +the Phase 5 defaults no box was detected at any amplitude up to 1000 sigma. +These tests pin the trailing-baseline behaviour. +""" +from __future__ import annotations + +import json +import warnings + +import numpy as np +import pandas as pd +import pytest +from codameter.anomaly.detection import ( + _lag1_autocorr, + detect_anomalies, + ljung_box_test, + transient_segments, +) +from scipy import stats + +N_SAMPLES = 600 +ONSET = 300 + + +def _ar1(rng: np.random.Generator, phi: float, n: int) -> np.ndarray: + e = rng.standard_normal(n) + x = np.empty(n) + x[0] = e[0] / np.sqrt(1.0 - phi**2) + for k in range(1, n): + x[k] = phi * x[k - 1] + e[k] + return x + + +def _overlaps(seg, start: int, stop: int) -> bool: + return seg.onset_index < stop and seg.end_index >= start + + +class TestTransientSegments: + @pytest.mark.parametrize("length", [7, 30, 90]) + def test_ten_sigma_box_detected(self, length): + rng = np.random.default_rng(0) + for _ in range(50): + x = rng.standard_normal(N_SAMPLES) + x[ONSET : ONSET + length] += 10.0 + with warnings.catch_warnings(): + warnings.simplefilter("error") + segs = transient_segments(x) + hits = [s for s in segs if _overlaps(s, ONSET, ONSET + length)] + assert len(hits) == 1 + seg = hits[0] + assert seg.sign == 1 + assert abs(seg.onset_index - ONSET) <= 1 + assert abs(seg.duration_samples - length) <= 2 + assert seg.peak_zscore > 5.0 + + def test_no_opposite_segment_after_box(self): + """The return to the pre-event level is not a second transient.""" + rng = np.random.default_rng(1) + for _ in range(50): + x = rng.standard_normal(N_SAMPLES) + x[ONSET : ONSET + 90] += 10.0 + segs = transient_segments(x) + assert [s.sign for s in segs] == [1] + + def test_step_is_one_segment_to_the_end(self): + rng = np.random.default_rng(2) + x = rng.standard_normal(N_SAMPLES) + x[ONSET:] -= 10.0 + segs = transient_segments(x) + assert len(segs) == 1 + assert segs[0].sign == -1 + assert abs(segs[0].onset_index - ONSET) <= 1 + assert segs[0].end_index >= N_SAMPLES - 3 + + def test_white_noise_false_alarm_rate_bounded(self): + rng = np.random.default_rng(3) + flagged = 0 + for _ in range(200): + with warnings.catch_warnings(): + warnings.simplefilter("error") + segs = transient_segments(rng.standard_normal(N_SAMPLES)) + flagged += len(segs) > 0 + # Expected rate is far below 1 %; allow 2 of 200. + assert flagged <= 2 + + def test_nan_samples_do_not_break_detection(self): + rng = np.random.default_rng(4) + x = rng.standard_normal(N_SAMPLES) + x[ONSET : ONSET + 30] += 10.0 + x[100:110] = np.nan + segs = transient_segments(x) + assert len(segs) == 1 + assert abs(segs[0].onset_index - ONSET) <= 1 + + def test_autocorrelated_residual_warns(self): + rng = np.random.default_rng(5) + with pytest.warns(UserWarning, match="lag-1 autocorrelation outside"): + transient_segments(_ar1(rng, 0.8, N_SAMPLES)) + + @pytest.mark.parametrize("onset", [292, 876]) + def test_early_step_detected_with_correct_sign(self, onset): + """A step in the first third of a long record is found at its onset. + + Samples with a short history used to be scored against the median + of the whole series, which a step past mid-record sets to the + post-step level. The start of the record was then flagged with the + wrong sign and the step itself was never tested. + """ + rng = np.random.default_rng(9) + for _ in range(20): + x = rng.standard_normal(2920) + x[onset:] -= 10.0 + segs = transient_segments(x) + assert len(segs) == 1 + assert segs[0].sign == -1 + assert abs(segs[0].onset_index - onset) <= 1 + assert segs[0].end_index >= 2917 + + def test_short_history_is_not_scored(self): + """A step at sample 15 is reported from sample 22, never at 0.""" + rng = np.random.default_rng(10) + for _ in range(20): + x = rng.standard_normal(N_SAMPLES) + x[15:] += 10.0 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + segs = transient_segments(x) + assert len(segs) == 1 + assert segs[0].sign == 1 + assert segs[0].onset_index == 22 + + def test_nan_inside_box_does_not_split_it(self): + rng = np.random.default_rng(11) + for _ in range(20): + x = rng.standard_normal(N_SAMPLES) + x[ONSET : ONSET + 60] += 10.0 + x[ONSET + 30] = np.nan + segs = transient_segments(x) + assert len(segs) == 1 + assert abs(segs[0].onset_index - ONSET) <= 1 + assert segs[0].end_index >= ONSET + 58 + + def test_moderate_step_is_one_segment(self): + """A 5 sigma step is not split at each sample that dips inside.""" + rng = np.random.default_rng(12) + n_segments = [] + for _ in range(100): + x = rng.standard_normal(N_SAMPLES) + x[ONSET:] += 5.0 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + n_segments.append(len(transient_segments(x))) + counts = np.bincount(n_segments, minlength=3) + # Rerun at seed 12: 5 missed, 93 single, 2 split in two. + assert counts[1] >= 90 + assert max(n_segments) <= 2 + + @pytest.mark.parametrize("dip", [1, 3, 4, 6]) + def test_segment_closes_when_most_of_next_window_is_inside(self, dip): + """The docstring rule: with min_length 7, an isolated dip of up to + 3 samples back inside the threshold keeps one segment; a dip of 4 + or more (fewer than min_length in a row) closes it.""" + rng = np.random.default_rng(2026) + x = rng.standard_normal(N_SAMPLES) + x[ONSET : ONSET + 100] += 10.0 + x[ONSET + 40 : ONSET + 40 + dip] = 0.0 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + segs = transient_segments(x, min_length=7) + spans = [(s.onset_index, s.end_index) for s in segs] + if dip <= 3: + assert spans == [(ONSET, ONSET + 99)] + else: + assert spans == [(ONSET, ONSET + 39), (ONSET + 40 + dip, ONSET + 99)] + + def test_negative_guard_rejected(self): + with pytest.raises(ValueError, match="guard"): + transient_segments(np.zeros(100), guard=-1) + + @pytest.mark.parametrize("guard", [2.5, True]) + def test_non_integer_guard_rejected(self, guard): + with pytest.raises(TypeError, match="guard"): + transient_segments(np.zeros(100), guard=guard) + + +class TestDetectAnomalies: + def test_phase5_defaults_detect_box_with_timestamps(self): + rng = np.random.default_rng(6) + idx = pd.date_range("2020-01-01", periods=N_SAMPLES, freq="D") + x = rng.standard_normal(N_SAMPLES) + x[ONSET : ONSET + 30] += 10.0 + report = detect_anomalies(pd.Series(x, index=idx)) + assert report.n_transients == 1 + seg = report.transients[0] + assert abs((seg.onset_time - idx[ONSET]).days) <= 1 + assert report.metadata["guard"] == 7 + assert report.metadata["baseline"] == "trailing_median_mad" + assert abs(report.metadata["residual_lag1_autocorr"]) < 0.3 + + def test_metadata_reaches_json(self): + rng = np.random.default_rng(13) + x = rng.standard_normal(N_SAMPLES) + x[ONSET : ONSET + 30] += 10.0 + d = detect_anomalies(x, n_fitted=2).to_dict() + meta = json.loads(json.dumps(d, allow_nan=False))["metadata"] + assert meta["guard"] == 7 + assert meta["n_fitted"] == 2 + assert meta["baseline"] == "trailing_median_mad" + assert isinstance(d["metadata"]["residual_lag1_autocorr"], float) + assert not isinstance(d["metadata"]["residual_lag1_autocorr"], np.floating) + + def test_correlation_warning_points_at_caller(self): + rng = np.random.default_rng(14) + with pytest.warns(UserWarning, match="lag-1") as record: + detect_anomalies(_ar1(rng, 0.8, N_SAMPLES)) + assert record[0].filename == __file__ + + +class TestLag1Autocorr: + def test_gaps_keep_value_in_unit_interval(self): + """Gaps used to inflate the value by (finite samples / pairs). + + This series has 9 finite samples and 2 adjacent pairs, and the + old estimator returned 2.0. + """ + nan = np.nan + x = np.array([1.0, 1.0, nan, 0, nan, 0, nan, 0, nan, 0, nan, -1.0, -1.0]) + assert _lag1_autocorr(x) == pytest.approx(1.0) + + def test_random_gappy_series_bounded(self): + rng = np.random.default_rng(21) + vals = [] + for _ in range(2000): + n = int(rng.integers(4, 30)) + y = rng.standard_normal(n) + y[rng.random(n) < rng.random()] = np.nan + vals.append(_lag1_autocorr(y)) + vals = np.array(vals) + vals = vals[np.isfinite(vals)] + assert np.all(np.abs(vals) <= 1.0 + 1e-12) + + def test_gap_free_ar1_matches_sample_autocorrelation(self): + rng = np.random.default_rng(22) + x = _ar1(rng, 0.8, N_SAMPLES) + d = x - x.mean() + ref = np.dot(d[1:], d[:-1]) / np.dot(d, d) + assert _lag1_autocorr(x) == pytest.approx(ref, abs=0.01) + + +class TestLjungBox: + def test_n_fitted_reduces_degrees_of_freedom(self): + rng = np.random.default_rng(7) + r = _ar1(rng, 0.2, 400) + q0, p0 = ljung_box_test(r, n_lags=20) + q2, p2 = ljung_box_test(r, n_lags=20, n_fitted=2) + assert q2 == q0 + assert p0 == pytest.approx(1.0 - stats.chi2.cdf(q0, df=20)) + assert p2 == pytest.approx(1.0 - stats.chi2.cdf(q0, df=18)) + assert p2 < p0 + + @pytest.mark.parametrize("n_fitted", [-1, 20, 25]) + def test_invalid_n_fitted_rejected(self, n_fitted): + with pytest.raises(ValueError, match="n_fitted"): + ljung_box_test( + np.random.default_rng(8).standard_normal(400), n_fitted=n_fitted + ) + + @pytest.mark.parametrize("n_fitted", [1.5, True]) + def test_non_integer_n_fitted_rejected(self, n_fitted): + with pytest.raises(TypeError, match="n_fitted"): + ljung_box_test( + np.random.default_rng(8).standard_normal(400), n_fitted=n_fitted + )