Skip to content

Band-limited resampling for stretching and impose_dvv (linear interpolation biased dv/v above 0.1 fs) - #56

Open
mdenolle wants to merge 6 commits into
docs/sign-convention-manuscriptfrom
fix/bandlimited-stretch-interp
Open

mdenolle wants to merge 6 commits into
docs/sign-convention-manuscriptfrom
fix/bandlimited-stretch-interp

Conversation

@mdenolle

@mdenolle mdenolle commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Pull Request

Summary

Linear interpolation between samples biased both stretching dv/v and the synthetic impose_dvv above about 0.1 fs. This PR adds a 16-tap band-limited resampler and uses it wherever a trace is stretched. Linear mode stays available, bit for bit.

Base is docs/sign-convention-manuscript (#37), not master. The stretching code on master differs. 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

Closed-form oracle: 40 tones evaluated at t(1 + dv/v), fs 50 Hz, 20 realisations. Rerun on 5d2d223.

Band True dv/v Estimator reads (gain) impose_dvv injects (fraction of requested)
8-16 Hz -0.1 % 1.13 0.78
11.3-20 Hz -0.1 % 1.34 0.56
11.3-20 Hz -0.5 % 0.94

The existing oracle test built its "current" trace with np.interp, so it shared the error and could not see it.

Changes (synthetic_demo.py, deviations.py)

  • interp_bandlimited: Kaiser-windowed sinc, 16 taps, beta 5. The complex response error is below 0.005 up to 0.8 Nyquist for every fractional offset; 8 taps cannot reach 0.02 there with any beta.
  • impose_dvv, impose_dvv_branch, add_clock_drift, daily_ccfs and branch_daily_ccfs take interp="bandlimited" (the new default) or "linear", which reproduces the former output bit for bit.
  • stretching_cc, measure_stretching, measure_stretching_trailing, measure_wts and measure_inversion take interp="auto" | "linear" | "bandlimited".
    • auto uses band-limited when band[1] / fs > 0.05, and is bit-identical to the former linear gather below that.
    • auto falls back to linear, with a UserWarning, on an irregular lag axis.
  • deviations.run_pipeline reads an optional cfg["interp"].
  • Float32 lag axes are accepted. They are common from HDF5, ASDF and zarr; the grid check is done in float64 with tolerance max(1e-3 dt, 4 ulp).
  • Complex input is kept.
  • On-grid queries are a direct gather, so a NaN does not leak into exact queries.
  • The kernel stays 8 samples clear of the trace end.
  • The estimators warn when band[1] / fs > 0.4. At 16-24 Hz with fs 50 Hz the band-limited estimator still reads about 1.07.

Effect on existing outputs

  • Both oracle bands now recover with |gain - 1| < 0.002.

  • Golden manifest regenerated with golden.regenerate_manifest(); MANIFEST_VERSION bumped to 4. Public-case RMS moved by -0.001 %, -0.09 % and -0.03 %, against tolerances of 35-60 %.

  • Recommended-pipeline RMS on golden.advisory_case:

    Case Change
    cryosphere -7.9 %
    landslide -5.8 %
    geothermal -1.0 %
    groundwater -0.9 %
    volcano, earthquake_fault < 0.1 %
  • Cost: band-limited stretching_cc takes about 2x the linear gather (365 days, 1-6 s window, 161 trial eps: 0.56 s linear, 1.29 s band-limited). impose_dvv takes 1.3 ms per 5001-sample trace instead of 0.07 ms.

  • Figures and Quarto outputs were not regenerated.

Checklist

  • Tests pass locally (pytest): 392 passed, 1 failed, 1 skipped at 6e8a910, 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 and black 23.11.0 as pinned in .pre-commit-config.yaml). The repository as a whole does not pass on the base.
  • New code has docstrings. No physics citation is needed: this is numerical resampling.
  • Sanity test against an analytical limit: the closed-form oracle above.
  • Config-file field: cfg["interp"] is optional and read with a default; the examples are unchanged.
  • CHANGELOG entry added under ## Unreleased
  • Documentation under docs/ (docstrings only)

