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
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -16,6 +24,19 @@ 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, 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.

- Phase 5 transient detection scored each sample against a centred
30-sample window, so a box or step entered its own baseline. With the
Phase 5 defaults, 0 of 200 boxes were detected at any amplitude up to
Expand Down
46 changes: 41 additions & 5 deletions src/codameter/deviations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -107,17 +117,37 @@ 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 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, 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)))
Comment thread
Copilot marked this conversation as resolved.
Resolved
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):
Expand Down Expand Up @@ -189,7 +219,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)
Comment on lines +222 to +225
if name == "stretching (TS)":
dvv, cc = measure_stretching(
stacked,
Expand Down Expand Up @@ -241,7 +274,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
Expand Down
179 changes: 164 additions & 15 deletions src/codameter/synthetic_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Literal, overload

import numpy as np

Expand Down Expand Up @@ -520,7 +521,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
Expand All @@ -530,12 +577,69 @@ 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``).

**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, is non-finite, or has a peak CC
that is not positive (the ratio has no meaning there).
"""
cc = np.atleast_2d(cc)
idx = np.argmax(cc, axis=1)
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, 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]
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]
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) & (peak > 0)
ratio[has] = other[has] / peak[has]
return dvv, peak, {"at_edge": at_edge, "second_peak_ratio": ratio}


def measure_stretching(
Expand Down Expand Up @@ -619,6 +723,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``).

Expand All @@ -635,18 +740,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)
Expand Down Expand Up @@ -1351,18 +1474,44 @@ 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 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:
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).
# 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]
csum = np.cumsum(ccfs, axis=0, dtype=np.float64)
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


Expand Down
Loading
Loading