From de5dcc3ef613c84e082bf5177b3aeb93ab75ea60 Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Thu, 3 Dec 2026 16:09:52 -0800 Subject: [PATCH 1/4] Detect Phase 5 transients against a trailing robust baseline transient_segments scored each residual sample against a centred 30-sample rolling mean and standard deviation. A box or a step entered its own baseline, so its z-score stayed below 3. With the Phase 5 defaults (z 3, min_length 7, window 30), a rerun on 600-sample white noise detected 0 of 200 boxes of 30 or 90 samples and 0 of 200 steps, at 5, 10 and 1000 sigma. Each sample is now scored against the median and MAD-sigma of the last rolling_window samples, ending guard samples before it. guard defaults to min_length. At onset the baseline is frozen, and the segment runs while the residual stays beyond the threshold. Samples of a kept segment are left out of later baselines, so the return to the pre-event level is not flagged as a second, opposite transient. Rerun with the fix: 10 sigma boxes and steps are detected in 200 of 200 draws, with onset error 0 and duration equal to the box; 5 sigma in 192 to 197 of 200; white noise gives no segment in 200 series of 600 or 2920 samples. The fixed threshold over-flags correlated residuals: AR(1) series with no transient are flagged in 1 of 200 at phi 0.5 and 108 of 200 at phi 0.8. transient_segments now warns when the lag-1 autocorrelation outside the detected segments exceeds 0.3. It is computed outside the segments because a detected box alone pushes it to about 0.8. KNOWN_ISSUES records that the threshold is not yet calibrated empirically. ljung_box_test and detect_anomalies accept n_fitted (default 0), which lowers the chi-square degrees of freedom to n_lags - n_fitted. The report metadata records guard, baseline, n_fitted and the background lag-1 autocorrelation. rolling_zscore is unchanged; its docstring says not to use it for detection. docs/workflow.md said 30 Ljung-Box lags; the code default is 20. Effect on existing outputs: the whiteness Q and p-value are unchanged at n_fitted 0. On the quarto tutorial-06 synthetic run, Q 23.2705, p 0.2757 and n_transients 0 are identical before and after, so the frozen output needs no regeneration. No golden file stores Phase 5 output. Studies that reported "no transients" from Phase 5 were run with a detector that could not find one. Tests: tests/test_anomaly_detection.py, 14 cases. 13 fail on 5d2d223 (the white-noise false-alarm bound passes on both) and all pass here. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++ KNOWN_ISSUES.md | 15 ++ docs/workflow.md | 9 +- src/codameter/anomaly/detection.py | 231 ++++++++++++++++++++++++++--- tests/test_anomaly_detection.py | 137 +++++++++++++++++ 5 files changed, 384 insertions(+), 19 deletions(-) create mode 100644 tests/test_anomaly_detection.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b238b7..a986a90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,17 @@ 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 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`. `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..dc53089 100644 --- a/KNOWN_ISSUES.md +++ b/KNOWN_ISSUES.md @@ -128,3 +128,18 @@ 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 samples. It over-flags correlated residuals: 600-sample AR(1) series +with no transient are flagged in 1 of 200 draws at phi 0.5 and in 108 of +200 at phi 0.8. 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. diff --git a/docs/workflow.md b/docs/workflow.md index 2fdaaf2..1d135cf 100644 --- a/docs/workflow.md +++ b/docs/workflow.md @@ -111,8 +111,13 @@ 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. 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..0688efd 100644 --- a/src/codameter/anomaly/detection.py +++ b/src/codameter/anomaly/detection.py @@ -7,9 +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 - onset time, amplitude, and duration. + 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. 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 overall p-value and the count of detected transient segments. @@ -23,6 +27,7 @@ """ from __future__ import annotations +import warnings from dataclasses import dataclass, field from typing import Any @@ -30,6 +35,15 @@ 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 1 of 200 draws at +#: phi = 0.5 and in 108 of 200 draws at phi = 0.8. +LAG1_AUTOCORR_WARN = 0.3 + @dataclass class TransientSegment: @@ -90,13 +104,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 +120,28 @@ 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) """ + 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 +151,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 +164,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,6 +181,95 @@ def rolling_zscore( return ((s - mu) / sd).to_numpy() +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, + *, + window: int, + guard: int, + min_periods: int, + fallback: tuple[float, float], +) -> tuple[np.ndarray, np.ndarray]: + """Trailing median and MAD-sigma for every sample of ``x``. + + 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, ``fallback`` is used. A zero MAD + is replaced by the fallback scale. + """ + 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, fallback[0]) + scale = np.full(n, fallback[1]) + ok = count >= min_periods + med[ok] = med_c[count[ok] - 1] + scale[ok] = sc_c[count[ok] - 1] + scale[~(scale > 0)] = fallback[1] + 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 the numerator, so a gap + does not join the samples on either side of it. + """ + 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) + var = float(np.dot(d, d)) + if var == 0: + return 0.0 + pair = ok[1:] & ok[:-1] + num = float(np.dot(d[1:][pair], d[:-1][pair])) + return num / var * ok.sum() / max(int(pair.sum()), 1) + + +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 transient_segments( residuals: np.ndarray | pd.Series, *, @@ -157,31 +277,82 @@ def transient_segments( min_length: int = 7, rolling_window: int = 30, timestamps: pd.DatetimeIndex | None = None, + guard: int | None = None, ) -> list[TransientSegment]: """Find contiguous excursions above ``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 segment opens at the first + sample with ``|z| >= z_threshold``. Its baseline is then frozen, and + the segment runs while the residual stays ``z_threshold`` sigma away + from that frozen baseline. 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. Samples + with too short a history are scored against the median and MAD of + the whole series. + + 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`. 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. + + 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) - z = rolling_zscore(r, window=rolling_window) - above = np.abs(z) >= z_threshold + if guard is None: + guard = 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 = _robust_location_scale(r) + clean = np.isfinite(r) + 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=fallback, + ) + 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]: + m0, s0 = med[i], scale[i] + j = i + 1 + while j < n and np.abs(r[j] - m0) / s0 >= z_threshold: j += 1 if j - i >= min_length: sub = r[i:j] - zsub = z[i:j] + zsub = (sub - m0) / s0 i_peak = int(np.argmax(np.abs(zsub))) seg = TransientSegment( onset_index=i, @@ -194,7 +365,21 @@ def transient_segments( sign=int(np.sign(zsub[i_peak])), ) segments.append(seg) + clean[i:j] = False + med, scale, above = baseline() i = j + + rho1 = _lag1_autocorr(_background(r, segments)) + 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=2, + ) return segments @@ -205,6 +390,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 +401,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,13 +417,17 @@ def detect_anomalies( ts = None r = np.asarray(residuals, dtype=float) - Q, p = ljung_box_test(r, n_lags=n_lags) + r = np.asarray(r, dtype=float) + if guard is None: + guard = min_transient_length + Q, p = ljung_box_test(r, n_lags=n_lags, n_fitted=n_fitted) segments = transient_segments( r, z_threshold=z_threshold, min_length=min_transient_length, rolling_window=rolling_window, timestamps=ts, + guard=guard, ) report = AnomalyReport( whiteness_pvalue=p, @@ -247,6 +440,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": _lag1_autocorr(_background(r, segments)), }, ) return report diff --git a/tests/test_anomaly_detection.py b/tests/test_anomaly_detection.py new file mode 100644 index 0000000..2f1323a --- /dev/null +++ b/tests/test_anomaly_detection.py @@ -0,0 +1,137 @@ +"""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 warnings + +import numpy as np +import pandas as pd +import pytest +from codameter.anomaly.detection import ( + 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)) + + def test_negative_guard_rejected(self): + with pytest.raises(ValueError, match="guard"): + transient_segments(np.zeros(100), guard=-1) + + +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 + + +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 + ) From 0cf03eea1a7e7a7f8e7c903585a4fe608518869c Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Thu, 3 Dec 2026 17:03:35 -0800 Subject: [PATCH 2/4] Leave short-history samples unscored and close segments by majority Samples with fewer than 15 trailing clean samples (the first 22 with the defaults) were scored against the median and MAD of the whole series, which includes the transient. When a step sat in the first half of the record, that median was the post-step level: the record start was flagged with the wrong sign, the segment ran through the pre-step period, and the step itself was never tested. Rerun on de5dcc3, N 2920, -10 sigma step at 292 or 876, 100 draws each: a +1 segment at index 0 in 100/100 and the correct segment in 0/100. Those samples are now left unscored. With this commit the same rerun gives one correct segment in 100/100 at both onsets. A step at sample 15 of 600 is reported from sample 22; one before sample 15 fills the first baseline and is missed, which KNOWN_ISSUES now states. Segments also split at every sample that dipped inside the threshold, and a NaN ended a segment. A 5 sigma step at 300 of 600 (seed 2026, 200 draws) gave more than one segment in 144 draws, and the leftover pieces triggered the lag-1 warning in 116. A segment still opens after min_length samples in a row beyond the threshold, now on the side of the onset. After that it closes only when most of the next min_length finite samples are back inside; NaN samples are skipped. The same rerun gives 6 missed, 187 single and 7 split in two, and 14 warnings. A 60-sample box with a NaN at its middle is one segment. Smaller changes from review: AnomalyReport.to_dict includes metadata as JSON-native values (NaN as None); min_length, rolling_window, guard and n_fitted must be integers (TypeError for 2.5 or True); the autocorrelation warning points at the caller of detect_anomalies or transient_segments; the CHANGELOG notes rolling_window >= 2. Effect on existing outputs: on the quarto tutorial-06 synthetic run (3650 samples) Phase 5 still gives Q 23.2705, p 0.2757, n_transients 0 and no warning. Detection rates at seed 12345 (600 samples, onset 300, 200 draws): 10 and 1000 sigma boxes and steps 200/200; 5 sigma 193 to 197/200; white noise 0/200 at 600 and 2920 samples; AR(1) with no transient flagged 2/200 at phi 0.5 and 115/200 at phi 0.8. No golden file stores Phase 5 output. Tests: 11 new cases in tests/test_anomaly_detection.py (early step at 10 % and 30 % of 2920 samples, short history, NaN inside a box, 5 sigma step fragmentation, integer validation, metadata in JSON, warning location). All 11 fail on de5dcc3 and pass here. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 +- KNOWN_ISSUES.md | 31 +++- docs/workflow.md | 3 +- src/codameter/anomaly/detection.py | 259 +++++++++++++++++++---------- tests/test_anomaly_detection.py | 89 ++++++++++ 5 files changed, 301 insertions(+), 98 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a986a90..d788be0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,11 +21,18 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht 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 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`. `rolling_zscore` is unchanged. (C4) + 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 diff --git a/KNOWN_ISSUES.md b/KNOWN_ISSUES.md index dc53089..b3b4d72 100644 --- a/KNOWN_ISSUES.md +++ b/KNOWN_ISSUES.md @@ -136,10 +136,27 @@ conventional in the example configs). `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 samples. It over-flags correlated residuals: 600-sample AR(1) series -with no transient are flagged in 1 of 200 draws at phi 0.5 and in 108 of -200 at phi 0.8. 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. +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 1d135cf..b823c88 100644 --- a/docs/workflow.md +++ b/docs/workflow.md @@ -115,7 +115,8 @@ v0.2. 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. A warning is issued when the residual lag-1 +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. diff --git a/src/codameter/anomaly/detection.py b/src/codameter/anomaly/detection.py index 0688efd..bb64821 100644 --- a/src/codameter/anomaly/detection.py +++ b/src/codameter/anomaly/detection.py @@ -11,9 +11,10 @@ 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. Samples inside a detected segment are left out of later - baselines. Each segment is summarised by onset time, amplitude, and - duration. + 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 overall p-value and the count of detected transient segments. @@ -27,6 +28,8 @@ """ from __future__ import annotations +import math +import operator import warnings from dataclasses import dataclass, field from typing import Any @@ -40,11 +43,20 @@ #: 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 1 of 200 draws at -#: phi = 0.5 and in 108 of 200 draws at phi = 0.8. +#: 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: """One contiguous transient anomaly.""" @@ -97,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()}, } @@ -132,6 +145,7 @@ def ljung_box_test( ------- (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}); " @@ -204,14 +218,14 @@ def _trailing_baseline( window: int, guard: int, min_periods: int, - fallback: tuple[float, float], + fallback_scale: float, ) -> tuple[np.ndarray, np.ndarray]: """Trailing median and MAD-sigma for every sample of ``x``. 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, ``fallback`` is used. A zero MAD - is replaced by the fallback scale. + ``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``. """ n = len(x) idx = np.flatnonzero(clean) @@ -234,12 +248,12 @@ def _trailing_baseline( ) # Number of clean samples with index <= k - guard - 1. count = np.searchsorted(idx, np.arange(n) - guard, side="left") - med = np.full(n, fallback[0]) - scale = np.full(n, fallback[1]) + 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[~(scale > 0)] = fallback[1] + scale[ok & ~(scale > 0)] = fallback_scale return med, scale @@ -259,7 +273,7 @@ def _lag1_autocorr(x: np.ndarray) -> float: return 0.0 pair = ok[1:] & ok[:-1] num = float(np.dot(d[1:][pair], d[:-1][pair])) - return num / var * ok.sum() / max(int(pair.sum()), 1) + return float(num / var * ok.sum() / max(int(pair.sum()), 1)) def _background(r: np.ndarray, segments: list[TransientSegment]) -> np.ndarray: @@ -270,60 +284,58 @@ def _background(r: np.ndarray, segments: list[TransientSegment]) -> np.ndarray: return bg -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 contiguous excursions above ``z_threshold`` lasting at least - ``min_length`` samples. +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 - 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 segment opens at the first - sample with ``|z| >= z_threshold``. Its baseline is then frozen, and - the segment runs while the residual stays ``z_threshold`` sigma away - from that frozen baseline. 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. Samples - with too short a history are scored against the median and MAD of - the whole series. - 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. +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, + ) - 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. - 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. +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. """ - r = np.asarray(residuals, dtype=float) - if guard is None: - guard = min_length + 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 = _robust_location_scale(r) + 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]: @@ -333,7 +345,7 @@ def baseline() -> tuple[np.ndarray, np.ndarray, np.ndarray]: window=rolling_window, guard=guard, min_periods=min_periods, - fallback=fallback, + fallback_scale=fallback_scale, ) with np.errstate(invalid="ignore"): above = np.abs(r - med) / scale >= z_threshold @@ -347,39 +359,117 @@ def baseline() -> tuple[np.ndarray, np.ndarray, np.ndarray]: i += 1 continue m0, s0 = med[i], scale[i] - j = i + 1 - while j < n and np.abs(r[j] - m0) / s0 >= z_threshold: - j += 1 - if j - i >= min_length: - sub = r[i:j] - zsub = (sub - m0) / s0 - i_peak = int(np.argmax(np.abs(zsub))) - seg = TransientSegment( + 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) - clean[i:j] = False - med, scale, above = baseline() - i = j + ) + clean[i : last + 1] = False + med, scale, above = baseline() + i = last + 1 rho1 = _lag1_autocorr(_background(r, segments)) - 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=2, - ) + 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. The segment + then closes only after ``min_length`` samples in a row fall back + inside the threshold (or cross to the other side); it ends at the last + sample beyond the threshold, so short dips do not split one event into + several. 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 @@ -418,10 +508,8 @@ def detect_anomalies( r = np.asarray(residuals, dtype=float) r = np.asarray(r, dtype=float) - if guard is None: - guard = min_transient_length Q, p = ljung_box_test(r, n_lags=n_lags, n_fitted=n_fitted) - segments = transient_segments( + segments, guard, rho1 = _find_segments( r, z_threshold=z_threshold, min_length=min_transient_length, @@ -429,6 +517,7 @@ def detect_anomalies( timestamps=ts, guard=guard, ) + _warn_if_correlated(rho1, stacklevel=2) report = AnomalyReport( whiteness_pvalue=p, whiteness_lags=n_lags, @@ -443,7 +532,7 @@ def detect_anomalies( "guard": guard, "baseline": "trailing_median_mad", "n_fitted": n_fitted, - "residual_lag1_autocorr": _lag1_autocorr(_background(r, segments)), + "residual_lag1_autocorr": rho1, }, ) return report diff --git a/tests/test_anomaly_detection.py b/tests/test_anomaly_detection.py index 2f1323a..391e267 100644 --- a/tests/test_anomaly_detection.py +++ b/tests/test_anomaly_detection.py @@ -7,6 +7,7 @@ """ from __future__ import annotations +import json import warnings import numpy as np @@ -98,10 +99,73 @@ def test_autocorrelated_residual_warns(self): 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 + 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): @@ -117,6 +181,24 @@ def test_phase5_defaults_detect_box_with_timestamps(self): 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 TestLjungBox: def test_n_fitted_reduces_degrees_of_freedom(self): @@ -135,3 +217,10 @@ def test_invalid_n_fitted_rejected(self, 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 + ) From a49adb15d8e25b892806fced31863b4549190f40 Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Fri, 4 Dec 2026 05:51:34 -0800 Subject: [PATCH 3/4] Keep the background lag-1 autocorrelation inside [-1, 1] (#58, Copilot review) _lag1_autocorr divided the sum over adjacent finite pairs by the sum of squares over all finite samples and then multiplied by (finite samples / pairs). With gaps, such as the NaN stretches left where detected segments are masked, that factor inflated the value: 1, 1, NaN, 0, NaN, 0, NaN, 0, NaN, 0, NaN, -1, -1 gave 2.0, random gappy series of 4 to 29 samples ranged from -2.85 to 1.88, and short alternating gap-free series went below -1. A value pushed above 0.3 this way raises the correlation warning without the residuals being correlated. The lag-1 sum over pairs is now divided by the root of the two sums of squares over the same pairs (deviations still from the mean of all finite samples), so Cauchy-Schwarz bounds it to [-1, 1]. Effect on existing outputs: segments, Q and p do not depend on this value. The tutorial-06 Phase 5 run gives Q 23.2705, p 0.2757, 0 transients, residual_lag1_autocorr -0.0104 and no warning on both the pre-fix commit 0cf03ee and this one. Tests: TestLag1Autocorr::test_gaps_keep_value_in_unit_interval and ::test_random_gappy_series_bounded fail on 0cf03ee and pass here; ::test_gap_free_ar1_matches_sample_autocorrelation passes on both. Co-Authored-By: Claude Opus 5.5 --- src/codameter/anomaly/detection.py | 17 +++++++++------- tests/test_anomaly_detection.py | 32 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/src/codameter/anomaly/detection.py b/src/codameter/anomaly/detection.py index bb64821..41ee63a 100644 --- a/src/codameter/anomaly/detection.py +++ b/src/codameter/anomaly/detection.py @@ -260,20 +260,23 @@ def _trailing_baseline( def _lag1_autocorr(x: np.ndarray) -> float: """Lag-1 sample autocorrelation of ``x``, ignoring non-finite samples. - Only pairs of adjacent finite samples enter the numerator, so a gap - does not join the samples on either side of it. + 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) - var = float(np.dot(d, d)) - if var == 0: - return 0.0 pair = ok[1:] & ok[:-1] - num = float(np.dot(d[1:][pair], d[:-1][pair])) - return float(num / var * ok.sum() / max(int(pair.sum()), 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: diff --git a/tests/test_anomaly_detection.py b/tests/test_anomaly_detection.py index 391e267..891747d 100644 --- a/tests/test_anomaly_detection.py +++ b/tests/test_anomaly_detection.py @@ -14,6 +14,7 @@ import pandas as pd import pytest from codameter.anomaly.detection import ( + _lag1_autocorr, detect_anomalies, ljung_box_test, transient_segments, @@ -200,6 +201,37 @@ def test_correlation_warning_points_at_caller(self): 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) From 7f9a63d1863f514cf1e566ce3640bc7c96838258 Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Fri, 4 Dec 2026 06:32:13 -0800 Subject: [PATCH 4/4] The transient_segments docstring states the majority closing rule (#58, Copilot review) The docstring said a segment closes only after min_length samples in a row fall back inside the threshold. _find_segments closes it when, at a sample back inside, at most half of the next min_length finite samples (that one included) are still beyond. With min_length 7, a +10 sigma box at 300 to 399 of 600 (seed 2026) with a dip set to 0 at 340 gives one segment for a 3-sample dip and two segments, (300, 339) and (344 or 346, 399), for 4- and 6-sample dips, where the docstring promised one. The code follows the rule of commit 0cf03ee, the CHANGELOG and docs/workflow.md, so the docstring is corrected, not the code. Effect on outputs: none; only the docstring changes. Tests: TestTransientSegments::test_segment_closes_when_most_of_next_window_is_inside (dips of 1, 3, 4, 6 samples) pins the documented rule. It passes on a49adb1 as well, since the code is unchanged. Co-Authored-By: Claude Opus 5.5 --- src/codameter/anomaly/detection.py | 22 +++++++++++++--------- tests/test_anomaly_detection.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/src/codameter/anomaly/detection.py b/src/codameter/anomaly/detection.py index 41ee63a..9edb135 100644 --- a/src/codameter/anomaly/detection.py +++ b/src/codameter/anomaly/detection.py @@ -428,15 +428,19 @@ def transient_segments( 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. The segment - then closes only after ``min_length`` samples in a row fall back - inside the threshold (or cross to the other side); it ends at the last - sample beyond the threshold, so short dips do not split one event into - several. 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. + ``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 diff --git a/tests/test_anomaly_detection.py b/tests/test_anomaly_detection.py index 891747d..e92dbce 100644 --- a/tests/test_anomaly_detection.py +++ b/tests/test_anomaly_detection.py @@ -158,6 +158,24 @@ def test_moderate_step_is_one_segment(self): 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)