Tests

  • 73a09ba adds 8 oracle cases at 8-16 and 11.3-20 Hz, dv/v -0.1 % and -0.5 %, for both the estimator and impose_dvv. All 8 fail on 5d2d223:
    • estimator gains 1.135, 1.279 and 0.936;
    • peak cc 0.988, below the 0.99 threshold;
    • impose_dvv waveform misfit 0.13-0.33, against a < 0.01 threshold.
  • 73a09ba also tests kernel accuracy at 0.8 Nyquist, on-grid exactness, bit-identity of linear mode, the auto switch, and the trailing and WTS paths.
  • 6e8a910 adds 7 tests, all failing on 73a09ba: float32 axes, auto fallback, complex input, NaN footprint, kernel reach, the 0.4 fs warning, and cfg["interp"] reaching the fixed, moving and inversion paths.

Scientific reviewer notes

The bias came to light on 50-Hz single-station autocorrelations, where 8-20 Hz coda is the usable band. A separate review agent read 73a09ba before this PR was opened and asked for changes: float32 axes rejected, complex input cast to float, NaN footprint, and the kernel reaching past the trace end. 6e8a910 addresses all four; it has not been re-reviewed.

Copilot review follow-up

  • Linear _resample and complex traces (synthetic_demo.py:412): invalid, no change. np.interp has accepted complex fp since NumPy 1.12 and codameter pins numpy>=1.24. On 6e8a910 the linear path returns complex128 and matches separate real/imag interpolation to 1e-16.
  • Per-epsilon CSR operator in stretching_cc / measure_stretching_trailing (lines 739, 938): declined after a benchmark, no change. Setup: 5001 lags, 2702-sample window, 161 epsilons. At 1095 days the CSR loop takes 4.65 s, of which 0.19 s goes to building the operators. Gather plus einsum takes 15.4 s. At 365 days it is 1.58 s against 9.18 s.
  • No new commits from this review.

Integration and second Copilot review

Replaces two stale lines above. "Figures and Quarto outputs were not regenerated" no longer holds: 17 figures were regenerated in f3a3d6c. The test counts at 6e8a910 are superseded by the counts at 57ade2c below.

Base merge

