Skip to content

Phase 5 detector: score against a trailing robust baseline (centred window detected 0/200) - #58

Merged
mdenolle merged 4 commits into
docs/sign-convention-manuscriptfrom
fix/transient-detector-trailing-baseline
Dec 4, 2026
Merged

mdenolle merged 4 commits into
docs/sign-convention-manuscriptfrom
fix/transient-detector-trailing-baseline

Conversation

@mdenolle

@mdenolle mdenolle commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Pull Request

Summary

The Phase 5 transient detector could not detect a transient. Each sample was scored against a centred rolling window that contained the transient itself, so with the defaults it found 0 of 200 boxes and steps even at 1000 sigma. This PR scores each sample against a trailing robust baseline, ending a guard gap before the sample.

Base is docs/sign-convention-manuscript (#37). Retarget after #37 merges.

Type of change

  • Bug fix
  • New feature (forward model, coupling tier, inversion mode, ...)
  • Documentation (KNOWN_ISSUES.md, docs/workflow.md)
  • Tests / CI
  • Refactor / cleanup
  • Breaking change (API, YAML schema, output format)

What was wrong

  • transient_segments used a centred 30-sample rolling mean and standard deviation. A box or step entered its own baseline, so its z-score stayed below 3.
  • Rerun with the Phase 5 defaults (z 3, min_length 7, window 30) on 600-sample white noise: 0 of 200 boxes of 30 or 90 samples detected, and 0 of 200 steps, at 5, 10 and 1000 sigma.

Consequence: studies that reported "no transients" from Phase 5 used a detector that could not find one.

Changes

Trailing baseline (de5dcc3)

  • Each sample is scored against the median and MAD-sigma of the last rolling_window samples, ending guard samples before it (guard defaults to min_length).
  • The baseline freezes at onset.
  • 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 transient of opposite sign.
  • ljung_box_test and detect_anomalies accept n_fitted, which lowers the chi-square degrees of freedom.
  • The detector warns when the lag-1 autocorrelation outside detected segments exceeds 0.3.
  • docs/workflow.md said 30 Ljung-Box lags; the code default is 20, and the doc now says so.

Fixes from review (0cf03ee)

  • Short history: samples with fewer than 15 trailing clean samples (the first 22 with the defaults) are now left unscored. They were scored against the whole series, which includes the transient. For a step in the first half of the record, the start was flagged with the wrong sign and the step itself was never tested: 0 of 100 correct at onset 292 or 876 of 2920. With this change, 100 of 100 are correct at both onsets.
  • Fragmentation: a segment opens after min_length consecutive samples beyond the threshold, and closes only when most of the next min_length finite samples are back inside. A 5-sigma step at sample 300 of 600 was split into more than one segment in 144 of 200 draws; it is now single in 187, split in 7 and missed in 6. NaN samples no longer end a segment.
  • Smaller items:
    • AnomalyReport.to_dict includes JSON-native metadata;
    • integer arguments are validated;
    • the warning points at the caller.

Effect on existing outputs

  • On the Quarto tutorial-06 synthetic run (3650 samples), Phase 5 still gives Q 23.2705, p 0.2757, 0 transients and no warning. No regeneration is needed, and no golden file stores Phase 5 output.
  • Detection rates at seed 12345 (600 samples, onset 300, 200 draws each), from the 0cf03ee commit message:
Input Flagged
10 and 1000 sigma boxes and steps 200/200
5 sigma box or step 193-197/200
White noise, 600 and 2920 samples 0/200
AR(1), no transient, phi 0.5 2/200
AR(1), no transient, phi 0.8 115/200

Known limitation: the fixed threshold over-flags correlated residuals. KNOWN_ISSUES.md records this. The next step is an empirical threshold, calibrated from bootstrapped pre-event residuals.

Checklist

  • Tests pass locally (pytest): 395 passed, 1 failed, 1 skipped at 0cf03ee, against 370 passed, 1 failed, 1 skipped on 5d2d223. The single failure on both is test_audit_small_fixes.py::test_aggregate_rejects_missing_shards_and_duplicates, which predates this PR.
  • Lint passes on the files this PR changes (ruff 0.1.6, black 23.11.0). anomaly/detection.py failed black on the base and passes now.
  • New code has docstrings
  • Sanity test against an analytical limit: the white-noise false-alarm bound
  • Config-file field: n/a
  • CHANGELOG entry added under ## Unreleased
  • Documentation under docs/ updated

Tests

tests/test_anomaly_detection.py, 25 cases:

  • 14 from de5dcc3: 13 fail on 5d2d223, and the white-noise false-alarm bound passes on both.
  • 11 from 0cf03ee: early steps at 10 % and 30 % of 2920 samples, short history, NaN inside a box, 5-sigma fragmentation, integer validation, metadata in JSON, and warning location. All 11 fail on de5dcc3.

Scientific reviewer notes

A separate review agent read de5dcc3 and asked for changes: the wrong-sign early step and the fragmentation. 0cf03ee addresses both; it has not been re-reviewed.

Copilot review follow-up

  • _lag1_autocorr can leave [-1, 1] when there are gaps (valid). The finite/pairs factor inflated the value: 2.0 for a short gappy example, and -2.85 to 1.88 on random gappy series. Fixed in a49adb1: the lag-1 sum is now divided by the root of the sums of squares over the same adjacent finite pairs. Two new TestLag1Autocorr tests fail on 0cf03ee and pass on a49adb1. The tutorial-06 Phase 5 output is unchanged (Q 23.2705, p 0.2757, 0 transients, no warning).
  • isinstance(value, bool | np.bool_) on py3.10/3.11 (invalid). PEP 604 unions work in isinstance from Python 3.10, which is codameter's minimum version. I checked _as_count on 3.10.0, 3.10.14, 3.11.13 and 3.11.15 with numpy 1.24 to 2.4, and it behaves as intended on all of them. No change.

Integration and second Copilot review

  • Base docs/sign-convention-manuscript is unchanged at 5d2d223. git merge reported already up to date, with no conflicts and no merge commit.
  • Copilot review 6190237873 (on a49adb1):
    • PEP 604 union in isinstance in _as_count: invalid. Python >= 3.10 accepts X | Y in isinstance, and it was rerun on 3.10, 3.11 and 3.12. No change.
    • Docstring vs. segment-closing rule: valid. The docstring said a segment closes after min_length samples in a row back inside, but the code closes it when at most half of the next min_length finite samples are still beyond. With min_length=7, a 4-sample dip in a 10 sigma box already splits it. 7f9a63d corrects the docstring (code unchanged) and adds test_segment_closes_when_most_of_next_window_is_inside.
  • Copilot review 6191246131 (on 7f9a63d): no open issues. It recommends maintainer validation on real residual series, which KNOWN_ISSUES already lists as open work.
  • Checks on 7f9a63d:
Check Result
Full test suite (local, Python 3.12) 402 passed, 1 skipped, 1 known failure (test_aggregate_rejects_missing_shards_and_duplicates, also fails on base)
Golden manifest regenerated byte-identical
codameter.figures --check --skip-slow --rtol 1e-5 16/16 match, Phase 5 detector not called
Manuscript build and text checks (local) 88 pages, 0/0/0/0
Tutorial-06 Phase 5 Q 23.2705, p 0.2757, 0 transients, no warning
CI (run 47359548963) sidecars, PDF and survey jobs pass
  • No manuscript number depends on the Phase 5 detector.

🤖 Generated with Claude Code

mdenolle and others added 2 commits December 3, 2026 16:09
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 13:33

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Approval is blocked by two unresolved moderate issues in src/codameter/anomaly/detection.py: _lag1_autocorr can yield out-of-range autocorrelation values when gaps/NaNs are present, and _as_count uses an isinstance check with a PEP 604 union that can be incompatible with the supported Python versions.

2 open issues
What changed in this PR

Updates the Phase 5 transient detector to score samples against a trailing robust baseline with a guard gap so transients no longer contaminate their own baseline, restoring expected detection behavior and improving segment stability.

Changes:

  • Replace centered rolling-window scoring with a trailing median/MAD baseline, guard gap, onset baseline freeze, and exclusion of detected samples from future baselines.
  • Extend diagnostics and reporting (n_fitted support, lag-1 autocorrelation warning, JSON-native AnomalyReport metadata serialization).
  • Add regression tests and update documentation and changelog to reflect new behavior and known limitations.
File Description
tests/​test_anomaly_detection.py Adds targeted unit tests covering the trailing-baseline detector behavior, edge cases (short history/NaNs/fragmentation), and new diagnostics and metadata output.
src/​codameter/​anomaly/​detection.py Implements the trailing robust-baseline transient detection logic with guard handling, segment opening/closing rules, updated diagnostics (n_fitted, autocorrelation warning), and JSON-native report metadata.
KNOWN_ISSUES.md Documents the detector’s known limitations, including over-flagging under correlated residuals and early-record scoring constraints.
docs/​workflow.md Updates the Phase 5 workflow documentation to match current defaults and the new trailing-baseline/guard-gap detector behavior and warnings.
CHANGELOG.md Records the Phase 5 detector fix and related API/diagnostic updates under the Unreleased section.

Review effort: Balanced
Copilot was unable to complete this review at the selected tier due to model policy or plan restrictions.

Comment thread src/codameter/anomaly/detection.py Resolved
Comment thread src/codameter/anomaly/detection.py Resolved
…t 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 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 13:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical runtime bug is present in src/codameter/anomaly/detection.py where _as_count uses a PEP604 union type in isinstance (raising TypeError and breaking multiple downstream functions/tests), alongside a docstring/behavior mismatch in _find_segments that could mislead users.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Low severity Docstring disagrees with segment-closing majority logic

src/​codameter/​anomaly/​detection.py:434

The docstring says the segment closes only after min_length consecutive samples fall back inside the threshold, but the implementation closes when a majority of the next min_length finite samples are inside (see _find_segments lookahead/majority logic). This mismatch could mislead users about fragmentation behavior.

1 resolved since last review

Review effort: Balanced

… 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 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 14:57

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The Phase 5 transient detection logic was substantially redesigned with scientifically sensitive rules (baseline/guard, masking, segment closure, autocorrelation warning), so a maintainer should validate the behavior on representative real residual series and edge cases beyond synthetic/unit tests before approving.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@mdenolle

mdenolle commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Second Copilot review

  • Review 6190237873, item 1 (repeat): _as_count uses a PEP 604 union in isinstance, said to raise TypeError. No change, as in the earlier reply on this line (comment 4801091888). isinstance has accepted X | Y unions since Python 3.10 and codameter requires >=3.10. _as_count was run as written on Python 3.10.0, 3.10.14, 3.11.13, 3.11.15 and 3.12.13, and it rejects bools and floats with the intended TypeError on each one.
  • Review 6190237873, item 2: transient_segments docstring (detection.py:434) says a segment closes only after min_length samples in a row back inside. Valid: the docstring described the wrong closing rule. With min_length 7, a 4-sample dip inside a 10 sigma box already splits it into (300, 339) and (344, 399). The code implements the intended majority rule, so 7f9a63d corrects the docstring and adds test_segment_closes_when_most_of_next_window_is_inside to pin the rule for dips of 1, 3, 4 and 6 samples.

@mdenolle
mdenolle merged commit d67b71c into docs/sign-convention-manuscript Dec 4, 2026
4 checks passed
mdenolle added a commit that referenced this pull request Dec 4, 2026
… into fix/envelope-window-degenerate

Conflicts: CHANGELOG.md (Fixed section). Kept both entries, the #58
transient-detector entry first, then this PR's coda-window entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mdenolle added a commit that referenced this pull request Dec 4, 2026
… into fix/peak-dvv-nan-and-edge

Conflicts: CHANGELOG.md (Unreleased/Fixed), resolved by keeping all three
entries: the #57 missing-day entry, then the #58 transient-detector and #59
coda-window entries. src/codameter/synthetic_demo.py merged without
conflict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mdenolle added a commit that referenced this pull request Dec 5, 2026
… into fix/bandlimited-stretch-interp

Conflicts: CHANGELOG.md (kept the C1 entry and the #57, #58 and #59
entries, in that order); src/codameter/synthetic_demo.py
(_stretch_window keeps both margin from #56 and keyword-only min_samples
from #59; measure_stretching_trailing keeps both interp from #56 and
min_frac from #57, validates min_frac before resolving interp).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants