From 73e984560cc7b1049ef99908e9ac506767bbfb8d Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Thu, 3 Dec 2026 16:10:09 -0800 Subject: [PATCH 1/4] Return NaN dv/v for missing days in peak pick and stacks 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 --- CHANGELOG.md | 11 +++ src/codameter/deviations.py | 44 +++++++-- src/codameter/synthetic_demo.py | 78 +++++++++++++--- tests/test_peak_dvv_missing_and_edge.py | 115 ++++++++++++++++++++++++ 4 files changed, 230 insertions(+), 18 deletions(-) create mode 100644 tests/test_peak_dvv_missing_and_edge.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b238b7..c0a0a86 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 +- A missing day no longer becomes a finite dv/v. `peak_dvv` returns NaN + dv/v and NaN peak CC for any CC row with a non-finite value; before, an + all-NaN row picked column 0 and read as `eps_to_dvv(-eps_max)` + (+6.383 % at `eps_max = 0.06`). `_trailing_stack` and + `measure_stretching_trailing` skip missing days (new `min_frac`, default + 0.5); before, one NaN day entered the cumulative sum and every later + epoch read +6.383 % with NaN CC. `run_pipeline` builds its fixed and + generic moving references from days with data and sets epochs with a + missing stacked waveform to NaN, so `gate=False` no longer keeps them. + Results on gap-free input are unchanged bit for bit. + - 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/src/codameter/deviations.py b/src/codameter/deviations.py index 3a8fa12..53e3783 100644 --- a/src/codameter/deviations.py +++ b/src/codameter/deviations.py @@ -93,7 +93,17 @@ # Run one pipeline configuration on a shared set of daily CCFs. # --------------------------------------------------------------------------- def _moving_reference( - name, ccfs, t, *, band, fs, window, ref_days=45, collect_cc=False, **kw + name, + ccfs, + t, + *, + band, + fs, + window, + ref_days=45, + collect_cc=False, + min_frac=0.5, + **kw, ): """Generic trailing-reference measurement for *any* estimator. @@ -107,17 +117,35 @@ def _moving_reference( :func:`codameter.synthetic_demo.measure_stretching_trailing` fast path (identical to float rounding, ~5x faster); the generic per-day loop below serves every other estimator. + + Missing days (rows with any non-finite sample) are skipped in the + reference, which is the mean of the rows with data and is missing when + fewer than ``ceil(min_frac * ref_days)`` of them have data; a missing day + is NaN itself. Without gaps this is the plain trailing mean. """ if name == "stretching (TS)": out, cc_out = measure_stretching_trailing( - ccfs, t, band=band, fs=fs, window=window, ref_days=ref_days, **kw + ccfs, + t, + band=band, + fs=fs, + window=window, + ref_days=ref_days, + min_frac=min_frac, + **kw, ) return (out, cc_out) if collect_cc else out ndays = ccfs.shape[0] out = np.full(ndays, np.nan) cc_out = np.full(ndays, np.nan) + have = np.isfinite(ccfs).all(axis=1) + need = max(1, int(np.ceil(min_frac * ref_days))) for d in range(ref_days, ndays): - ref = ccfs[d - ref_days : d].mean(axis=0) + in_ref = have[d - ref_days : d] + if not have[d] or in_ref.sum() < need: + continue + rows = ccfs[d - ref_days : d] + ref = rows.mean(axis=0) if in_ref.all() else rows[in_ref].mean(axis=0) if collect_cc: res = METHODS[name](ccfs[d], ref, t, band=band, fs=fs, window=window, **kw) if isinstance(res, tuple): @@ -189,7 +217,10 @@ def run_pipeline(ccfs, t, fs, cfg, *, eps_max=0.05, return_cc=False, prefiltered cc = None if ref == "fixed": - reference = ccfs[: int(0.6 * len(ccfs))].mean(axis=0) # long stable stack + # 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) if name == "stretching (TS)": dvv, cc = measure_stretching( stacked, @@ -241,7 +272,10 @@ def run_pipeline(ccfs, t, fs, cfg, *, eps_max=0.05, return_cc=False, prefiltered else: raise ValueError(ref) - dvv = np.asarray(dvv, float) + dvv = np.array(dvv, float) + # An epoch whose stacked waveform is missing has no measurement, whatever + # value the estimator returned for it (DTW returned ~0 on a NaN trace). + dvv[~np.isfinite(stacked).all(axis=1)] = np.nan valid = np.isfinite(dvv) if cfg.get("gate") and ref in ("fixed", "moving"): # The gate is a property of the data at this band, window, stack and diff --git a/src/codameter/synthetic_demo.py b/src/codameter/synthetic_demo.py index 7aa088d..24bf40a 100644 --- a/src/codameter/synthetic_demo.py +++ b/src/codameter/synthetic_demo.py @@ -512,12 +512,25 @@ def peak_dvv(es: np.ndarray, cc: np.ndarray) -> tuple[np.ndarray, np.ndarray]: a current waveform that had to be *dilated* to match the reference (``epsilon > 0``) means travel times lengthened, i.e. the velocity *dropped*. (Before v0.4.0 this returned epsilon itself, labeled dv/v.) + + A row of ``cc`` holding any non-finite value (a missing day, or a NaN + reference) returns NaN for both dv/v and the peak CC. Before this was + enforced, ``argmax`` of an all-NaN row picked column 0, so a missing day + came back as the finite grid-edge value ``eps_to_dvv(-eps_max)`` + (+6.383 % at ``eps_max = 0.06``). """ - cc = np.atleast_2d(cc) - idx = np.argmax(cc, axis=1) + cc = np.atleast_2d(np.asarray(cc, dtype=float)) + ndays = cc.shape[0] + ok = np.isfinite(cc).all(axis=1) + idx = np.argmax(np.where(ok[:, None], cc, -np.inf), axis=1) de = es[1] - es[0] - eps = np.array([es[i] + _parabolic(cc[d], i) * de for d, i in enumerate(idx)]) - return eps_to_dvv(eps), cc[np.arange(cc.shape[0]), idx] + eps = np.full(ndays, np.nan) + peak = np.full(ndays, np.nan) + for d in np.flatnonzero(ok): + i = idx[d] + eps[d] = es[i] + _parabolic(cc[d], i) * de + peak[d] = cc[d, i] + return eps_to_dvv(eps), peak def measure_stretching( @@ -601,6 +614,7 @@ def measure_stretching_trailing( eps_max: float = 0.06, n_eps: int = 161, prefiltered: bool = False, + min_frac: float = 0.5, ) -> tuple[np.ndarray, np.ndarray]: """Vectorized stretching against a trailing reference (previous ``ref_days``). @@ -617,18 +631,36 @@ def measure_stretching_trailing( Returns ``(dvv, cc)`` over the full length of ``cur_mat``; the ``ref_days`` warm-up epochs are NaN. + + Missing days (rows with any non-finite sample) are skipped: the reference + for day d is the mean of the rows in ``[d - ref_days, d)`` that have data, + and is NaN when fewer than ``ceil(min_frac * ref_days)`` (at least one) + of them do. A missing day itself returns NaN. Without gaps the result is + bit-identical to the plain trailing mean. (Before this, one NaN day + entered the cumulative sum and made every later reference NaN, and every + later epoch came back as the grid-edge value.) """ + if not 0.0 <= min_frac <= 1.0: + raise ValueError(f"min_frac must lie in [0, 1], got {min_frac}") cur_mat = np.atleast_2d(np.asarray(cur_mat, float)) ndays, nlag = cur_mat.shape dvv = np.full(ndays, np.nan) cc_peak = np.full(ndays, np.nan) if ndays <= ref_days: return dvv, cc_peak - # Trailing reference for day d is the mean of rows [d - ref_days, d). - csum = np.cumsum(cur_mat, axis=0, dtype=np.float64) + # Trailing reference for day d is the mean of the rows in [d - ref_days, d) + # that have data; missing rows contribute zero to the sum and to the count. + ok = np.isfinite(cur_mat).all(axis=1) + filled = cur_mat if ok.all() else np.where(ok[:, None], cur_mat, 0.0) + csum = np.cumsum(filled, axis=0, dtype=np.float64) + cnt = np.cumsum(ok, dtype=np.float64) head = csum[ref_days - 1 : ndays - 1] tail = np.concatenate([np.zeros((1, nlag)), csum[: ndays - ref_days - 1]], axis=0) - refs = (head - tail) / float(ref_days) + nref = cnt[ref_days - 1 : ndays - 1] - np.concatenate( + [[0.0], cnt[: ndays - ref_days - 1]] + ) + refs = (head - tail) / np.maximum(nref, 1.0)[:, None] + refs[nref < max(1, int(np.ceil(min_frac * ref_days)))] = np.nan reffs = refs if prefiltered else bandpass(refs, fs, *band) sel, _ = _stretch_window(t, window, eps_max, branch) @@ -1333,18 +1365,38 @@ def _boost_fonts(*axes, tick=13.0, label=15.0, title=16.0): ax.title.set_size(title) -def _trailing_stack(ccfs: np.ndarray, k: int) -> np.ndarray: +def _trailing_stack(ccfs: np.ndarray, k: int, min_frac: float = 0.5) -> np.ndarray: + """Trailing mean of the last ``k`` days, skipping missing (NaN) days. + + Day d averages the rows in ``[d - k + 1, d]`` that have data (rows with + any non-finite sample are missing). The window is shorter at the start + of the series. Day d is NaN when fewer than ``ceil(min_frac * w)`` (at + least one) of the ``w = min(d + 1, k)`` rows in its window have data, so + a stack never reaches back across a long gap with a single day. Without + gaps the result is bit-identical to the plain trailing mean. (Before + this, one NaN day entered the cumulative sum and made every later stack + NaN.) + """ if k <= 1: return ccfs - # Trailing mean of the last k days (shorter at the start), as a difference - # of float64 cumulative sums: O(ndays * nlag) instead of O(ndays * k * nlag). + if not 0.0 <= min_frac <= 1.0: + raise ValueError(f"min_frac must lie in [0, 1], got {min_frac}") + # Trailing mean as a difference of float64 cumulative sums: + # O(ndays * nlag) instead of O(ndays * k * nlag). ndays = ccfs.shape[0] - csum = np.cumsum(ccfs, axis=0, dtype=np.float64) + ok = np.isfinite(ccfs).all(axis=1) + filled = ccfs if ok.all() else np.where(ok[:, None], ccfs, 0.0) + csum = np.cumsum(filled, axis=0, dtype=np.float64) out = np.empty_like(csum) out[:k] = csum[:k] np.subtract(csum[k:], csum[:-k], out=out[k:]) # window sum over [d-k+1, d] - counts = np.minimum(np.arange(1, ndays + 1), k).astype(np.float64) - out /= counts[:, None] + cnt = np.cumsum(ok, dtype=np.float64) + counts = cnt.copy() + counts[k:] -= cnt[:-k] # rows with data in [d-k+1, d] + out /= np.maximum(counts, 1.0)[:, None] + window = np.minimum(np.arange(1, ndays + 1), k) + need = np.maximum(1, np.ceil(min_frac * window)) + out[counts < need] = np.nan return out diff --git a/tests/test_peak_dvv_missing_and_edge.py b/tests/test_peak_dvv_missing_and_edge.py new file mode 100644 index 0000000..e404635 --- /dev/null +++ b/tests/test_peak_dvv_missing_and_edge.py @@ -0,0 +1,115 @@ +"""Missing days and grid-edge peaks in the stretching peak pick. + +A missing day (a NaN row in the CCF matrix) must come back as NaN, never as a +finite dv/v. Before the fix, ``np.argmax`` of an all-NaN CC row returned +column 0, so the missing day read as ``eps_to_dvv(-eps_max)`` (+6.383 % at +``eps_max = 0.06``), and the trailing-reference cumulative sum carried the +NaN into every later reference, so every later epoch read the same value. +""" + +from __future__ import annotations + +import numpy as np +import pytest +from codameter import deviations as D +from codameter.synthetic_demo import ( + Synth, + _trailing_stack, + daily_ccfs, + eps_to_dvv, + measure_stretching_trailing, + peak_dvv, +) + +BAND = (0.3, 2.0) +WINDOW = (8.0, 35.0) +FS = 50.0 +EPS_MAX = 0.06 +EDGE_DVV = float(eps_to_dvv(-EPS_MAX)) # +6.383 %, the value a NaN row used to get + + +@pytest.fixture(scope="module") +def gappy(): + s = Synth() + days = np.arange(0, 160) + truth = 0.004 * np.sin(2 * np.pi * days / 50) + ccfs = daily_ccfs(s.t, [s.ref], [truth], fs=s.fs, snr=8.0, seed=11) + gap = ccfs.copy() + gap[80] = np.nan + return s, truth, ccfs, gap + + +# --------------------------------------------------------------------------- +# C2: non-finite rows return NaN +# --------------------------------------------------------------------------- +def test_peak_dvv_nonfinite_row_returns_nan(): + es = np.linspace(-EPS_MAX, EPS_MAX, 161) + good = np.exp(-(((es - 0.01) / 0.005) ** 2)) + one_nan = good.copy() + one_nan[40] = np.nan + cc = np.vstack([good, np.full_like(good, np.nan), one_nan]) + dvv, pk = peak_dvv(es, cc) + assert dvv[0] == pytest.approx(float(eps_to_dvv(0.01)), abs=1e-4) + assert pk[0] == pytest.approx(1.0, abs=5e-3) + assert np.isnan(dvv[1:]).all() and np.isnan(pk[1:]).all() + + +def test_trailing_reference_survives_one_missing_day(gappy): + s, truth, ccfs, gap = gappy + kw = dict(band=BAND, fs=FS, window=WINDOW, ref_days=30, eps_max=EPS_MAX) + clean, _ = measure_stretching_trailing(ccfs, s.t, **kw) + dvv, cc = measure_stretching_trailing(gap, s.t, **kw) + assert np.isnan(dvv[80]) and np.isnan(cc[80]) + later = np.r_[81:160] + assert np.isfinite(dvv[later]).all() and np.isfinite(cc[later]).all() + assert not np.isclose(dvv[later], EDGE_DVV).any() + # Days before the gap are bit-identical; days whose reference window has + # passed the gap differ only by cumulative-sum rounding. + np.testing.assert_array_equal(dvv[:80], clean[:80]) + np.testing.assert_allclose(dvv[111:], clean[111:], rtol=0, atol=1e-12) + # Days whose window holds the gap use 29 of 30 days: still close to clean. + np.testing.assert_allclose(dvv[81:111], clean[81:111], atol=2e-4) + + +def test_trailing_reference_long_gap_obeys_min_frac(gappy): + s, truth, ccfs, _ = gappy + gap = ccfs.copy() + gap[60:80] = np.nan # 20 of the 30 reference days missing for day 80 + kw = dict(band=BAND, fs=FS, window=WINDOW, ref_days=30, eps_max=EPS_MAX) + dvv, _ = measure_stretching_trailing(gap, s.t, min_frac=0.5, **kw) + assert np.isnan(dvv[80]) # 10 < ceil(0.5 * 30) days with data + assert np.isnan(dvv[94]) # 14 days with data + assert np.isfinite(dvv[95]) # 15 days with data + dvv0, _ = measure_stretching_trailing(gap, s.t, min_frac=0.0, **kw) + assert np.isfinite(dvv0[80]) + with pytest.raises(ValueError): + measure_stretching_trailing(gap, s.t, min_frac=1.5, **kw) + + +def test_trailing_stack_skips_missing_day(gappy): + _, _, ccfs, gap = gappy + k = 10 + out = _trailing_stack(gap, k) + for d in (79, 80, 81, 85, 89, 90): + rows = gap[max(0, d - k + 1) : d + 1] + rows = rows[np.isfinite(rows).all(axis=1)] + np.testing.assert_allclose(out[d], rows.mean(axis=0), rtol=0, atol=1e-12) + assert np.isfinite(out[80:]).all() + # Without gaps the result is unchanged. + np.testing.assert_array_equal(_trailing_stack(ccfs, k)[:80], out[:80]) + # A gap longer than (1 - min_frac) * k leaves the stack missing. + long_gap = ccfs.copy() + long_gap[50:58] = np.nan + assert np.isnan(_trailing_stack(long_gap, k, min_frac=0.5)[57]).all() + assert np.isfinite(_trailing_stack(long_gap, k, min_frac=0.2)[57]).all() + + +@pytest.mark.parametrize("reference", ["fixed", "moving"]) +def test_run_pipeline_missing_day_gate_false_is_nan(gappy, reference): + """Missing day with gate=False yields NaN, not +6.38 %.""" + s, truth, _, gap = gappy + cfg = dict(D.BASELINE, reference=reference, stack=1, gate=False) + dvv, valid = D.run_pipeline(gap, s.t, s.fs, cfg, eps_max=EPS_MAX) + assert np.isnan(dvv[80]) and not valid[80] + assert not np.isclose(dvv[valid], EDGE_DVV).any() + assert valid[81:].all() From 93fff517103ce444f281d3d57dc19152b267157c Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Thu, 3 Dec 2026 16:16:11 -0800 Subject: [PATCH 2/4] Add grid-edge flags, edge guard and dv/v search bounds to peak_dvv 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 --- CHANGELOG.md | 8 ++ src/codameter/synthetic_demo.py | 97 ++++++++++++++++++++++++- tests/test_peak_dvv_missing_and_edge.py | 67 +++++++++++++++++ 3 files changed, 169 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0a0a86..12dd415 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ### Added +- `peak_dvv(edge_guard=0, return_flags=False)`: `return_flags=True` adds + 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. New + `dvv_search_bounds(eps_max)` gives the asymmetric dv/v bounds of the + grid (-2.913 % and +3.093 % at `eps_max = 0.03`). Cut edge picks in + epsilon, never as `abs(dv/v) < eps_max`, which keeps one edge and drops + the other. Defaults leave every existing result unchanged. + - `golden.advisory_case`: public seasonal development examples for all six applications, independent of private evaluation records. Advisor snippets use per-channel recovery, fixed scoring support, and report availability. diff --git a/src/codameter/synthetic_demo.py b/src/codameter/synthetic_demo.py index 24bf40a..ac04a69 100644 --- a/src/codameter/synthetic_demo.py +++ b/src/codameter/synthetic_demo.py @@ -41,6 +41,7 @@ import warnings from dataclasses import dataclass, field from pathlib import Path +from typing import Literal, overload import numpy as np @@ -502,7 +503,53 @@ def dvv_to_epsilon(dvv): return -dvv / (1.0 + dvv) -def peak_dvv(es: np.ndarray, cc: np.ndarray) -> tuple[np.ndarray, np.ndarray]: +def dvv_search_bounds(eps_max: float) -> tuple[float, float]: + """The ``(lowest, highest)`` dv/v a stretching grid ``[-eps_max, eps_max]`` can return. + + The map :func:`eps_to_dvv` is not odd, so the bounds are asymmetric: at + ``eps_max = 0.03`` they are -2.913 % (``eps = +eps_max``, the last grid + column) and +3.093 % (``eps = -eps_max``, column 0). A dv/v at either + bound is a grid-edge pick, i.e. the true peak may lie outside the grid. + Cut edge picks in epsilon (grid index, see ``peak_dvv(return_flags=True)``), + never as ``abs(dv/v) < eps_max``: that test keeps every -2.913 % edge pick + and drops every +3.093 % one, which biases the kept set negative. + """ + if not eps_max > 0.0: + raise ValueError(f"eps_max must be positive, got {eps_max}") + return float(eps_to_dvv(eps_max)), float(eps_to_dvv(-eps_max)) + + +@overload +def peak_dvv( + es: np.ndarray, + cc: np.ndarray, + *, + edge_guard: int = ..., + return_flags: Literal[False] = ..., +) -> tuple[np.ndarray, np.ndarray]: + ... + + +@overload +def peak_dvv( + es: np.ndarray, + cc: np.ndarray, + *, + edge_guard: int = ..., + return_flags: Literal[True], +) -> tuple[np.ndarray, np.ndarray, dict[str, np.ndarray]]: + ... + + +def peak_dvv( + es: np.ndarray, + cc: np.ndarray, + *, + edge_guard: int = 0, + return_flags: bool = False, +) -> ( + tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, dict[str, np.ndarray]] +): """Peak-pick a ``CC(epsilon, time)`` image → (dv/v per time, peak CC). Returns **physical dv/v** = ``-epsilon / (1 + epsilon)`` at the @@ -518,9 +565,33 @@ def peak_dvv(es: np.ndarray, cc: np.ndarray) -> tuple[np.ndarray, np.ndarray]: enforced, ``argmax`` of an all-NaN row picked column 0, so a missing day came back as the finite grid-edge value ``eps_to_dvv(-eps_max)`` (+6.383 % at ``eps_max = 0.06``). + + **Grid-edge picks.** A peak on the first or last grid column means the + true peak may lie outside ``[-eps_max, eps_max]``; its dv/v is a bound, + not a measurement. By default (``edge_guard=0``) such picks are returned + unchanged. With ``edge_guard = g >= 1`` a peak within ``g`` grid steps of + either end (columns ``0 .. g-1`` and ``n-g .. n-1``) returns NaN dv/v; + its peak CC is kept. Cut edge picks in epsilon, as here, never as + ``abs(dv/v) < eps_max``: the dv/v bounds are asymmetric (-2.913 % and + +3.093 % at ``eps_max = 0.03``, see :func:`dvv_search_bounds`), so that + test keeps one edge and drops the other. + + With ``return_flags=True`` a third item is returned, a dict of per-row + arrays: + + - ``at_edge`` (bool): the peak lies in the guarded columns, or on column + 0 or ``n-1`` when ``edge_guard=0``. False for non-finite rows. + - ``second_peak_ratio`` (float): the highest other local maximum of the + row (an end column counts when it exceeds its one neighbour) divided by + the peak CC. Near 1 means an ambiguous pick, e.g. a cycle skip. NaN when + the row has no other local maximum or is non-finite. Meaningful for a + positive peak CC only. """ + edge_guard = int(edge_guard) + if edge_guard < 0: + raise ValueError(f"edge_guard must be >= 0, got {edge_guard}") cc = np.atleast_2d(np.asarray(cc, dtype=float)) - ndays = cc.shape[0] + ndays, n_eps = cc.shape ok = np.isfinite(cc).all(axis=1) idx = np.argmax(np.where(ok[:, None], cc, -np.inf), axis=1) de = es[1] - es[0] @@ -530,7 +601,27 @@ def peak_dvv(es: np.ndarray, cc: np.ndarray) -> tuple[np.ndarray, np.ndarray]: i = idx[d] eps[d] = es[i] + _parabolic(cc[d], i) * de peak[d] = cc[d, i] - return eps_to_dvv(eps), peak + margin = max(edge_guard, 1) + at_edge = ok & ((idx < margin) | (idx > n_eps - 1 - margin)) + if edge_guard > 0: + eps[at_edge] = np.nan + dvv = eps_to_dvv(eps) + if not return_flags: + return dvv, peak + # Local maxima: interior columns above the left and not below the right + # neighbour; end columns above their single neighbour. + lmax = np.zeros(cc.shape, dtype=bool) + if n_eps >= 2: + lmax[:, 1:-1] = (cc[:, 1:-1] > cc[:, :-2]) & (cc[:, 1:-1] >= cc[:, 2:]) + lmax[:, 0] = cc[:, 0] > cc[:, 1] + lmax[:, -1] = cc[:, -1] > cc[:, -2] + lmax[np.arange(ndays), idx] = False + lmax &= ok[:, None] + other = np.where(lmax, cc, -np.inf).max(axis=1) + ratio = np.full(ndays, np.nan) + has = np.isfinite(other) + ratio[has] = other[has] / peak[has] + return dvv, peak, {"at_edge": at_edge, "second_peak_ratio": ratio} def measure_stretching( diff --git a/tests/test_peak_dvv_missing_and_edge.py b/tests/test_peak_dvv_missing_and_edge.py index e404635..031251b 100644 --- a/tests/test_peak_dvv_missing_and_edge.py +++ b/tests/test_peak_dvv_missing_and_edge.py @@ -16,6 +16,7 @@ Synth, _trailing_stack, daily_ccfs, + dvv_search_bounds, eps_to_dvv, measure_stretching_trailing, peak_dvv, @@ -113,3 +114,69 @@ def test_run_pipeline_missing_day_gate_false_is_nan(gappy, reference): assert np.isnan(dvv[80]) and not valid[80] assert not np.isclose(dvv[valid], EDGE_DVV).any() assert valid[81:].all() + + +# --------------------------------------------------------------------------- +# C3: grid-edge flags, edge guard and search bounds +# --------------------------------------------------------------------------- +ES03 = np.linspace(-0.03, 0.03, 241) + + +def _edge_image(): + """Rows peaked at column 0, at the last column, at column 2, and inside.""" + n = ES03.size + cc = np.zeros((4, n)) + cc[0, 0] = 1.0 + cc[1, -1] = 1.0 + cc[2, 2] = 1.0 + cc[3, :] = np.exp(-(((ES03 - 0.01) / 0.004) ** 2)) + return cc + + +def test_dvv_search_bounds_are_asymmetric(): + lo, hi = dvv_search_bounds(0.03) + assert lo == pytest.approx(-0.029126, abs=1e-6) + assert hi == pytest.approx(0.030928, abs=1e-6) + with pytest.raises(ValueError): + dvv_search_bounds(0.0) + + +def test_peak_dvv_default_unchanged_at_edges(): + cc = _edge_image() + dvv, pk = peak_dvv(ES03, cc) + lo, hi = dvv_search_bounds(0.03) + assert dvv[0] == pytest.approx(hi, abs=1e-12) # column 0 -> +3.093 % + assert dvv[1] == pytest.approx(lo, abs=1e-12) # last column -> -2.913 % + np.testing.assert_array_equal(pk, [1.0, 1.0, 1.0, cc[3].max()]) + + +def test_peak_dvv_flags_column_0_and_last_column(): + cc = _edge_image() + dvv, pk, flags = peak_dvv(ES03, cc, return_flags=True) + np.testing.assert_array_equal(flags["at_edge"], [True, True, False, False]) + np.testing.assert_array_equal(dvv, peak_dvv(ES03, cc)[0]) + + +def test_peak_dvv_edge_guard_masks_in_eps(): + cc = _edge_image() + dvv, pk, flags = peak_dvv(ES03, cc, edge_guard=1, return_flags=True) + assert np.isnan(dvv[:2]).all() and np.isfinite(dvv[2:]).all() + np.testing.assert_array_equal(pk[:2], [1.0, 1.0]) # peak CC is kept + dvv3, _, flags3 = peak_dvv(ES03, cc, edge_guard=3, return_flags=True) + np.testing.assert_array_equal(flags3["at_edge"], [True, True, True, False]) + assert np.isnan(dvv3[:3]).all() and np.isfinite(dvv3[3]) + with pytest.raises(ValueError): + peak_dvv(ES03, cc, edge_guard=-1) + + +def test_peak_dvv_second_peak_ratio(): + n = ES03.size + two = np.exp(-(((ES03 - 0.01) / 0.002) ** 2)) + two += 0.8 * np.exp(-(((ES03 + 0.01) / 0.002) ** 2)) + one = np.exp(-(((ES03 - 0.01) / 0.004) ** 2)) + cc = np.vstack([two, one, np.full(n, np.nan)]) + _, _, flags = peak_dvv(ES03, cc, return_flags=True) + r = flags["second_peak_ratio"] + assert r[0] == pytest.approx(0.8, abs=1e-3) + assert np.isnan(r[1]) and np.isnan(r[2]) + assert not flags["at_edge"][2] From c4df16eaf1dffc844e3c8bd5f6aa84882abb8e7b Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Fri, 4 Dec 2026 06:12:24 -0800 Subject: [PATCH 3/4] Validate min_frac in the moving reference and leave second_peak_ratio 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 --- src/codameter/deviations.py | 2 ++ src/codameter/synthetic_demo.py | 6 ++--- tests/test_peak_dvv_missing_and_edge.py | 33 +++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/codameter/deviations.py b/src/codameter/deviations.py index 53e3783..96191fe 100644 --- a/src/codameter/deviations.py +++ b/src/codameter/deviations.py @@ -123,6 +123,8 @@ def _moving_reference( fewer than ``ceil(min_frac * ref_days)`` of them have data; a missing day is NaN itself. Without gaps this is the plain trailing mean. """ + if not 0.0 <= min_frac <= 1.0: + raise ValueError(f"min_frac must lie in [0, 1], got {min_frac}") if name == "stretching (TS)": out, cc_out = measure_stretching_trailing( ccfs, diff --git a/src/codameter/synthetic_demo.py b/src/codameter/synthetic_demo.py index ac04a69..c72ab4d 100644 --- a/src/codameter/synthetic_demo.py +++ b/src/codameter/synthetic_demo.py @@ -584,8 +584,8 @@ def peak_dvv( - ``second_peak_ratio`` (float): the highest other local maximum of the row (an end column counts when it exceeds its one neighbour) divided by the peak CC. Near 1 means an ambiguous pick, e.g. a cycle skip. NaN when - the row has no other local maximum or is non-finite. Meaningful for a - positive peak CC only. + the row has no other local maximum, is non-finite, or has a peak CC + that is not positive (the ratio has no meaning there). """ edge_guard = int(edge_guard) if edge_guard < 0: @@ -619,7 +619,7 @@ def peak_dvv( lmax &= ok[:, None] other = np.where(lmax, cc, -np.inf).max(axis=1) ratio = np.full(ndays, np.nan) - has = np.isfinite(other) + has = np.isfinite(other) & (peak > 0) ratio[has] = other[has] / peak[has] return dvv, peak, {"at_edge": at_edge, "second_peak_ratio": ratio} diff --git a/tests/test_peak_dvv_missing_and_edge.py b/tests/test_peak_dvv_missing_and_edge.py index 031251b..ddbeba8 100644 --- a/tests/test_peak_dvv_missing_and_edge.py +++ b/tests/test_peak_dvv_missing_and_edge.py @@ -9,6 +9,8 @@ from __future__ import annotations +import warnings + import numpy as np import pytest from codameter import deviations as D @@ -180,3 +182,34 @@ def test_peak_dvv_second_peak_ratio(): assert r[0] == pytest.approx(0.8, abs=1e-3) assert np.isnan(r[1]) and np.isnan(r[2]) assert not flags["at_edge"][2] + + +def test_peak_dvv_second_peak_ratio_nan_for_nonpositive_peak(): + # A zero peak CC used to give -inf (with a divide-by-zero warning) and a + # negative one a ratio above 1; both are NaN now. + zero = -np.ones(ES03.size) + zero[40], zero[20] = 0.0, -0.5 + neg = -np.ones(ES03.size) + neg[40], neg[20] = -0.2, -0.5 + with warnings.catch_warnings(): + warnings.simplefilter("error") + _, pk, flags = peak_dvv(ES03, np.vstack([zero, neg]), return_flags=True) + np.testing.assert_array_equal(pk, [0.0, -0.2]) + assert np.isnan(flags["second_peak_ratio"]).all() + + +@pytest.mark.parametrize("name", ["stretching (TS)", "MWCS"]) +@pytest.mark.parametrize("min_frac", [-0.1, 1.5]) +def test_moving_reference_rejects_min_frac_out_of_range(gappy, name, min_frac): + s, _, ccfs, _ = gappy + with pytest.raises(ValueError, match="min_frac"): + D._moving_reference( + name, + ccfs[:40], + s.t, + band=BAND, + fs=FS, + window=WINDOW, + ref_days=30, + min_frac=min_frac, + ) From 8cc7e361788bdcda99b282789327d96f51bf2f97 Mon Sep 17 00:00:00 2001 From: Marine Denolle Date: Fri, 4 Dec 2026 10:17:31 -0800 Subject: [PATCH 4/4] Validate min_frac and mask partly non-finite rows when _trailing_stack 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 --- CHANGELOG.md | 10 ++++++---- src/codameter/synthetic_demo.py | 12 +++++++++--- tests/test_peak_dvv_missing_and_edge.py | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12dd415..97e22b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,10 +29,12 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht all-NaN row picked column 0 and read as `eps_to_dvv(-eps_max)` (+6.383 % at `eps_max = 0.06`). `_trailing_stack` and `measure_stretching_trailing` skip missing days (new `min_frac`, default - 0.5); before, one NaN day entered the cumulative sum and every later - epoch read +6.383 % with NaN CC. `run_pipeline` builds its fixed and - generic moving references from days with data and sets epochs with a - missing stacked waveform to NaN, so `gate=False` no longer keeps them. + 0.5, checked to lie in [0, 1]; with `k = 1` `_trailing_stack` returns a + row with any non-finite sample as all-NaN); before, one NaN day entered + the cumulative sum and every later epoch read +6.383 % with NaN CC. + `run_pipeline` builds its fixed and generic moving references from days + with data and sets epochs with a missing stacked waveform to NaN, so + `gate=False` no longer keeps them. Results on gap-free input are unchanged bit for bit. - Enlarge the calibration table, preserve nonzero Monte Carlo standard errors, diff --git a/src/codameter/synthetic_demo.py b/src/codameter/synthetic_demo.py index c72ab4d..090b01b 100644 --- a/src/codameter/synthetic_demo.py +++ b/src/codameter/synthetic_demo.py @@ -1468,14 +1468,20 @@ def _trailing_stack(ccfs: np.ndarray, k: int, min_frac: float = 0.5) -> np.ndarr this, one NaN day entered the cumulative sum and made every later stack NaN.) """ - if k <= 1: - return ccfs if not 0.0 <= min_frac <= 1.0: raise ValueError(f"min_frac must lie in [0, 1], got {min_frac}") + ok = np.isfinite(ccfs).all(axis=1) + if k <= 1: + # No stacking: the input itself, with a partly non-finite row made + # all-NaN like any other missing day. + if ok.all(): + return ccfs + out = np.array(ccfs, dtype=np.result_type(ccfs, np.float64)) + out[~ok] = np.nan + return out # Trailing mean as a difference of float64 cumulative sums: # O(ndays * nlag) instead of O(ndays * k * nlag). ndays = ccfs.shape[0] - ok = np.isfinite(ccfs).all(axis=1) filled = ccfs if ok.all() else np.where(ok[:, None], ccfs, 0.0) csum = np.cumsum(filled, axis=0, dtype=np.float64) out = np.empty_like(csum) diff --git a/tests/test_peak_dvv_missing_and_edge.py b/tests/test_peak_dvv_missing_and_edge.py index ddbeba8..7a38d8e 100644 --- a/tests/test_peak_dvv_missing_and_edge.py +++ b/tests/test_peak_dvv_missing_and_edge.py @@ -213,3 +213,27 @@ def test_moving_reference_rejects_min_frac_out_of_range(gappy, name, min_frac): ref_days=30, min_frac=min_frac, ) + + +@pytest.mark.parametrize("k", [1, 10]) +@pytest.mark.parametrize("min_frac", [-0.1, 1.5]) +def test_trailing_stack_rejects_min_frac_out_of_range(gappy, k, min_frac): + """min_frac is checked with or without stacking (k = 1 used to skip it).""" + _, _, ccfs, _ = gappy + with pytest.raises(ValueError, match="min_frac"): + _trailing_stack(ccfs[:40], k, min_frac=min_frac) + + +def test_trailing_stack_no_stacking_partial_nan_row_is_missing(gappy): + """With k = 1 a row with any non-finite sample comes back all-NaN.""" + _, _, ccfs, _ = gappy + # Gap-free input is returned as is. + assert _trailing_stack(ccfs, 1) is ccfs + part = ccfs[:40].copy() + part[7, 100] = np.nan + part[9, 3] = np.inf + out = _trailing_stack(part, 1) + assert np.isnan(out[[7, 9]]).all() + keep = np.setdiff1d(np.arange(40), [7, 9]) + np.testing.assert_array_equal(out[keep], part[keep]) + assert np.isinf(part[9, 3]) # the input is not modified