75bda47 merges docs/sign-convention-manuscript at aee4a5b (#57, which also contains #58 and #59). Conflicts:

Second Copilot review (6198936761 on f3a3d6c)

  • Snap tolerance (r4807768074): valid, fixed in 57ade2c. On a float32 lag axis at 50 Hz, positions sit up to 9.2e-5 samples off the integers, so impose_dvv with dv/v 0 moved the trace by about 4e-4 and one NaN spread to 17 samples. _grid_fit now returns a snap tolerance of 1e-9 plus the axis' largest departure from its uniform line; uniform float64 axes keep 1e-9, so sidecars and the golden manifest are unchanged. New test test_own_samples_are_exact_on_accepted_axes[float32, jittered] fails on f3a3d6c and passes on 57ade2c.
  • Review 6199475749 on 57ade2c: no inline items.

Checks on 57ade2c

Check Result
pytest tests 468 passed, 1 failed, 1 skipped (failure: test_audit_small_fixes.py::test_aggregate_rejects_missing_shards_and_duplicates, also fails on the base)
golden.regenerate_manifest() byte-identical to tests/data/golden/manifest.json (MANIFEST_VERSION 4)
python -m codameter.figures --check --skip-slow --rtol 1e-5 16/16 match (also in CI)
--check --only demo_10,11,12 --rtol 1e-5 3/3 match
python paper/build.py --no-survey + text checks 88 pages; unresolved 0, commapct 0, lt 0, tilde 0
ruff 0.1.6, black 23.11.0 on changed files clean

Figures regenerated (f3a3d6c)

demo_1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (png, npz, json). demo_5 and realdata_1 reproduce unchanged.

Manuscript numbers that move (for the author; paper/manuscript_marine.qmd is not edited here)

Old and new values computed from the aee4a5b and 57ade2c sidecars, or from reruns of the two paper/data/bayes scripts on the head code (two independent reruns agree; the JSON files are not committed).

# Line Source Quoted Old value New value New quote
1 457 demo_1 (c), TS RMS 0.005 0.0047 0.0043 0.004
2 457 demo_1 (c), WTS RMS 0.010 0.0096 0.0094 0.009
3 458 demo_1 (c), DTW RMS 0.16 0.1628 0.1736 0.17
4 530 demo_2, unweighted A / B ~11x 10.52 10.49 ~10x
5 792 demo_18 snr4 step error, 2 d 0.002 % 0.00182 0.00142 0.001 %
6 792 demo_18 snr4 step error, 60 d 0.014 % 0.01408 0.01346 0.013 %
7 793 demo_18 snr0.5 step error, minimum 0.005 0.00478 0.00434 0.004
8 875 demo_15 high-band envelope RMS ~0.020 % 0.02063 0.01899 ~0.019 %
9 889 demo_15 caption, fixed/envelope ratio ~104x 103.8 112.0 ~112x
10 1224, 1245 demo_12 corr_length_days 5.7 d 5.702 5.759 5.8 d
11 1248 demo_12 n_eff (figure title already 30/229) 29 28.95 29.64 30
12 1222 cd_whitening.json raw lag-1 correlation 0.57 0.5713 0.5797 0.58
13 1163 duplication_check.json half-width x1 0.063 % 0.06251 0.06216 0.062 %
14 1164 duplication_check.json half-width x4 0.040 % 0.03982 0.03936 0.039 %
15 1164 duplication_check.json x4/x1 0.64 0.6370 0.6332 0.63

Same ratio as #9 in the text at l.876 ("~100x"): still ~100x at one significant figure, but it now sits further from the caption's value.

Not regenerated, may move: paper/data/bayes/cd_whitening.json and duplication_check.json (rerun in scratch only, numbers above), and the locked 200-realisation calibration runs behind paper/calibration_table.tex and the abstract/text values 0.956, 0.59, 0.34, 0.81, L = 6.1 d on average and N_eff 45 on average. One clean-scenario check with the head code on 20 new seeds (2000-2019; not paired with the locked seeds) gives member 68 % 0.808 +- 0.002, member 95 % 0.956 +- 0.001, posterior 95 % 0.591 +- 0.012, against 0.808, 0.9561 and 0.590 in the table: consistent within its standard errors. The shared-source (0.34) and clock-drift columns were not rerun, and the table's 4-decimal 0.9561 is not verified at that precision.

Real data

No real-data revalidation here. realdata_1_validation reproduces its committed sidecar because it reads archived Gate 1 products; checking it under band-limited resampling needs a rerun of that pipeline.

🤖 Generated with Claude Code

mdenolle and others added 2 commits December 3, 2026 16:45
Linear interpolation between samples biased dv/v above about 0.1 fs.
On a closed-form oracle (40 tones evaluated at t(1+dv/v), fs 50 Hz,
20 realisations, rerun on 5d2d223) the stretching estimator read 1.13x
the truth at 8-16 Hz and 1.34x at 11.3-20 Hz for dv/v = -0.1 %, and
0.94x at 11.3-20 Hz for -0.5 %. impose_dvv injected 0.78x and 0.56x of
the requested change in the same bands. The existing oracle test built
its current trace with np.interp, so it shared the error.

Changes in synthetic_demo.py:
- interp_bandlimited: Kaiser-windowed sinc, 16 taps, beta 5. Complex
  response error < 0.005 up to 0.8 Nyquist for every fractional offset.
  Eight taps cannot reach 0.02 there with any beta.
- impose_dvv, impose_dvv_branch, add_clock_drift, daily_ccfs and
  branch_daily_ccfs take interp="bandlimited" (default) or "linear"
  (former output, bit for bit).
- stretching_cc, measure_stretching, measure_stretching_trailing and
  measure_wts take interp="auto" | "linear" | "bandlimited". auto uses
  band-limited when band[1] / fs > 0.05 and is bit-identical to the
  former linear gather otherwise. The band-limited trials use one sparse
  operator per trial eps on the window (one stacked operator for WTS).

Effect on existing outputs:
- Both oracle bands now recover with |gain - 1| < 0.002.
- Golden manifest regenerated with golden.regenerate_manifest() and
  MANIFEST_VERSION bumped to 4. Public-case RMS moved by -0.001 %,
  -0.09 % and -0.03 % (tolerances 35-60 %).
- Recommended-pipeline RMS on golden.advisory_case: cryosphere -7.9 %,
  landslide -5.8 %, geothermal -1.0 %, groundwater -0.9 %, volcano and
  earthquake_fault < 0.1 %.
- Estimator cost: band-limited stretching_cc about 2x the linear gather
  (365 days, 1-6 s window, 161 eps: 0.56 s vs 1.29 s). impose_dvv costs
  1.3 ms per 5001-sample trace instead of 0.07 ms.
- Figures and Quarto outputs were not regenerated.

Tests: the analytic oracle now evaluates the closed form at t(1+dv/v).
New closed-form oracle at 8-16 and 11.3-20 Hz, fs 50 Hz, dv/v -0.1 %
and -0.5 %, for the estimator and for impose_dvv. All 8 cases fail on
5d2d223: estimator gains 1.135, 1.279, 0.936 and peak cc 0.988 < 0.99;
impose_dvv waveform misfit 0.13-0.33 against < 0.01. Kernel accuracy at
0.8 Nyquist, on-grid
exactness, bit-identity of the linear mode, the auto switch, and the
trailing and WTS paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of 73a09ba found that the band-limited path rejected float32 lag
axes, which np.interp accepted on the base. A float32 axis such as
(arange(-1250, 1251) / 50).astype(float32) has spacing errors up to
7.2e-5 dt, above the 1e-6 dt uniformity tolerance, so impose_dvv with
default arguments and stretching_cc under interp="auto" at 8-16 Hz,
fs 50 Hz raised ValueError. Lags read from HDF5, ASDF or zarr are often
float32.

Changes in synthetic_demo.py:
- _uniform_grid checks each sample against the line through the end
  points in float64, with tolerance max(1e-3 dt, 4 ulp of max |t|).
  Float32 axes up to +/-3000 s at 50 Hz pass. Band-limited queries are
  formed on a float64 copy of the axis.
- interp="auto" falls back to linear with a UserWarning on an irregular
  axis; an explicit "bandlimited" still raises.
- interp_bandlimited keeps complex input (np.result_type instead of a
  float cast). On-grid queries are a direct gather, and the sparse
  operator drops zero weights, so a NaN no longer reaches an exact query.
  Off-grid queries read 16 samples; the docstring now says so, and notes
  the 0.8 Nyquist limit and the 0.001 error near DC.
- _stretch_window takes a margin; band-limited mode keeps 8 samples
  clear of the trace end, so the kernel never replicates the end sample.
- The band-limited estimators warn when band[1] / fs > 0.4.
- measure_inversion takes interp; deviations.run_pipeline reads an
  optional cfg["interp"] and passes it to the stretching paths and WTS.
- Test docstring quoted 0.29-0.83 for linear injection; the tested bands
  give 0.78x (8-16 Hz) and 0.56x (11.3-20 Hz).

Effect on existing outputs: none. impose_dvv, impose_dvv_branch,
add_clock_drift, stretching_cc, the trailing path and WTS are
bit-identical to 73a09ba on float64 axes with windows clear of the
trace end; golden.regenerate_manifest() reproduces the committed
manifest byte for byte and the six use-case RMS values are unchanged.

Tests added (7, all fail on 73a09ba): float32 axis for impose_dvv and
measure_stretching, auto fallback on an irregular axis, complex input,
NaN footprint, kernel reach inside the trace, warning above 0.4 fs, and
cfg["interp"] reaching the fixed, moving and inversion paths.

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

Approval is blocked by a critical correctness issue where linear resampling via np.interp silently discards the imaginary part of complex inputs, alongside a moderate inefficiency from rebuilding a CSR band-limited operator inside a tight epsilon loop.

2 open issues
What changed in this PR

Introduces a 16-tap Kaiser-windowed, band-limited fractional resampler and routes stretching-based resampling through it to eliminate high-frequency dv/v bias from linear interpolation, while preserving a bit-identical legacy linear mode.

Changes:

  • Add interp_bandlimited resampling and make it the default for trace stretching/dv/v injection, with explicit linear and bandlimited options.
  • Thread interp="auto|linear|bandlimited" through stretching estimators (including trailing/WTS/inversion) and allow optional cfg["interp"] in the pipeline.
  • Add analytic/oracle and regression tests for accuracy and edge cases; bump golden manifest version and update stored expectations; document the change in the changelog.
File Description
tests/​test_stretching_interpolation.py Adds closed-form oracle and regression tests covering band-limited vs linear interpolation, auto switching, and several edge cases (grid exactness, NaN footprint, warnings, complex/float32 handling).
tests/​data/​golden/​manifest.json Updates golden expectations and manifest contents to reflect the new default interpolation behavior.
src/​codameter/​synthetic_demo.py Implements the band-limited resampling kernel and threads interpolation mode selection through dv/v injection and stretching/measurement routines.
src/​codameter/​golden.py Bumps the golden manifest version constant to invalidate stale cached expectations after interpolation changes.
src/​codameter/​deviations.py Plumbs an optional cfg["interp"] setting through run_pipeline so stretching/WTS/inversion paths can select the interpolation mode.
CHANGELOG.md Documents the interpolation bias fix, new interpolation options/defaults, and the associated golden manifest update.

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
Comment thread src/codameter/synthetic_demo.py Resolved
mdenolle and others added 3 commits December 4, 2026 11:55
… 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>
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>
The committed sidecars were produced with linear interpolation in
impose_dvv. With band-limited resampling as the default, the synthetic
correlations change, so the CI sidecar check failed on demo_1
(21 arrays, up to 1.81 relative) and demo_2 (13 arrays, up to 1.98).

Regenerated with `python -m codameter.figures` (fast and slow) on
2a4a7bc in the pixi dev env with OMP/OPENBLAS threads 1: demo_1, 2, 3,
4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 and 18. demo_5 and
realdata_1 reproduce their committed sidecars and are left as they are.
`--check --skip-slow --rtol 1e-5` in the pixi test env: 16 of 16 match.
CHANGELOG C1 entry notes the regeneration.

Manuscript numbers that move at their quoted precision are listed in
the PR; the manuscript text is not changed here.

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

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 inconsistency between _uniform_grid’s permissive axis acceptance tolerance and _bandlimited_taps’ much stricter on-grid snapping can cause nominally on-grid queries to miss exact-gather handling and propagate NaNs, indicating an unresolved correctness issue in src/codameter/synthetic_demo.py around line 299.

1 open issue
2 resolved since last review

Review effort: Balanced

Comment thread src/codameter/synthetic_demo.py Resolved
…ling (#56, Copilot review)

_uniform_grid accepts float32 axes (up to about 1e-4 dt off the uniform
line) and float64 axes up to 1e-3 dt off it, but _bandlimited_taps only
snapped positions within 1e-9 samples onto a sample. On a float32 lag
axis at 50 Hz, a query at the axis' own samples was interpolated:
impose_dvv(x, t32, 0.0) moved the trace by up to 3.7e-4 and one NaN
spread to 17 output samples instead of staying in one.

_grid_fit now returns the snap tolerance, 1e-9 plus the axis' largest
departure from its uniform line in samples, and interp_bandlimited and
_bandlimited_operator pass it to _bandlimited_taps. On a uniform float64
axis the tolerance is 1e-9 as before.

Outputs: figure sidecars (fast 16 of 16, slow 3 of 3, rtol 1e-5) and
the golden manifest reproduce unchanged. New test
test_own_samples_are_exact_on_accepted_axes (float32 and jittered
float64 axes) fails before and passes after; full suite 468 passed,
1 known failure (test_aggregate_rejects_missing_shards_and_duplicates).

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

🔵 Needs a closer look

The change introduces substantial numerical resampling/estimator and default-behavior shifts that could subtly alter scientific dv/v results and performance, and the provided evidence indicates these effects require validation on representative real datasets (including figure/manuscript consistency) beyond what static review can confirm.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@mdenolle

mdenolle commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

Copilot review 6199475749 (on 57ade2c). No open items. Figures and sidecars are regenerated on this head and the CI sidecar check passes. Fifteen numbers quoted in paper/manuscript_marine.qmd move at their quoted precision; they are listed in the PR body for the author to update, together with the Bayes and calibration products that were not rerun. The real-data figure reads archived Gate 1 products, so revalidating it under band-limited resampling needs a rerun of that pipeline and is not part of this PR.

This branch has not been deployed

No deployments
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