Skip to content

coda_window_from_envelope: reject degenerate windows that gave dv/v at cc 1.000 - #59

Merged
mdenolle merged 5 commits into
docs/sign-convention-manuscriptfrom
fix/envelope-window-degenerate
Dec 4, 2026
Merged

mdenolle merged 5 commits into
docs/sign-convention-manuscriptfrom
fix/envelope-window-degenerate

Conversation

@mdenolle

@mdenolle mdenolle commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Pull Request

Summary

coda_window_from_envelope could return a zero-length window such as (3, 3). Stretching on that window correlates one sample per branch and reports a confident wrong dv/v at cc = 1.000. This PR makes the function raise on degenerate windows, and stops every stretching estimator from accepting one.

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
  • Tests / CI
  • Refactor / cleanup
  • Breaking change (API, YAML schema, output format)

What was wrong

  • When floor_window (default 40-50 s) missed the trace, the function fell back to the last envelope sample as the noise floor.
  • When the envelope was already on the floor at t_start, it returned (3, 3).
  • Test case: an 8-16 Hz autocorrelation with fs 50 Hz, 60-s max lag and 0.7-s coda decay, rerun on 5d2d223. Stretching on (3, 3) or (3, 3.01) returned dv/v from +3.35 % to +3.81 %, at cc 1.000, against a truth of -0.5 %.

Changes (synthetic_demo.py)

  • The function raises ValueError when floor_window does not overlap the positive-lag support. The message names the max lag.
  • The last smooth_s / 2 seconds of the mode="same" envelope roll off against the zero padding, so they are excluded from the floor median.
  • New min_cycles (default 3): the window must span at least min_cycles periods of band[0].
    • A shorter detection is extended, with a UserWarning.
    • If the extension would pass the max lag, the function raises.
  • _stretch_window takes min_samples (default 8, both branches counted) and raises below it, so no stretching estimator accepts a window that would read cc = 1.

Effect on existing outputs

  • On the verifier grid, the 25-s max-lag cases now raise.
  • The 60-s / 0.7-s case returns (3, 3.375) at 8-16 Hz and recovers -0.48 % to -0.52 % at cc 0.98-0.99.
  • In fig_window_envelope (demo_15), the window ends move from 29.08, 36.92 and 14.40 s to 29.04, 36.90 and 14.38 s, with adaptive RMS changes in the fifth significant figure.
  • The manuscript values are unchanged at their quoted precision: (3, 29), (3, 37), (3, 14), 0.030 / 0.017 / 0.020 % and ~104x.
  • The archived PNG and sidecars were not regenerated.

Checklist

  • Tests pass locally (pytest): 382 passed, 1 failed, 1 skipped, 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. The reviewer reran the new file but did not finish an independent full-suite run.
  • Lint passes on the files this PR changes (ruff 0.1.6, black 23.11.0)
  • New code has docstrings
  • Forward model or kernel: n/a
  • Config-file field: n/a
  • CHANGELOG entry added under ## Unreleased
  • Documentation under docs/ (docstrings only)

Tests

tests/test_coda_window.py, 12 cases. 11 fail on 5d2d223 and all pass here; the twelfth documents the envelope roll-off itself.

Scientific reviewer notes

Before opening, a separate review agent reran the new tests fresh: approve.

Copilot review follow-up

  • _stretch_window docstring said min_samples counts "both branches" (comment 4800525001). Valid. The check counts the samples on the requested branch. A window of 6 samples per side passes with branch="both" (12 samples) and raises with "causal" or "acausal" (6 samples). Docstring corrected; behavior unchanged. Commit 518d33e. The f08c49c commit message has the same "both branches counted" wording; read it as "selected branch".

Integration and second Copilot review

Second Copilot review (6190188198, on 518d33e), both items valid, fixed in aec9c25:

  • Envelope roll-off exclusion now uses the convolution half-width: the last (n - 1) // 2 samples of the n-sample mode="same" boxcar, by index. Before, 0.5 * n / fs always dropped one unaffected sample, and with smooth_s near one sample a floor_window at the trace end raised spuriously.
  • coda_window_from_envelope raises ValueError for band[0] <= 0 (was ZeroDivisionError at 0, guard silently off below 0) and for min_cycles <= 0 (was the zero-length (3, 3) window again).
  • 8 new cases in tests/test_coda_window.py. All fail on 518d33e and pass now.

