Skip to content

peak_dvv: NaN for missing days (was +6.38 %), NaN-aware trailing stacks, grid-edge flags - #57

Merged
mdenolle merged 5 commits into
docs/sign-convention-manuscriptfrom
fix/peak-dvv-nan-and-edge
Dec 4, 2026
Merged

mdenolle merged 5 commits into
docs/sign-convention-manuscriptfrom
fix/peak-dvv-nan-and-edge

Conversation

@mdenolle

@mdenolle mdenolle commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Pull Request

Summary

peak_dvv turned a missing day into a finite dv/v of +6.38 %. Through the cumulative-sum trailing reference, one missing day then contaminated every later epoch. This PR returns NaN for missing data, makes the trailing stacks NaN-aware, and flags grid-edge picks.

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

Type of change

  • Bug fix
  • New feature (opt-in keywords edge_guard, return_flags, min_frac, and dvv_search_bounds)
  • Documentation
  • Tests / CI
  • Refactor / cleanup
  • Breaking change (API, YAML schema, output format)

What was wrong

Missing days (73e9845)

  • peak_dvv took a bare argmax of each CC row. An all-NaN row picked column 0 and returned eps_to_dvv(-eps_max): +6.383 % at eps_max 0.06.
  • The trailing reference in measure_stretching_trailing and the stack in _trailing_stack are cumulative-sum differences. One NaN day therefore made every later reference NaN, and every later epoch read +6.383 % with NaN CC.
  • Rerun on 5d2d223 (160 synthetic days, NaN on day 80): run_pipeline with gate=False kept those epochs as valid, because valid = isfinite(dvv).
  • With the fixed reference, one NaN day in the first 60 % of the record made every epoch +6.383 %.

Grid-edge picks (93fff51)

  • A grid-edge pick came back as an ordinary measurement, with no flag. Its value is a bound, not a measurement.
  • The bounds are asymmetric because eps_to_dvv is not odd: -2.913 % and +3.093 % at eps_max 0.03. A cut written as abs(dvv) < eps_max keeps every -2.913 % edge pick and drops every +3.093 % one.
  • On pure noise, 5.25 % of picks land on an edge.

Changes

  • peak_dvv returns NaN dv/v and NaN peak CC for any row containing a non-finite value.
  • _trailing_stack and measure_stretching_trailing skip missing rows and divide by the number of days with data. A new min_frac keyword (default 0.5) sets a minimum: the result is NaN when fewer than ceil(min_frac x window) days have data.
  • deviations.run_pipeline:
    • builds the fixed reference from days with data;
    • applies the same min_frac rule in the moving-reference loop;
    • sets to NaN any epoch whose stacked waveform is missing.
  • peak_dvv(..., edge_guard=0, return_flags=False):
    • return_flags=True adds a dict with per-row at_edge and second_peak_ratio;
    • edge_guard=g returns NaN dv/v for a peak within g grid steps of either end;
    • typing overloads keep the 2-tuple return type for existing callers.
  • New dvv_search_bounds(eps_max). The docstrings say to cut edge picks in epsilon, never as abs(dvv) < eps_max.

Effect on existing outputs

None on gap-free input. A rerun of _trailing_stack, measure_stretching_trailing, peak_dvv and run_pipeline (stretching, MWCS and DTW; fixed and moving references) on 365 gap-free synthetic days is bit-identical to 5d2d223. Only inputs with NaN days change. The goldens and fig_aggregation are not affected.

Checklist

  • Tests pass locally (pytest): 381 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.
  • 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_peak_dvv_missing_and_edge.py, 11 cases:

  • 6 from 73e9845, all failing on 5d2d223: NaN rows, one missing day and a long gap in the trailing reference, the NaN-aware stack, and run_pipeline with gate=False for fixed and moving references.
  • 5 from 93fff51: the default edge values, flags, guard masking, second_peak_ratio 0.8 on a two-peak row, and dvv_search_bounds(0.03). The flag, guard and ratio tests fail on 5d2d223 (unknown keyword).

Scientific reviewer notes

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

Copilot review follow-up

  • min_frac range in _moving_reference (deviations.py): valid. Only the stretching path validated it. With MWCS, min_frac=2.0 silently returned no epochs and -0.1 behaved like 0. The function now raises ValueError outside [0, 1] before dispatch, and a new test covers the TS and MWCS paths. c4df16e
  • second_peak_ratio for a non-positive peak (synthetic_demo.py peak_dvv): valid. A zero peak gave -inf with a divide-by-zero warning, and a negative peak gave ratios above 1. The ratio is now NaN unless the peak CC is positive, the docstring and a new test cover this, and dv/v and peak CC are unchanged. The second location Copilot named (line 1471, the k <= 1 return in _trailing_stack) has no such division, so nothing changed there. c4df16e

