Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht
`min_length`, `rolling_window` and `guard`, and `ljung_box_test` requires integer `n_fitted` (both raise
`TypeError` otherwise). `rolling_zscore` is unchanged. (C4)

- `coda_window_from_envelope` no longer returns a zero-length or
one-sample window. It raises `ValueError` when `floor_window` misses the
positive-lag support, and names the max lag. The envelope roll-off over
the last `(n - 1) // 2` samples of the `n`-sample boxcar (about
`smooth_s / 2` s) is excluded from the floor. New `min_cycles`
(default 3) makes the window span at least 3 periods of `band[0]`, with a
warning; `band[0] <= 0` or `min_cycles <= 0` raises. `_stretch_window`
raises below `min_samples` (default 8). Before, window (3, 3) gave dv/v
+3.35 to +3.81 % at cc 1.000 for a -0.5 % truth. The demo_15 window ends
move by 0.02 to 0.04 s; quoted values unchanged.

- 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)
Expand Down
6 changes: 4 additions & 2 deletions literature/figs/demo_15_window_envelope.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
"figure": "demo_15_window_envelope",
"generator": "codameter.synthetic_demo.fig_window_envelope",
"codameter_version": "0.4.0",
"git_commit": "141e7bc25bb439420c5ee73223bf78eb4ca7a839",
"generated_utc": "2026-09-10T18:31:11+00:00",
"git_commit": "182351a634579e47981f55880e1739f0165c5426",
"git_dirty": false,
"generator_digest": "c10090402e3e",
"generated_utc": "2026-12-04T16:11:21+00:00",
"python": "3.12.13",
"numpy": "2.4.3",
"matplotlib": "3.10.9",
Expand Down
Binary file modified literature/figs/demo_15_window_envelope.npz
Binary file not shown.
Binary file modified literature/figs/demo_15_window_envelope.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
77 changes: 73 additions & 4 deletions src/codameter/synthetic_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,8 @@ def _stretch_window(
window: tuple[float, float],
eps_max: float,
branch: str = "both",
*,
min_samples: int = 8,
) -> tuple[np.ndarray, tuple[float, float]]:
"""Window mask shared by every trial epsilon in a stretching search.

Expand All @@ -371,6 +373,13 @@ def _stretch_window(
changing valid-support size cannot spuriously change which epsilon
looks like the best-correlated one.

A window holding fewer than ``min_samples`` samples on the selected
``branch`` raises ``ValueError``: with ``branch="both"`` the samples of
both lag signs are counted together, with ``"causal"`` or ``"acausal"``
only that side is counted. With one or two samples the normalised
correlation is 1 for almost any trial epsilon, so the peak picker would
return an arbitrary dv/v at cc = 1 instead of failing.

Returns ``(sel, (w0, w1))``: ``sel`` is the boolean mask on ``t``, and
``(w0, w1)`` is the (possibly shrunk) window actually used.
"""
Expand All @@ -393,7 +402,16 @@ def _stretch_window(
stacklevel=3,
)
w1 = safe_w1
return _window_mask(t, (w0, w1), branch), (w0, w1)
sel = _window_mask(t, (w0, w1), branch)
n_sel = int(np.count_nonzero(sel))
if n_sel < min_samples:
Comment on lines +406 to +407
raise ValueError(
f"coda window ({w0:g}, {w1:g}) on branch {branch!r} holds "
f"{n_sel} sample(s), fewer than min_samples={min_samples}; the "
"stretching correlation is degenerate (cc = 1 for almost any "
"trial epsilon). Widen the window."
)
return sel, (w0, w1)