Merge of docs/sign-convention-manuscript (182351a, includes #58): one conflict in CHANGELOG.md, both Fixed entries kept.

Figure: demo_15_window_envelope png/npz/json regenerated at 182351a (47f75fd). The roll-off fix does not move the windows: (3, 29.04), (3, 36.90), (3, 14.38) s. Local codameter.figures --check --rtol 1e-5 over all 19 figures, slow ones included: 19 match.

Manuscript value Before After At quoted precision
windows ~(3,29), (3,37), (3,14) s 29.08, 36.92, 14.40 29.04, 36.90, 14.38 unchanged
adaptive RMS ~0.030 / 0.017 / 0.020 % 0.029956 / 0.016456 / 0.020637 0.029956 / 0.016469 / 0.020626 unchanged
fixed RMS ~0.036 / 0.035 / 2.0 % 0.035657 / 0.035207 / 2.1404 identical unchanged
high-band ratio ~104x 103.71 103.77 unchanged

Checks: golden manifest regenerates byte-identical. Full suite: 422 passed, 1 failed (known base failure test_aggregate_rejects_missing_shards_and_duplicates), 1 skipped. ruff 0.1.6 and black 23.11.0 clean. Manuscript text check passes locally (88 pages, 0/0/0/0). CI on 47f75fd: all paper jobs pass.

Third Copilot review (6192801675, on 47f75fd): suggests validating min_samples >= 1 in the private _stretch_window. Not changed. No caller passes it (all use the default 8), and a floor of 1 would not restore the guard.

🤖 Generated with Claude Code

coda_window_from_envelope fell back to the last envelope sample as the
noise floor when floor_window (default 40-50 s) missed the trace, and
returned (3, 3) when the envelope was already on the floor at t_start.
On a short-maxlag 8-16 Hz autocorrelation (fs 50 Hz, 60 s max lag,
coda decay 0.7 s) stretching on window (3, 3) or (3, 3.01) correlates
one sample per branch and returned dv/v of +3.35 to +3.81 % at cc 1.000
against a truth of -0.5 % (verifier script rerun on base 5d2d223).

Changes in synthetic_demo.py:
- coda_window_from_envelope raises ValueError when floor_window does not
  overlap the positive-lag support, naming the max lag.
- The last smooth_s/2 s of the mode="same" envelope roll off against the
  zero padding and are excluded from the floor median.
- New min_cycles (default 3): the window spans at least min_cycles
  periods of band[0]. A shorter detection is extended with a UserWarning;
  if the extension passes the max lag it raises. t_start stays 3.0.
- _stretch_window takes min_samples (default 8, both branches counted)
  and raises below it, so every stretching estimator refuses a window
  that would read cc = 1.

Effect on existing outputs: on the verifier grid the 25 s max-lag cases
now raise, and the 60 s / 0.7 s case returns (3, 3.375) at 8-16 Hz,
which recovers -0.48 to -0.52 % at cc 0.98-0.99. In fig_window_envelope
(demo_15) the floor rises 1.8 to 4.6 % without the roll-off, and the
window ends move from 29.08, 36.92, 14.40 s to 29.04, 36.90, 14.38 s.
Adaptive RMS goes 0.016456 -> 0.016469 % (mid) and 0.020637 -> 0.020626 %
(high); low band unchanged. The manuscript quotes (3,29), (3,37), (3,14),
0.030/0.017/0.020 % and ~104x, all unchanged at that precision. The
archived PNG and sidecars were not regenerated.

Tests: tests/test_coda_window.py, 12 cases. 11 fail on the base commit
and all pass here; the twelfth documents the envelope roll-off itself.

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

A misleading docstring in src/codameter/synthetic_demo.py incorrectly describes how min_samples is applied when _window_mask selects only the causal or acausal branch, so the documentation should be corrected to match the implemented behavior.

1 open issue
What changed in this PR

Hardens envelope-based coda-window selection and stretching dv/v estimation by rejecting degenerate windows that previously produced spuriously perfect correlations (cc = 1.000) and incorrect dv/v.

Changes:

  • Make coda_window_from_envelope raise on invalid floor_window overlap and exclude end-of-trace envelope roll-off from the floor estimate; add min_cycles to enforce a minimum window span.
  • Add a min_samples guard to _stretch_window so stretching estimators cannot operate on sample-degenerate windows.
  • Add regression tests covering the prior failure mode and document the behavior change in the changelog.
File Description
tests/​test_coda_window.py Adds a focused regression test suite that reproduces the degenerate-window failure mode and verifies the new window validity guards and expected window endpoints.
src/​codameter/​synthetic_demo.py Strengthens coda_window_from_envelope validation (floor overlap, roll-off exclusion, min-cycles) and updates stretching window handling to reject too-few-sample windows via min_samples.
CHANGELOG.md Records the new error/guard behavior and summarizes the expected impact on existing outputs and demos.

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/synthetic_demo.py Resolved
… Copilot review)

The docstring said min_samples counts "both branches", but the check
counts the samples _window_mask selects for the requested branch. With
branch="causal" or "acausal" only that side is counted: a window of 6
samples per side passes with branch="both" (12 samples) and raises with
"causal" or "acausal" (6 samples). The docstring now says so. The commit
message of f08c49c has the same "both branches counted" wording; the code
there is unchanged and correct.