Integration and second Copilot review

Second Copilot review (6190569315, on c4df16e)

  • _trailing_stack skipped the min_frac range check when k <= 1, so min_frac=1.5 was accepted without stacking. It is now checked first (8cc7e36).
  • With k = 1, a row with a single non-finite sample came back partly finite, although the docstring treats any such row as missing. These rows now come back all-NaN. A gap-free input is still returned as the same object, so no output on gap-free data changes (8cc7e36).
  • New tests: test_trailing_stack_rejects_min_frac_out_of_range and test_trailing_stack_no_stacking_partial_nan_row_is_missing. The k = 1 cases fail on c4df16e and pass after the fix.

Merge of docs/sign-convention-manuscript (after #58 and #59): the only conflict was CHANGELOG.md, resolved by keeping all three Fixed entries. synthetic_demo.py merged cleanly. Merge commit b78458c.

Verification on b78458c

Check Result
Figure sidecars, all 19 incl. slow demo_10/11/12, --rtol 1e-5 19 match, 0 differ
golden.regenerate_manifest() vs tests/data/golden/manifest.json byte-identical
Full test suite 443 passed, 1 skipped, 1 failed (known base failure test_aggregate_rejects_missing_shards_and_duplicates)
ruff 0.1.6 / black 23.11.0 on changed .py files clean
Local PDF build + text checks 88 pages, 0 unresolved / ,% / << / ~
CI paper workflow run 47402238508 3 of 3 pass

Third Copilot review (6194956617, on b78458c): one comment on deviations.py:225 about a "Mean of empty slice" warning when none of the first 60 % of days has data. The output is the intended all-NaN (the pre-PR code returned the bogus edge value for every epoch), and the repo does not turn warnings into errors. No code change.

🤖 Generated with Claude Code

mdenolle and others added 2 commits December 3, 2026 16:10
What was wrong: peak_dvv took a bare argmax of each CC row. An all-NaN
row (a missing day, or a NaN reference) picked column 0 and came back as
the finite grid-edge value eps_to_dvv(-eps_max), +6.383 % at eps_max
0.06. The trailing reference in measure_stretching_trailing and the
trailing stack in _trailing_stack are cumulative-sum differences, so one
NaN day made every later reference NaN and every later epoch read
+6.383 % with NaN CC. Rerun on 5d2d223 (160 synthetic days, NaN on day
80, eps_max 0.06): run_pipeline with gate=False kept those epochs as
valid, because valid = isfinite(dvv); with the fixed reference a NaN
day in the first 60 % made every epoch +6.383 %. DTW returned ~0 for a
NaN trace.

What changed:
- peak_dvv returns NaN dv/v and NaN peak CC for any row with a
  non-finite value.
- _trailing_stack and measure_stretching_trailing skip missing rows and
  divide by the number of days with data. New min_frac keyword
  (default 0.5): the stack or reference is NaN when fewer than
  ceil(min_frac * window) days have data.
- deviations.run_pipeline builds the fixed reference from the days with
  data, the generic moving-reference loop skips missing days with the
  same min_frac rule, and any epoch whose stacked waveform is missing is
  set to NaN whatever the estimator returned.

Effect on existing outputs: none on gap-free input. A rerun of
_trailing_stack, measure_stretching_trailing, peak_dvv and run_pipeline
(stretching, MWCS, DTW; fixed and moving) on 365 gap-free synthetic days
is bit-identical to 5d2d223. Only inputs with NaN days change.

Tests: tests/test_peak_dvv_missing_and_edge.py (6 tests, all fail on
5d2d223): NaN rows in peak_dvv, one missing day and a long gap in the
trailing reference, the NaN-aware trailing stack, and run_pipeline with
gate=False and a missing day for the fixed and moving references.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
What was wrong: peak_dvv returned a grid-edge pick as an ordinary
measurement, with no flag. Its dv/v is a bound, and the bounds are
asymmetric because eps_to_dvv is not odd: rerun gives -2.913 % and
+3.093 % at eps_max 0.03. A cut written as abs(dv/v) < eps_max keeps
every -2.913 % edge pick and drops every +3.093 % one. On pure noise
the edge fraction is 0.0525 (rerun recorded in the review synthesis).

What changed:
- peak_dvv gains keyword arguments edge_guard (default 0) and
  return_flags (default False). return_flags=True returns a third item,
  a dict with per-row at_edge (bool) and second_peak_ratio (highest
  other local maximum over the peak CC, NaN if none). edge_guard=g
  returns NaN dv/v for a peak within g grid steps of either end and
  keeps its peak CC. typing overloads keep the 2-tuple return type for
  existing callers.
- New dvv_search_bounds(eps_max) returns (eps_to_dvv(eps_max),
  eps_to_dvv(-eps_max)).
- Docstrings say to cut edge picks in epsilon, never as
  abs(dv/v) < eps_max.

Effect on existing outputs: none. Defaults reproduce the previous
commit; a rerun of peak_dvv, measure_stretching_trailing and
run_pipeline on 365 gap-free synthetic days is bit-identical to
5d2d223. fig_aggregation and the goldens are not touched, so no
regeneration is needed. No FutureWarning is emitted for the default.

Tests: five tests in tests/test_peak_dvv_missing_and_edge.py. Column-0
and last-column peaks give the two bounds by default and are flagged
with return_flags; edge_guard 1 and 3 mask in grid index; a
two-peak row gives second_peak_ratio 0.8; dvv_search_bounds(0.03).
The flag, guard and ratio tests fail on 5d2d223 (unknown keyword).

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

Two moderate-severity active issues remain: a newly added public kwarg (min_frac) lacks the expected [0,1] validation, and second_peak_ratio can yield inf/-inf by dividing by a zero/negative peak CC despite the docstring’s stated assumptions.

2 open issues
What changed in this PR

Fixes a bug where missing (NaN) daily CCF rows could be turned into a finite dv/v value that then propagated through trailing-reference computations, and adds explicit handling/metadata for grid-edge stretching picks.

Changes:

  • Make peak_dvv NaN-safe (non-finite CC rows yield NaN dv/v and NaN peak CC) and add optional edge-related outputs (edge_guard, return_flags, second_peak_ratio) plus dvv_search_bounds.
  • Make trailing references/stacks NaN-aware by skipping missing rows and enforcing a min_frac data-availability threshold.
  • Update the deviations pipeline to build references from available days and to invalidate epochs whose stacked waveform is missing.
  • Add regression tests covering missing-day handling, NaN-aware trailing behavior, and grid-edge picks; document updates in CHANGELOG.md.
File Description
tests/​test_peak_dvv_missing_and_edge.py Adds regression tests for NaN-day handling, NaN-aware trailing stacks/references with min_frac, and grid-edge flags/guarding behavior in peak_dvv.
src/​codameter/​synthetic_demo.py Implements NaN-safe peak_dvv with optional edge flags/guard and second_peak_ratio, introduces dvv_search_bounds, and updates trailing reference/stack helpers to skip missing days using min_frac.
src/​codameter/​deviations.py Updates fixed/moving reference construction and pipeline masking so missing days do not contaminate references and epochs with missing stacked waveforms produce NaN outputs.
CHANGELOG.md Documents the missing-day dv/v fix and the new peak-picking options (edge_guard, return_flags, min_frac, dvv_search_bounds) under Unreleased.

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/deviations.py Resolved
Comment thread src/codameter/synthetic_demo.py Resolved
… NaN for a non-positive peak (#57, Copilot review)

_moving_reference took min_frac without a range check. The stretching
path raised through measure_stretching_trailing, but every other
estimator ran the generic loop unchecked: min_frac=2.0 silently left no
epoch (MWCS on 60 synthetic days, ref_days=30: 0 finite epochs instead
of 30) and min_frac=-0.1 acted as 0. It now raises ValueError for a value
outside [0, 1] before dispatch, with the same message as
measure_stretching_trailing and _trailing_stack.

peak_dvv(return_flags=True) divided the second local maximum by the
peak CC with no sign guard: a zero peak gave -inf with a divide-by-zero
warning, and a negative peak gave a ratio above 1 (2.5 for peak -0.2,
second maximum -0.5). The ratio is now NaN unless the peak CC is
positive; the docstring says so.

Effect on existing outputs: none for valid min_frac or for dv/v and
peak CC. Only out-of-range min_frac now raises, and only rows with a
peak CC <= 0 change their second_peak_ratio, a flag new in this PR.
Defaults are bit-identical on gap-free input.

Tests in tests/test_peak_dvv_missing_and_edge.py that fail on 93fff51
and pass here:
- test_peak_dvv_second_peak_ratio_nan_for_nonpositive_peak
- test_moving_reference_rejects_min_frac_out_of_range[-0.1-MWCS]
- test_moving_reference_rejects_min_frac_out_of_range[1.5-MWCS]
The stretching cases of the last test pass on both and guard the
existing check.

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

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 moderate active finding notes that _trailing_stack() returns early when k<=1 and therefore fails to validate min_frac (silently accepting invalid values and behaving inconsistently with related functions), which can hide configuration errors and warrants changes.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity min_frac is skipped when stacking is disabled

src/​codameter/​synthetic_demo.py:1474

_trailing_stack() skips validating min_frac when k <= 1 (returns early), so invalid values like min_frac=1.5 are silently accepted for the no-stacking case. This makes the API inconsistent with measure_stretching_trailing() / _moving_reference() (which always validate) and can hide configuration errors. Consider validating first, and (optionally) normalizing rows with any non-finite sample to all-NaN even when k==1, to match the docstring’s “any non-finite sample are missing” rule.

2 resolved since last review

Review effort: Balanced

mdenolle and others added 2 commits December 4, 2026 10:17
…k does not stack (#57, Copilot review)

_trailing_stack returned its input before checking min_frac when k <= 1,
so min_frac=1.5 or -0.1 was accepted without stacking while the stacking
path, measure_stretching_trailing and _moving_reference reject it. With
k = 1 a row with one non-finite sample also came back partly finite,
although the docstring treats any such row as missing and the k > 1 path
excludes it.

min_frac is now checked first. With k <= 1 a gap-free input is still
returned as the same object; otherwise a copy is returned with each row
holding any non-finite sample set to all-NaN.

Outputs on gap-free input are unchanged (same object returned), so no
figure, sidecar or golden case moves.

Tests: test_trailing_stack_rejects_min_frac_out_of_range (k = 1 and 10)
and test_trailing_stack_no_stacking_partial_nan_row_is_missing; the k = 1
cases fail before this change and pass after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… 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>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 18:51

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 unresolved issue remains in src/codameter/deviations.py where reference can be computed as the mean of an empty or all-nonfinite early slice, producing warnings and all-NaN output that may destabilize downstream behavior and fail strict test environments.

1 open issue

Review effort: Balanced

Comment on lines +222 to +225
# Long stable stack over the first 60 % of days that have data.
early = ccfs[: int(0.6 * len(ccfs))]
have = np.isfinite(early).all(axis=1)
reference = (early if have.all() else early[have]).mean(axis=0)
@mdenolle

mdenolle commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Second Copilot review

  • Second Copilot review 6190569315 (on c4df16e), part 1: _trailing_stack returns early for k <= 1 without validating min_frac: Valid. _trailing_stack(x, 1, min_frac=1.5) was accepted while k = 10 raised. Fixed in 8cc7e36 by checking min_frac before the no-stacking return, with test_trailing_stack_rejects_min_frac_out_of_range covering k = 1 and k = 10.
  • Second Copilot review 6190569315, part 2 (optional): with k == 1, make rows with any non-finite sample all-NaN, per the docstring: Valid, since the docstring already treats any row with a non-finite sample as missing and the k > 1 path does so. Fixed in 8cc7e36: with k = 1 a gap-free input is still returned as the same object, so no figure, sidecar or golden case changes, and partly non-finite rows now come back all-NaN. Covered by test_trailing_stack_no_stacking_partial_nan_row_is_missing.
  • Third Copilot review 6194956617 (on pushed head b78458c), inline comment 4804467817 at src/codameter/deviations.py:225: The warning is real when none of the first 60 % of days has data, but the result is the intended one: the reference is NaN, so every epoch comes back NaN and invalid (0 of 60 finite in a reproduction, against 60 of 60 at the edge value on the pre-PR base). A one-day series warned the same way before this PR, and the repo does not turn warnings into errors. Left as is; raising a ValueError for an unusable reference could be a separate change.

@mdenolle
mdenolle merged commit aee4a5b into docs/sign-convention-manuscript Dec 4, 2026
4 checks passed
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>
mdenolle added a commit that referenced this pull request Dec 5, 2026
After merging #57 (missing days skipped in measure_stretching_trailing)
with band-limited resampling, nothing exercised the two together: the
#57 tests use band (0.3, 2.0) Hz at fs 50 Hz, where interp="auto" stays
linear. The new test runs the band-limited path at 8-16 Hz with one NaN
day and checks that the day is NaN, later days are finite and match the
day-by-day loop over the reference days with data, and earlier days are
unchanged bit for bit. No code change; outputs unchanged.

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