def _parabolic(y: np.ndarray, i: int) -> float:
Expand Down Expand Up @@ -1364,6 +1382,7 @@ def coda_window_from_envelope(
floor_window: tuple[float, float] = (40.0, 50.0),
persist_s: float = 3.0,
smooth_s: float = 1.5,
min_cycles: float = 3.0,
) -> tuple[float, float]:
"""Pick the coda window automatically: track the envelope, stop where it flattens.

Expand All @@ -1382,13 +1401,47 @@ def coda_window_from_envelope(
:func:`make_freqdep_coda`), so this returns a *shorter* window at high
frequency and a *longer* one at low frequency without being told the band
in advance -- it discovers the covariation from the data.

The smoothed envelope is a ``mode="same"`` boxcar of ``n`` samples
(``n = max(1, int(smooth_s * fs))``), so its last ``(n - 1) // 2``
samples (about ``smooth_s / 2`` seconds) roll off against the zero
padding. Those samples are excluded from the floor estimate. ``ValueError`` is
raised when ``floor_window`` does not overlap the remaining positive-lag
support (for example the default ``(40, 50)`` on a trace with a 25 s max
lag); pass a ``floor_window`` inside the trace instead.

The returned window spans at least ``min_cycles`` periods of ``band[0]``.
When the envelope already sits on the floor at ``t_start`` (short,
strongly attenuated high-frequency coda), the window end is pushed to
``t_start + min_cycles / band[0]`` with a ``UserWarning``. ``ValueError``
is raised if that end lies past the trace's max lag. ``ValueError`` is
also raised when ``band[0]`` or ``min_cycles`` is not positive, since
either would disable that guard.
"""
if not band[0] > 0:
raise ValueError(f"band[0] must be positive, got {band[0]!r} Hz")
if not min_cycles > 0:
raise ValueError(f"min_cycles must be positive, got {min_cycles!r}")
bp = bandpass(ref, fs, *band)
env = _envelope(bp, fs, smooth_s=smooth_s)
pos = t >= 0
tp, envp = t[pos], env[pos]
fmask = (tp >= floor_window[0]) & (tp <= floor_window[1])
floor = np.median(envp[fmask]) if fmask.any() else envp[-1]
t_max = float(tp[-1])
# mode="same" boxcar of n samples (as in _envelope): the last (n - 1) // 2
# output samples see the zero padding past the trace end.
n_edge = (max(1, int(smooth_s * fs)) - 1) // 2
unpadded = np.arange(tp.size) < tp.size - n_edge
t_floor_max = t_max - n_edge / fs
fmask = (tp >= floor_window[0]) & (tp <= floor_window[1]) & unpadded
if not fmask.any():
raise ValueError(
f"floor_window {tuple(floor_window)} does not overlap the "
f"positive-lag support of the trace (max lag {t_max:g} s; the last "
f"{t_max - t_floor_max:g} s are excluded because the "
f"smooth_s={smooth_s:g} s envelope rolls off there). Pass a "
f"floor_window inside (0, {t_floor_max:g}] s."
)
floor = np.median(envp[fmask])
flat = envp <= floor_factor * floor
persist_n = max(1, int(persist_s * fs))
sustained = (
Expand All @@ -1397,7 +1450,23 @@ def coda_window_from_envelope(
)
tsus = tp[: len(sustained)]
candidates = np.where((tsus >= t_start) & sustained)[0]
t_end = float(tsus[candidates[0]]) if len(candidates) else float(tp[-1])
t_end = float(tsus[candidates[0]]) if len(candidates) else t_max
t_min_end = t_start + min_cycles / band[0]
if t_end < t_min_end:
if t_min_end > t_max:
raise ValueError(
f"a window of min_cycles={min_cycles:g} periods of "
f"{band[0]:g} Hz from t_start={t_start:g} s ends at "
f"{t_min_end:g} s, past the trace's max lag {t_max:g} s."
)
warnings.warn(
f"envelope of band {tuple(band)} Hz reaches the noise floor at "
f"{t_end:g} s, before t_start + min_cycles / band[0] = "
f"{t_min_end:g} s; window end set to {t_min_end:g} s. The coda "
"may have decayed before t_start: check the cc values.",
stacklevel=2,
)
t_end = t_min_end
return t_start, t_end


Expand Down
198 changes: 198 additions & 0 deletions tests/test_coda_window.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Degenerate coda windows from ``coda_window_from_envelope``.

Before this fix the envelope picker could return a window of zero length,
``(3, 3)``, or one sample, ``(3, 3.01)``, for a short-maxlag or strongly
attenuated high-frequency autocorrelation. Stretching on such a window
correlates one or two samples per branch: cc reads 1.000 for almost any
trial epsilon and the peak picker returned dv/v of +3.35 to +3.81 % against
a truth of -0.5 %. These tests lock the three guards that replace that
silent failure, and check the paper figure's windows stay put.
"""

from __future__ import annotations

import warnings

import numpy as np
import pytest
from codameter.synthetic_demo import (
Synth,
_envelope,
_stretch_window,
bandpass,
coda_window_from_envelope,
daily_ccfs,
impose_dvv,
make_freqdep_coda,
measure_stretching,
)

FS = 50.0


def _acf(maxlag: float, tau: float, seed: int) -> tuple[np.ndarray, np.ndarray]:
"""Symmetric autocorrelation: 1-20 Hz coda decaying with time constant tau."""
rng = np.random.default_rng(seed)
t = np.arange(-maxlag * FS, maxlag * FS + 1) / FS
x = bandpass(rng.standard_normal(t.size), FS, 1.0, 20.0) * np.exp(-np.abs(t) / tau)
x = 0.5 * (x + x[::-1])
x += 30.0 * np.exp(-((t / 0.08) ** 2))
x += 0.02 * bandpass(rng.standard_normal(t.size), FS, 1.0, 20.0)
return t, x


def test_floor_window_outside_support_raises():
"""Default floor_window (40, 50) on a 25 s max-lag trace has no samples."""
t, x = _acf(25.0, 0.7, 0)
with pytest.raises(ValueError, match="max lag 25"):
coda_window_from_envelope(t, x, FS, (8.0, 16.0))


def test_floor_window_only_in_envelope_rolloff_raises():
"""The last smooth_s/2 s of the envelope roll off and cannot set the floor."""
t, x = _acf(25.0, 0.7, 0)
with pytest.raises(ValueError, match="rolls off"):
coda_window_from_envelope(t, x, FS, (1.0, 4.0), floor_window=(24.5, 30.0))
# Inside the valid support the same trace is accepted (the min_cycles
# extension warns here; that path is tested below).
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
t0, t1 = coda_window_from_envelope(
t, x, FS, (1.0, 4.0), floor_window=(15.0, 24.0)
)
assert t1 > t0


def test_rolloff_excluded_from_floor():
"""Envelope at the trace end is biased low; the floor must ignore it."""
t, x = _acf(25.0, 0.7, 0)
env = _envelope(bandpass(x, FS, 1.0, 4.0), FS, smooth_s=1.5)
tail = env[t >= 24.5]
body = env[(t >= 20.0) & (t <= 24.0)]
assert np.median(tail) < np.median(body)


@pytest.mark.parametrize("band", [(8.0, 16.0), (11.3, 20.0)])
def test_window_spans_min_cycles(band):
"""60 s max lag, tau 0.7 s: the envelope is on the floor before t_start."""
t, x = _acf(60.0, 0.7, 0)
with pytest.warns(UserWarning, match="min_cycles"):
t0, t1 = coda_window_from_envelope(t, x, FS, band)
assert t0 == 3.0
assert t1 - t0 >= 3.0 / band[0] - 1e-12


def test_min_cycles_past_max_lag_raises():
t, x = _acf(60.0, 0.7, 0)
with pytest.raises(ValueError, match="past the trace's max lag"):
coda_window_from_envelope(
t, x, FS, (8.0, 16.0), floor_window=(40.0, 50.0), min_cycles=500.0
)


@pytest.mark.parametrize(
"smooth_s, n_edge", [(0.03, 0), (0.04, 0), (0.06, 1), (1.5, 37)]
)
def test_rolloff_exclusion_matches_convolution_edge(smooth_s, n_edge):
"""Only the last (n - 1) // 2 envelope samples see the zero padding.

The floor may use the sample just before them: a floor_window holding
only that sample is accepted, and only those samples differ from the
same boxcar run over the trace extended with more data.
"""
t, x = _acf(25.0, 0.7, 0)
n = max(1, int(smooth_s * FS))
assert (n - 1) // 2 == n_edge
tail = np.abs(np.random.default_rng(3).standard_normal(n)) + 1.0
env = _envelope(x, FS, smooth_s=smooth_s)
env_ext = np.convolve(
np.concatenate([np.abs(x), tail]), np.ones(n) / n, mode="same"
)
# Same centring offset because the kernel is unchanged.
env_ext = env_ext[: x.size]
differs = ~np.isclose(env, env_ext)
assert int(differs.sum()) == n_edge
t_last = t[t.size - 1 - n_edge]
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
t0, t1 = coda_window_from_envelope(
t, x, FS, (1.0, 4.0), smooth_s=smooth_s, floor_window=(t_last, 30.0)
)
assert t1 > t0


@pytest.mark.parametrize("fmin", [0.0, -1.0])
def test_nonpositive_band_low_edge_raises(fmin):
"""band[0] = 0 divided by zero; band[0] < 0 put the min_cycles end early."""
t, x = _acf(25.0, 0.7, 0)
with pytest.raises(ValueError, match="band\\[0\\] must be positive"):
coda_window_from_envelope(t, x, FS, (fmin, 4.0), floor_window=(15.0, 24.0))


@pytest.mark.parametrize("min_cycles", [0.0, -3.0])
def test_nonpositive_min_cycles_raises(min_cycles):
"""min_cycles <= 0 silently returned the zero-length window (3, 3)."""
t, x = _acf(60.0, 0.7, 0)
with pytest.raises(ValueError, match="min_cycles must be positive"):
coda_window_from_envelope(t, x, FS, (8.0, 16.0), min_cycles=min_cycles)


@pytest.mark.parametrize("window", [(3.0, 3.0), (3.0, 3.01), (3.0, 3.04)])
def test_stretch_window_rejects_short_window(window):
"""2, 2 and 6 samples (both branches) are below min_samples = 8."""
t = np.arange(-60 * FS, 60 * FS + 1) / FS
with pytest.raises(ValueError, match="min_samples"):
_stretch_window(t, window, 0.06, "both")


def test_stretch_window_accepts_eight_samples():
t = np.arange(-60 * FS, 60 * FS + 1) / FS
sel, _ = _stretch_window(t, (3.0, 3.06), 0.06, "both")
assert int(sel.sum()) == 8
sel, _ = _stretch_window(t, (3.0, 3.0), 0.06, "both", min_samples=2)
assert int(sel.sum()) == 2


def test_degenerate_window_no_longer_reports_cc_one():
"""The reproduction: window (3, 3) gave dv/v +3.35 % at cc 1.000, truth -0.5 %."""
t, ref = _acf(60.0, 0.7, 1)
rng = np.random.default_rng(5)
cur = np.stack(
[
impose_dvv(ref, t, -0.005)
+ 0.002 * bandpass(rng.standard_normal(t.size), FS, 8.0, 16.0)
for _ in range(5)
]
)
for window in [(3.0, 3.0), (3.0, 3.01)]:
with pytest.raises(ValueError, match="min_samples"):
measure_stretching(cur, ref, t, band=(8.0, 16.0), fs=FS, window=window)
# A real window still recovers the truth.
dvv, cc = measure_stretching(
cur, ref, t, band=(8.0, 16.0), fs=FS, window=(0.4, 3.0)
)
assert np.all(np.abs(dvv + 0.005) < 1e-3)


def test_fig_window_envelope_windows():
"""Paper figure (demo_15): windows move at most one or two samples.

Archived windows (literature/figs/demo_15_window_envelope.npz) are
(3, 29.08), (3, 36.92), (3, 14.40) s. Dropping the envelope roll-off from
the floor estimate raises the floor by 1.8-4.6 % and moves the ends to
29.04, 36.90 and 14.38 s. No min_cycles extension and no warning.
"""
fs = Synth().fs
tf, cf = make_freqdep_coda(fs=fs, seed=2)
ref = daily_ccfs(
tf, [cf], [np.zeros(60)], fs=fs, snr=8.0, gen_band=(0.2, 8.0), seed=5
).mean(axis=0)
archived = {(0.3, 0.8): 29.08, (1.0, 2.5): 36.92, (3.0, 6.0): 14.40}
expected = {(0.3, 0.8): 29.04, (1.0, 2.5): 36.90, (3.0, 6.0): 14.38}
with warnings.catch_warnings():
warnings.simplefilter("error")
for band, t_end in expected.items():
t0, t1 = coda_window_from_envelope(tf, ref, fs, band)
assert t0 == 3.0
assert t1 == pytest.approx(t_end, abs=1e-9)
assert abs(t1 - archived[band]) <= 2.0 / fs + 1e-9
Loading