Effect on existing outputs: none, docstring only. No test added; the
targeted tests in tests/test_coda_window.py pass (12 passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 13:49

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 change still has unresolved edge-case bugs flagged in synthetic_demo.py, including missing parameter validation that can trigger division by zero/degenerate windows and a roll-off exclusion calculation inconsistent with the convolution windowing, which can incorrectly exclude samples and cause spurious errors.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Use convolution half-width for envelope edge exclusion

src/​codameter/​synthetic_demo.py:1425

The roll-off exclusion uses 0.5 * n / fs, but _envelope() uses np.convolve(..., mode="same") where the edge affected by zero padding is (n - 1) // 2 samples (and for n==1 it should exclude 0 samples). With the current formula smooth_s values near one sample can incorrectly exclude the last sample and make floor_window spuriously raise.

Medium severity Validate min_cycles and band frequency before computing start time

src/​codameter/​synthetic_demo.py:1445

t_start + min_cycles / band[0] will raise ZeroDivisionError for band[0] == 0 (and behaves nonsensically for band[0] < 0). Also, min_cycles <= 0 effectively disables the new guard and can reintroduce degenerate windows. Validate both parameters and raise a clear ValueError instead.

1 resolved since last review

Review effort: Balanced

mdenolle and others added 3 commits December 4, 2026 08:08
…nd min_cycles (#59, Copilot review)

coda_window_from_envelope excluded the last 0.5 * n / fs seconds of the
smoothed envelope from the floor estimate. np.convolve(mode="same") with
an n-sample boxcar only pads the last (n - 1) // 2 output samples, so one
unaffected sample was always dropped; with smooth_s near one sample a
floor_window holding only the last sample raised spuriously. The
exclusion is now by index, (n - 1) // 2 samples.

band[0] == 0 raised ZeroDivisionError in t_start + min_cycles / band[0],
band[0] < 0 put the minimum end before t_start, and min_cycles <= 0
returned the zero-length window (3, 3) again. All three now raise
ValueError before any filtering.

Effect on outputs: none on the demo_15 windows, still (3, 29.04),
(3, 36.90), (3, 14.38) s (the median floor over 40-50 s gains the
sample at 49.26 s and the crossings do not move).

Tests: tests/test_coda_window.py adds 8 cases (roll-off edge for
n = 1, 2, 3, 75; band[0] 0 and -1; min_cycles 0 and -3). All 8 fail on
518d33e and pass now; the file runs 20 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… 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>
…windows (#59)

The CI job "figure sidecars reproduce" failed on demo_15: the committed
sidecar held the windows from before this PR, (3, 29.08), (3, 36.92),
(3, 14.40) s. With the floor estimate no longer using the envelope
roll-off the windows are (3, 29.04), (3, 36.90), (3, 14.38) s.

Regenerated with python -m codameter.figures --only
demo_15_window_envelope at 182351a (clean tree). Changed arrays: the
three window spans in panel (a) and the adaptive-window RMS bars in
panel (b): 0.029956 -> 0.029956, 0.016456 -> 0.016469,
0.020637 -> 0.020626 %. Fixed-window bars unchanged. The quoted
manuscript values (3, 29), (3, 37), (3, 14) s, 0.030 / 0.017 / 0.020 %
and ~104x do not change at their quoted precision (high band ratio
103.71 -> 103.77).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 16:32

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

A moderate active finding notes that min_samples is not validated in src/codameter/synthetic_demo.py:406, allowing zero/negative values to bypass the degenerate-window guard and undermining the intended safety check.

1 open issue

Review effort: Balanced

Comment on lines +406 to +407
n_sel = int(np.count_nonzero(sel))
if n_sel < min_samples:
@mdenolle

mdenolle commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Second Copilot review

  • Copilot review 6190188198 item 1: use the convolution half-width (n - 1) // 2 for the envelope edge exclusion (synthetic_demo.py:1425). Valid. mode='same' pads only the last (n - 1) // 2 samples, so the old rule always dropped one unaffected sample and raised spuriously for a floor_window at the trace end with smooth_s near one sample. Fixed in aec9c25 with index-based exclusion and a parametrized test for n = 1, 2, 3, 75 (all fail on 518d33e). The demo_15 windows do not move.
  • Copilot review 6190188198 item 2: validate min_cycles and band[0] before computing t_start + min_cycles / band[0] (synthetic_demo.py:1445). Valid. On 518d33e band[0] = 0 raised ZeroDivisionError, band[0] < 0 silently disabled the guard, and min_cycles <= 0 returned the (3, 3) window this PR set out to remove. Both now raise ValueError before filtering (aec9c25), with 4 tests that fail on 518d33e.
  • Copilot review 6192801675 (on 47f75fd), inline comment 4802717037 at synthetic_demo.py:407: validate min_samples >= 1 in _stretch_window. The guard can be turned off only by calling the private _stretch_window directly with min_samples <= 0. No caller does that: lines 465, 652 and 952 all use the default 8, and no public function exposes the argument. A floor of 1 would not restore the protection either, because 1 or 2 samples are still degenerate. Leaving it as an explicit opt-out for direct callers.

@mdenolle
mdenolle merged commit 5bd3c8a 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/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