diff --git a/CHANGELOG.md b/CHANGELOG.md index d4e8994..14548c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,32 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ### Fixed +- Band-limited resampling for stretching. Linear interpolation biased + dv/v above about 0.1 fs. On a closed-form 40-tone oracle at fs 50 Hz and + dv/v -0.1 %, the stretching estimator read 1.13x (8-16 Hz) and 1.34x + (11.3-20 Hz) the truth, and `impose_dvv` injected 0.78x and 0.56x of + the requested change in the same bands. + New `interp_bandlimited` (Kaiser-windowed sinc, 16 taps, error < 0.5 % + up to 0.8 Nyquist). `impose_dvv`, `impose_dvv_branch`, `add_clock_drift`, + `daily_ccfs` and `branch_daily_ccfs` use it by default; `interp="linear"` + restores the former output. `stretching_cc`, `measure_stretching`, + `measure_stretching_trailing` and `measure_wts` take + `interp="auto"|"linear"|"bandlimited"`; `auto` switches to band-limited + when `band[1] / fs > 0.05` and is bit-identical to the former code below. + Both oracle bands now recover with |gain - 1| < 0.002. Golden manifest + regenerated as version 4; public-case RMS moved by at most 0.09 %. + Float32 lag axes are accepted (rounding up to about 1e-4 dt); under + `auto` an irregular axis falls back to linear with a warning. Complex + input keeps its imaginary part, on-grid queries stay exact next to a + NaN (also at the samples of a float32 or slightly irregular axis), the + window keeps the 16-tap kernel inside the trace, and a warning + is raised when `band[1] / fs` exceeds 0.4. `run_pipeline` reads an + optional `cfg["interp"]` and `measure_inversion` takes `interp`. + Every generated figure except `demo_5_window_band` and + `realdata_1_validation` is regenerated with its sidecars, because the + synthetic correlations now come from the band-limited `impose_dvv`. + (C1) + - 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)` diff --git a/literature/figs/demo_10_deviations.json b/literature/figs/demo_10_deviations.json index 7742afd..98967cb 100644 --- a/literature/figs/demo_10_deviations.json +++ b/literature/figs/demo_10_deviations.json @@ -2,8 +2,10 @@ "figure": "demo_10_deviations", "generator": "codameter.deviations.oat_effects + fig_deviation_ranking", "codameter_version": "0.4.0", - "git_commit": "c0f91f1f5d72ab3d7b4ed4be9294e7b023a372aa", - "generated_utc": "2026-09-13T17:03:25+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:46:42+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", @@ -90,15 +92,15 @@ "axis": "baseline", "option": "best practice", "is_best": true, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 }, @@ -106,15 +108,15 @@ "axis": "Estimator", "option": "stretching (TS)", "is_best": true, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 }, @@ -122,15 +124,15 @@ "axis": "Estimator", "option": "MWCS", "is_best": false, - "rms": 0.003910682471699039, - "drop_err": 0.0006314660597331476, - "rms_lo": 0.0035658996000358383, - "rms_hi": 0.004311647890357689, - "drop_lo": 0.0003183721404259087, - "drop_hi": 0.0012257342654826203, - "rms_common": 0.003924359593933799, - "rms_common_lo": 0.0035987239163105876, - "rms_common_hi": 0.0043087852037078204, + "rms": 0.003908528877209911, + "drop_err": 0.0006305143867989038, + "rms_lo": 0.003564826954407117, + "rms_hi": 0.004309014350469757, + "drop_lo": 0.0003155607488015068, + "drop_hi": 0.0012204416482730109, + "rms_common": 0.003922201382443934, + "rms_common_lo": 0.0035976639322490944, + "rms_common_hi": 0.004306183046168926, "availability": 1.0, "n_seeds": 3 }, @@ -138,15 +140,15 @@ "axis": "Estimator", "option": "WCS", "is_best": false, - "rms": 0.01516901904364181, - "drop_err": -0.0005176326958938746, - "rms_lo": 0.013558523196586961, - "rms_hi": 0.016510688359233913, - "drop_lo": -0.003845978487677306, - "drop_hi": 0.004345266590408422, - "rms_common": 0.015146876799817308, - "rms_common_lo": 0.013389763432331945, - "rms_common_hi": 0.016731088175750634, + "rms": 0.015163009666041902, + "drop_err": -0.0005191231845998512, + "rms_lo": 0.013554082832810826, + "rms_hi": 0.016503589262655525, + "drop_lo": -0.0038399327346839442, + "drop_hi": 0.00433708009848985, + "rms_common": 0.015140897336875745, + "rms_common_lo": 0.013385264891194563, + "rms_common_hi": 0.01672392703075104, "availability": 1.0, "n_seeds": 3 }, @@ -154,15 +156,15 @@ "axis": "Estimator", "option": "DTW", "is_best": false, - "rms": 0.0018912620160057441, - "drop_err": -0.00045590931774620375, - "rms_lo": 0.0017857690352370472, - "rms_hi": 0.001986953304728184, - "drop_lo": -0.0005617834835006095, - "drop_hi": -0.00025060364537466285, - "rms_common": 0.001885711375110619, - "rms_common_lo": 0.0018086406608723918, - "rms_common_hi": 0.0019806049646585856, + "rms": 0.001890591462018888, + "drop_err": -0.0004396780440298997, + "rms_lo": 0.0017851330278944204, + "rms_hi": 0.0019861113146623127, + "drop_lo": -0.0005553707345728894, + "drop_hi": -0.000236414241963702, + "rms_common": 0.001885006394476814, + "rms_common_lo": 0.0018080012977571597, + "rms_common_hi": 0.0019796844116441855, "availability": 1.0, "n_seeds": 3 }, @@ -170,15 +172,15 @@ "axis": "Frequency band", "option": "0.4\u20131", "is_best": true, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 }, @@ -186,15 +188,15 @@ "axis": "Frequency band", "option": "0.8\u20132", "is_best": false, - "rms": 0.00022873532732278992, - "drop_err": -2.5742496116336565e-05, - "rms_lo": 0.00022192379795304393, - "rms_hi": 0.00023370566994114375, - "drop_lo": -8.16884787913758e-05, - "drop_hi": 2.392748075854276e-05, - "rms_common": 0.00023266982896944874, - "rms_common_lo": 0.0002259506540851431, - "rms_common_hi": 0.00023804273518531147, + "rms": 0.00022842431919958446, + "drop_err": -2.7045860443987897e-05, + "rms_lo": 0.0002217147175111152, + "rms_hi": 0.0002334006220936935, + "drop_lo": -8.318090437174153e-05, + "drop_hi": 2.2706906288440937e-05, + "rms_common": 0.00023237074786621142, + "rms_common_lo": 0.00022575587268981238, + "rms_common_hi": 0.00023770763213724333, "availability": 1.0, "n_seeds": 3 }, @@ -202,15 +204,15 @@ "axis": "Frequency band", "option": "0.2\u20130.5", "is_best": false, - "rms": 0.0006288404793382894, - "drop_err": -0.000267997734789348, - "rms_lo": 0.0005723467342313203, - "rms_hi": 0.0006578714857538511, - "drop_lo": -0.0004867978410263104, - "drop_hi": -4.929561389202053e-05, - "rms_common": 0.0006278475395724551, - "rms_common_lo": 0.0005700905229826909, - "rms_common_hi": 0.0006623186242991041, + "rms": 0.0006290719045639213, + "drop_err": -0.0002670409597953668, + "rms_lo": 0.0005725016274967915, + "rms_hi": 0.0006579943274368692, + "drop_lo": -0.0004864125606843608, + "drop_hi": -4.932172168373465e-05, + "rms_common": 0.0006280718870286649, + "rms_common_lo": 0.0005702851764399051, + "rms_common_hi": 0.0006624080984104623, "availability": 1.0, "n_seeds": 3 }, @@ -218,15 +220,15 @@ "axis": "Coda window", "option": "10\u201330", "is_best": true, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 }, @@ -234,15 +236,15 @@ "axis": "Coda window", "option": "4\u201314", "is_best": false, - "rms": 0.00027196589468172474, - "drop_err": -6.155504424924637e-05, - "rms_lo": 0.0002673549431669386, - "rms_hi": 0.0002767971977677517, - "drop_lo": -0.00023300490600866586, - "drop_hi": 0.00019088863739512817, - "rms_common": 0.0002743674159537052, - "rms_common_lo": 0.00026914449518474957, - "rms_common_hi": 0.0002801459348187179, + "rms": 0.0002721713367946997, + "drop_err": -6.475003232628191e-05, + "rms_lo": 0.00026761321017837697, + "rms_hi": 0.0002770176214262116, + "drop_lo": -0.0002354308956137286, + "drop_hi": 0.0001875649216594138, + "rms_common": 0.0002746623903150649, + "rms_common_lo": 0.00026952380567816137, + "rms_common_hi": 0.00028039020971473293, "availability": 1.0, "n_seeds": 3 }, @@ -250,15 +252,15 @@ "axis": "Coda window", "option": "25\u201345", "is_best": false, - "rms": 0.0006454646417901085, - "drop_err": -0.00011556237224470704, - "rms_lo": 0.0006250252824107874, - "rms_hi": 0.0006602515153341077, - "drop_lo": -0.0002536703488477971, - "drop_hi": -4.4746834378657334e-05, - "rms_common": 0.0006467855931023099, - "rms_common_lo": 0.000619789916919298, - "rms_common_hi": 0.0006604706251103147, + "rms": 0.0006452411547414367, + "drop_err": -0.00011554763597978373, + "rms_lo": 0.0006249443921907015, + "rms_hi": 0.0006599644952438814, + "drop_lo": -0.00025342072537616004, + "drop_hi": -4.5456251561109325e-05, + "rms_common": 0.0006465541385637978, + "rms_common_lo": 0.000619698637766519, + "rms_common_hi": 0.0006601870814024621, "availability": 0.9993911719939117, "n_seeds": 3 }, @@ -266,15 +268,15 @@ "axis": "Stack length", "option": "10", "is_best": true, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 }, @@ -282,15 +284,15 @@ "axis": "Stack length", "option": "1", "is_best": false, - "rms": 0.0007689197465655149, - "drop_err": -0.00022437571790866773, - "rms_lo": 0.0007527319715592372, - "rms_hi": 0.0007901562880647926, - "drop_lo": -0.0004278477372717782, - "drop_hi": -1.4417056869917271e-05, - "rms_common": 0.0007715931370727444, - "rms_common_lo": 0.0007561953762031397, - "rms_common_hi": 0.000788202583806116, + "rms": 0.0007684156412869368, + "drop_err": -0.00022440769167811968, + "rms_lo": 0.0007522787610527559, + "rms_hi": 0.0007895721126566787, + "drop_lo": -0.00043160240388822593, + "drop_hi": -1.3044641407702808e-05, + "rms_common": 0.0007711454259898605, + "rms_common_lo": 0.0007557872267249023, + "rms_common_hi": 0.0007876860102626783, "availability": 1.0, "n_seeds": 3 }, @@ -298,15 +300,15 @@ "axis": "Stack length", "option": "45", "is_best": false, - "rms": 0.0005101364928674309, - "drop_err": -0.0002658687768184607, - "rms_lo": 0.0004857130707012234, - "rms_hi": 0.0005310199476645786, - "drop_lo": -0.0003883097087691123, - "drop_hi": -9.725816897521253e-05, - "rms_common": 0.0005178039424300951, - "rms_common_lo": 0.0004948274857815161, - "rms_common_hi": 0.0005393243416532102, + "rms": 0.0005100211925478936, + "drop_err": -0.00026866496878765665, + "rms_lo": 0.0004856237885684948, + "rms_hi": 0.000531001142281391, + "drop_lo": -0.0003913794090212256, + "drop_hi": -0.00010067358811072452, + "rms_common": 0.0005176884587230853, + "rms_common_lo": 0.0004947335749769936, + "rms_common_hi": 0.0005392281193385576, "availability": 1.0, "n_seeds": 3 }, @@ -314,15 +316,15 @@ "axis": "Reference scheme", "option": "fixed", "is_best": true, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 }, @@ -330,15 +332,15 @@ "axis": "Reference scheme", "option": "moving", "is_best": false, - "rms": 0.0016432492300336044, - "drop_err": 0.002862478844061284, - "rms_lo": 0.0016371781867057364, - "rms_hi": 0.0016512918951721374, - "drop_lo": 0.002771166135137934, - "drop_hi": 0.0029473932960450617, - "rms_common": 0.0016432492300336044, - "rms_common_lo": 0.0016371781867057364, - "rms_common_hi": 0.0016512918951721374, + "rms": 0.0016431896298567492, + "drop_err": 0.0028627529600753453, + "rms_lo": 0.0016371314810842642, + "rms_hi": 0.0016512393929283898, + "drop_lo": 0.002771363077466793, + "drop_hi": 0.0029461767889109357, + "rms_common": 0.0016431896298567492, + "rms_common_lo": 0.0016371314810842642, + "rms_common_hi": 0.0016512393929283898, "availability": 0.958904109589041, "n_seeds": 3 }, @@ -346,15 +348,15 @@ "axis": "Reference scheme", "option": "inversion", "is_best": true, - "rms": 0.0005487182340473559, - "drop_err": 4.6002754800999404e-05, - "rms_lo": 0.00043425417315532197, - "rms_hi": 0.0006357042558434154, - "drop_lo": -7.755495766570896e-05, - "drop_hi": 0.0002920725581694939, - "rms_common": 0.0005571279450994593, - "rms_common_lo": 0.00043901001334001566, - "rms_common_hi": 0.0006465397282213954, + "rms": 0.0005518491172355084, + "drop_err": 4.443069897491523e-05, + "rms_lo": 0.0004370976055065416, + "rms_hi": 0.0006389463777410816, + "drop_lo": -7.92071254293778e-05, + "drop_hi": 0.00029041164541276443, + "rms_common": 0.000560345330958844, + "rms_common_lo": 0.0004419428407151817, + "rms_common_hi": 0.000649866375590441, "availability": 1.0, "n_seeds": 3 }, @@ -362,15 +364,15 @@ "axis": "CC gating", "option": "True", "is_best": true, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 }, @@ -378,15 +380,15 @@ "axis": "CC gating", "option": "False", "is_best": false, - "rms": 0.00032707093938488487, - "drop_err": -9.439411401275695e-05, - "rms_lo": 0.0003168436926370666, - "rms_hi": 0.0003474450336877325, - "drop_lo": -0.0002511457048576791, - "drop_hi": 0.00015517430895534666, - "rms_common": 0.00032916891570529346, - "rms_common_lo": 0.000314402851250775, - "rms_common_hi": 0.0003514136929118085, + "rms": 0.00032682013727376914, + "drop_err": -9.511771516699322e-05, + "rms_lo": 0.0003164325702918374, + "rms_hi": 0.00034732799574862513, + "drop_lo": -0.00025217715426362024, + "drop_hi": 0.000153705284858779, + "rms_common": 0.000328930613741473, + "rms_common_lo": 0.000314082539120673, + "rms_common_hi": 0.0003512429126862506, "availability": 1.0, "n_seeds": 3 } diff --git a/literature/figs/demo_10_deviations.npz b/literature/figs/demo_10_deviations.npz index 67f3fff..bbe8388 100644 Binary files a/literature/figs/demo_10_deviations.npz and b/literature/figs/demo_10_deviations.npz differ diff --git a/literature/figs/demo_10_deviations.png b/literature/figs/demo_10_deviations.png index 7c89f1c..0d4d8aa 100644 Binary files a/literature/figs/demo_10_deviations.png and b/literature/figs/demo_10_deviations.png differ diff --git a/literature/figs/demo_11_multiverse.json b/literature/figs/demo_11_multiverse.json index eccc276..215d55e 100644 --- a/literature/figs/demo_11_multiverse.json +++ b/literature/figs/demo_11_multiverse.json @@ -2,8 +2,10 @@ "figure": "demo_11_multiverse", "generator": "codameter.deviations.multiverse + fig_multiverse_full", "codameter_version": "0.4.0", - "git_commit": "606f52826e348f55cf41c5c8cc97d83f7477e814", - "generated_utc": "2026-09-14T20:22:04+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:57:32+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", @@ -1011,22 +1013,23 @@ -0.0015953601640949972 ], "sobol_rms": { - "estimator": 0.18463613802418932, - "band": 0.023801370403100576, - "window": 0.2695482936114043, - "stack": 0.16715781784273717, - "reference": 0.0013864692528178886 + "estimator": 0.18445166519099854, + "band": 0.02381154821547316, + "window": 0.2693840022330576, + "stack": 0.16709327207817404, + "reference": 0.0013859532978639296 }, "sobol_drop": { - "estimator": 0.06235364288721693, - "band": 0.02898266944784389, - "window": 0.055215473347404134, - "stack": 0.00045630955433450854, - "reference": 0.12776374206635088 + "estimator": 0.06122332722101527, + "band": 0.03069160091704638, + "window": 0.05613026098851044, + "stack": 0.0005895962788846058, + "reference": 0.1327145109868779 }, "n_pipelines": 108, "n_valid": 96, "n_empty": 12, + "n_sparse": 0, "empty": [ { "config": { diff --git a/literature/figs/demo_11_multiverse.npz b/literature/figs/demo_11_multiverse.npz index 2ca1912..e155ef9 100644 Binary files a/literature/figs/demo_11_multiverse.npz and b/literature/figs/demo_11_multiverse.npz differ diff --git a/literature/figs/demo_11_multiverse.png b/literature/figs/demo_11_multiverse.png index 33b00b6..01beabd 100644 Binary files a/literature/figs/demo_11_multiverse.png and b/literature/figs/demo_11_multiverse.png differ diff --git a/literature/figs/demo_12_bayes.json b/literature/figs/demo_12_bayes.json index ad152d1..ecf384a 100644 --- a/literature/figs/demo_12_bayes.json +++ b/literature/figs/demo_12_bayes.json @@ -2,8 +2,10 @@ "figure": "demo_12_bayes", "generator": "codameter.uq_bayes._build_bayes + _fig_bayes", "codameter_version": "0.4.0", - "git_commit": "c0f91f1f5d72ab3d7b4ed4be9294e7b023a372aa", - "generated_utc": "2026-09-13T17:05:28+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:59:19+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", @@ -61,7 +63,7 @@ }, { "axes": "ax3", - "title": "(c) time-dependent error; $N_{eff}$=29/229", + "title": "(c) time-dependent error; $N_{eff}$=30/229", "xlabel": "time (years)", "ylabel": "$\\sigma$ (dv/v, %)", "lines": [ @@ -141,10 +143,10 @@ "data/within_std" ], "bayes": { - "tau": 0.0003612992348785833, - "s": 12.098861625892763, - "corr_length_days": 5.702100823925634, - "n_eff": 28.950925940431706, + "tau": 0.0003498117728801866, + "s": 11.948446386342154, + "corr_length_days": 5.759274035639329, + "n_eff": 29.63796958127553, "n_epochs": 229, "labels": [ "stretching (TS) 0.4-1Hz 8-28s stack10d fixed", diff --git a/literature/figs/demo_12_bayes.npz b/literature/figs/demo_12_bayes.npz index 2a6057b..f05f047 100644 Binary files a/literature/figs/demo_12_bayes.npz and b/literature/figs/demo_12_bayes.npz differ diff --git a/literature/figs/demo_12_bayes.png b/literature/figs/demo_12_bayes.png index 79b83c3..fb54d4c 100644 Binary files a/literature/figs/demo_12_bayes.png and b/literature/figs/demo_12_bayes.png differ diff --git a/literature/figs/demo_13_branch_asymmetry.json b/literature/figs/demo_13_branch_asymmetry.json index 6978252..af83614 100644 --- a/literature/figs/demo_13_branch_asymmetry.json +++ b/literature/figs/demo_13_branch_asymmetry.json @@ -2,8 +2,10 @@ "figure": "demo_13_branch_asymmetry", "generator": "codameter.synthetic_demo.fig_branch_asymmetry", "codameter_version": "0.4.0", - "git_commit": "d3a5c18b08d95872cfa54fa796f080daec94d20a", - "generated_utc": "2026-09-13T13:34:57+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:36:58+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_13_branch_asymmetry.npz b/literature/figs/demo_13_branch_asymmetry.npz index f0f2520..52db61d 100644 Binary files a/literature/figs/demo_13_branch_asymmetry.npz and b/literature/figs/demo_13_branch_asymmetry.npz differ diff --git a/literature/figs/demo_13_branch_asymmetry.png b/literature/figs/demo_13_branch_asymmetry.png index 2caffa6..e531421 100644 Binary files a/literature/figs/demo_13_branch_asymmetry.png and b/literature/figs/demo_13_branch_asymmetry.png differ diff --git a/literature/figs/demo_14_network_pairs.json b/literature/figs/demo_14_network_pairs.json index fad6fe9..92bd241 100644 --- a/literature/figs/demo_14_network_pairs.json +++ b/literature/figs/demo_14_network_pairs.json @@ -2,8 +2,10 @@ "figure": "demo_14_network_pairs", "generator": "codameter.synthetic_demo.fig_network_pairs", "codameter_version": "0.4.0", - "git_commit": "141e7bc25bb439420c5ee73223bf78eb4ca7a839", - "generated_utc": "2026-09-10T18:30:57+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:33:19+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_14_network_pairs.npz b/literature/figs/demo_14_network_pairs.npz index 4671991..3bf9a22 100644 Binary files a/literature/figs/demo_14_network_pairs.npz and b/literature/figs/demo_14_network_pairs.npz differ diff --git a/literature/figs/demo_14_network_pairs.png b/literature/figs/demo_14_network_pairs.png index 7bb5eb0..c220b1f 100644 Binary files a/literature/figs/demo_14_network_pairs.png and b/literature/figs/demo_14_network_pairs.png differ diff --git a/literature/figs/demo_15_window_envelope.json b/literature/figs/demo_15_window_envelope.json index 3f43152..a2958d5 100644 --- a/literature/figs/demo_15_window_envelope.json +++ b/literature/figs/demo_15_window_envelope.json @@ -2,10 +2,10 @@ "figure": "demo_15_window_envelope", "generator": "codameter.synthetic_demo.fig_window_envelope", "codameter_version": "0.4.0", - "git_commit": "182351a634579e47981f55880e1739f0165c5426", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", "git_dirty": false, - "generator_digest": "c10090402e3e", - "generated_utc": "2026-12-04T16:11:21+00:00", + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:33:33+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_15_window_envelope.npz b/literature/figs/demo_15_window_envelope.npz index c3c4cd8..5890774 100644 Binary files a/literature/figs/demo_15_window_envelope.npz and b/literature/figs/demo_15_window_envelope.npz differ diff --git a/literature/figs/demo_15_window_envelope.png b/literature/figs/demo_15_window_envelope.png index d69e173..390de7b 100644 Binary files a/literature/figs/demo_15_window_envelope.png and b/literature/figs/demo_15_window_envelope.png differ diff --git a/literature/figs/demo_16_band_sensitivity.json b/literature/figs/demo_16_band_sensitivity.json index 9395d30..0d42f09 100644 --- a/literature/figs/demo_16_band_sensitivity.json +++ b/literature/figs/demo_16_band_sensitivity.json @@ -2,8 +2,10 @@ "figure": "demo_16_band_sensitivity", "generator": "codameter.synthetic_demo.fig_band_sensitivity", "codameter_version": "0.4.0", - "git_commit": "141e7bc25bb439420c5ee73223bf78eb4ca7a839", - "generated_utc": "2026-09-10T18:35:20+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:37:48+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_16_band_sensitivity.npz b/literature/figs/demo_16_band_sensitivity.npz index 29e37dc..75de7cd 100644 Binary files a/literature/figs/demo_16_band_sensitivity.npz and b/literature/figs/demo_16_band_sensitivity.npz differ diff --git a/literature/figs/demo_16_band_sensitivity.png b/literature/figs/demo_16_band_sensitivity.png index cc85e8d..9418ad0 100644 Binary files a/literature/figs/demo_16_band_sensitivity.png and b/literature/figs/demo_16_band_sensitivity.png differ diff --git a/literature/figs/demo_17_reference_schemes.json b/literature/figs/demo_17_reference_schemes.json index ab759ed..844006e 100644 --- a/literature/figs/demo_17_reference_schemes.json +++ b/literature/figs/demo_17_reference_schemes.json @@ -2,8 +2,10 @@ "figure": "demo_17_reference_schemes", "generator": "codameter.synthetic_demo.fig_reference_schemes", "codameter_version": "0.4.0", - "git_commit": "141e7bc25bb439420c5ee73223bf78eb4ca7a839", - "generated_utc": "2026-09-10T18:39:35+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:41:11+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_17_reference_schemes.npz b/literature/figs/demo_17_reference_schemes.npz index 3f26c20..c803302 100644 Binary files a/literature/figs/demo_17_reference_schemes.npz and b/literature/figs/demo_17_reference_schemes.npz differ diff --git a/literature/figs/demo_17_reference_schemes.png b/literature/figs/demo_17_reference_schemes.png index 5a2aa3f..f229063 100644 Binary files a/literature/figs/demo_17_reference_schemes.png and b/literature/figs/demo_17_reference_schemes.png differ diff --git a/literature/figs/demo_18_stack_coherence.json b/literature/figs/demo_18_stack_coherence.json index b18189e..cb4d255 100644 --- a/literature/figs/demo_18_stack_coherence.json +++ b/literature/figs/demo_18_stack_coherence.json @@ -2,8 +2,10 @@ "figure": "demo_18_stack_coherence", "generator": "codameter.synthetic_demo.fig_stack_coherence", "codameter_version": "0.4.0", - "git_commit": "c0f91f1f5d72ab3d7b4ed4be9294e7b023a372aa", - "generated_utc": "2026-09-13T16:54:15+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:42:42+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_18_stack_coherence.npz b/literature/figs/demo_18_stack_coherence.npz index 0464158..9c500e3 100644 Binary files a/literature/figs/demo_18_stack_coherence.npz and b/literature/figs/demo_18_stack_coherence.npz differ diff --git a/literature/figs/demo_18_stack_coherence.png b/literature/figs/demo_18_stack_coherence.png index 447a655..f26c8a2 100644 Binary files a/literature/figs/demo_18_stack_coherence.png and b/literature/figs/demo_18_stack_coherence.png differ diff --git a/literature/figs/demo_1_methods.json b/literature/figs/demo_1_methods.json index d4b0c40..edc0678 100644 --- a/literature/figs/demo_1_methods.json +++ b/literature/figs/demo_1_methods.json @@ -2,8 +2,10 @@ "figure": "demo_1_methods", "generator": "codameter.synthetic_demo.fig_methods", "codameter_version": "0.4.0", - "git_commit": "d3a5c18b08d95872cfa54fa796f080daec94d20a", - "generated_utc": "2026-09-13T13:30:45+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:22:11+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_1_methods.npz b/literature/figs/demo_1_methods.npz index a564865..cfd150c 100644 Binary files a/literature/figs/demo_1_methods.npz and b/literature/figs/demo_1_methods.npz differ diff --git a/literature/figs/demo_1_methods.png b/literature/figs/demo_1_methods.png index a797fa5..df2c1ff 100644 Binary files a/literature/figs/demo_1_methods.png and b/literature/figs/demo_1_methods.png differ diff --git a/literature/figs/demo_2_aggregation.json b/literature/figs/demo_2_aggregation.json index 5b8c72c..f6234bd 100644 --- a/literature/figs/demo_2_aggregation.json +++ b/literature/figs/demo_2_aggregation.json @@ -2,8 +2,10 @@ "figure": "demo_2_aggregation", "generator": "codameter.synthetic_demo.fig_aggregation", "codameter_version": "0.4.0", - "git_commit": "7bfdcef47453919afb5ee5e32a0d7979330402e0", - "generated_utc": "2026-09-10T19:01:48+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:22:53+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_2_aggregation.npz b/literature/figs/demo_2_aggregation.npz index 8dc56dd..9cd53d6 100644 Binary files a/literature/figs/demo_2_aggregation.npz and b/literature/figs/demo_2_aggregation.npz differ diff --git a/literature/figs/demo_2_aggregation.png b/literature/figs/demo_2_aggregation.png index 7ea2e95..a0de052 100644 Binary files a/literature/figs/demo_2_aggregation.png and b/literature/figs/demo_2_aggregation.png differ diff --git a/literature/figs/demo_3_uncertainty.json b/literature/figs/demo_3_uncertainty.json index 6e3c730..2078dfe 100644 --- a/literature/figs/demo_3_uncertainty.json +++ b/literature/figs/demo_3_uncertainty.json @@ -2,8 +2,10 @@ "figure": "demo_3_uncertainty", "generator": "codameter.synthetic_demo.fig_uncertainty", "codameter_version": "0.4.0", - "git_commit": "1374e81e863346a84aeb8ce28a0f58d876454009", - "generated_utc": "2026-09-10T18:27:17+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:28:45+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_3_uncertainty.npz b/literature/figs/demo_3_uncertainty.npz index f23581e..d2887a5 100644 Binary files a/literature/figs/demo_3_uncertainty.npz and b/literature/figs/demo_3_uncertainty.npz differ diff --git a/literature/figs/demo_3_uncertainty.png b/literature/figs/demo_3_uncertainty.png index 817a992..5de9dd0 100644 Binary files a/literature/figs/demo_3_uncertainty.png and b/literature/figs/demo_3_uncertainty.png differ diff --git a/literature/figs/demo_4_frequency_depth.json b/literature/figs/demo_4_frequency_depth.json index 4957f1e..e5440e4 100644 --- a/literature/figs/demo_4_frequency_depth.json +++ b/literature/figs/demo_4_frequency_depth.json @@ -2,8 +2,10 @@ "figure": "demo_4_frequency_depth", "generator": "codameter.synthetic_demo.fig_frequency_depth", "codameter_version": "0.4.0", - "git_commit": "d3a5c18b08d95872cfa54fa796f080daec94d20a", - "generated_utc": "2026-09-13T13:25:32+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:33:29+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_4_frequency_depth.npz b/literature/figs/demo_4_frequency_depth.npz index 5bcdb15..a175a2f 100644 Binary files a/literature/figs/demo_4_frequency_depth.npz and b/literature/figs/demo_4_frequency_depth.npz differ diff --git a/literature/figs/demo_4_frequency_depth.png b/literature/figs/demo_4_frequency_depth.png index 0143438..5f49b58 100644 Binary files a/literature/figs/demo_4_frequency_depth.png and b/literature/figs/demo_4_frequency_depth.png differ diff --git a/literature/figs/demo_6_stacking.json b/literature/figs/demo_6_stacking.json index 0b40eff..7bcded3 100644 --- a/literature/figs/demo_6_stacking.json +++ b/literature/figs/demo_6_stacking.json @@ -2,8 +2,10 @@ "figure": "demo_6_stacking", "generator": "codameter.synthetic_demo.fig_stacking", "codameter_version": "0.4.0", - "git_commit": "d3a5c18b08d95872cfa54fa796f080daec94d20a", - "generated_utc": "2026-09-13T13:27:18+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:33:51+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_6_stacking.npz b/literature/figs/demo_6_stacking.npz index 5ab3a38..df4c6e7 100644 Binary files a/literature/figs/demo_6_stacking.npz and b/literature/figs/demo_6_stacking.npz differ diff --git a/literature/figs/demo_6_stacking.png b/literature/figs/demo_6_stacking.png index fb83919..4198d96 100644 Binary files a/literature/figs/demo_6_stacking.png and b/literature/figs/demo_6_stacking.png differ diff --git a/literature/figs/demo_7_reference.json b/literature/figs/demo_7_reference.json index ea476c1..c970230 100644 --- a/literature/figs/demo_7_reference.json +++ b/literature/figs/demo_7_reference.json @@ -2,8 +2,10 @@ "figure": "demo_7_reference", "generator": "codameter.synthetic_demo.fig_reference", "codameter_version": "0.4.0", - "git_commit": "d3a5c18b08d95872cfa54fa796f080daec94d20a", - "generated_utc": "2026-09-13T13:26:35+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:34:49+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_7_reference.npz b/literature/figs/demo_7_reference.npz index fcb9633..12903c4 100644 Binary files a/literature/figs/demo_7_reference.npz and b/literature/figs/demo_7_reference.npz differ diff --git a/literature/figs/demo_7_reference.png b/literature/figs/demo_7_reference.png index bdeafb2..d2db121 100644 Binary files a/literature/figs/demo_7_reference.png and b/literature/figs/demo_7_reference.png differ diff --git a/literature/figs/demo_8_artifacts.json b/literature/figs/demo_8_artifacts.json index d94fe71..9e33a7f 100644 --- a/literature/figs/demo_8_artifacts.json +++ b/literature/figs/demo_8_artifacts.json @@ -2,8 +2,10 @@ "figure": "demo_8_artifacts", "generator": "codameter.synthetic_demo.fig_artifacts", "codameter_version": "0.4.0", - "git_commit": "141e7bc25bb439420c5ee73223bf78eb4ca7a839", - "generated_utc": "2026-09-10T18:32:30+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:35:04+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_8_artifacts.npz b/literature/figs/demo_8_artifacts.npz index 882544a..f8ab9be 100644 Binary files a/literature/figs/demo_8_artifacts.npz and b/literature/figs/demo_8_artifacts.npz differ diff --git a/literature/figs/demo_8_artifacts.png b/literature/figs/demo_8_artifacts.png index 51d8664..e9817d4 100644 Binary files a/literature/figs/demo_8_artifacts.png and b/literature/figs/demo_8_artifacts.png differ diff --git a/literature/figs/demo_9_multiverse.json b/literature/figs/demo_9_multiverse.json index 492cbfb..94facda 100644 --- a/literature/figs/demo_9_multiverse.json +++ b/literature/figs/demo_9_multiverse.json @@ -2,8 +2,10 @@ "figure": "demo_9_multiverse", "generator": "codameter.synthetic_demo.fig_multiverse", "codameter_version": "0.4.0", - "git_commit": "141e7bc25bb439420c5ee73223bf78eb4ca7a839", - "generated_utc": "2026-09-10T18:34:02+00:00", + "git_commit": "2a4a7bc175bfd5f81db94b547a6aa5b33b612187", + "git_dirty": false, + "generator_digest": "71a6804b03f4", + "generated_utc": "2026-12-04T23:36:29+00:00", "python": "3.12.13", "numpy": "2.4.3", "matplotlib": "3.10.9", diff --git a/literature/figs/demo_9_multiverse.npz b/literature/figs/demo_9_multiverse.npz index 0e3d952..e1b2751 100644 Binary files a/literature/figs/demo_9_multiverse.npz and b/literature/figs/demo_9_multiverse.npz differ diff --git a/literature/figs/demo_9_multiverse.png b/literature/figs/demo_9_multiverse.png index 0a3e3f7..dcbd4c4 100644 Binary files a/literature/figs/demo_9_multiverse.png and b/literature/figs/demo_9_multiverse.png differ diff --git a/src/codameter/deviations.py b/src/codameter/deviations.py index 96191fe..bcc47c7 100644 --- a/src/codameter/deviations.py +++ b/src/codameter/deviations.py @@ -205,6 +205,12 @@ def run_pipeline(ccfs, t, fs, cfg, *, eps_max=0.05, return_cc=False, prefiltered an identical band and only for the estimators whose band usage is that one linear filter (stretching, WCC, DTW, MWCS; the wavelet estimators apply no such filter, so ``prefiltered`` raises for them). + + The optional key ``cfg["interp"]`` ('auto', the default when absent, + 'linear' or 'bandlimited') sets the resampling kernel of the + stretching-based estimators (stretching, WTS, the joint inversion); see + :func:`codameter.synthetic_demo.stretching_cc`. ``'linear'`` reproduces + results computed before band-limited resampling existed. """ name = cfg["estimator"] band, window, k, ref = cfg["band"], cfg["window"], cfg["stack"], cfg["reference"] @@ -213,7 +219,12 @@ def run_pipeline(ccfs, t, fs, cfg, *, eps_max=0.05, return_cc=False, prefiltered f"prefiltered=True is only valid for {sorted(_PREFILTER_OK)}, not {name!r}" ) stacked = _trailing_stack(ccfs, k) - extra = {"eps_max": eps_max} if name in ("stretching (TS)", "WTS") else {} + interp = cfg.get("interp", "auto") + extra = ( + {"eps_max": eps_max, "interp": interp} + if name in ("stretching (TS)", "WTS") + else {} + ) if prefiltered: extra["prefiltered"] = True @@ -233,6 +244,7 @@ def run_pipeline(ccfs, t, fs, cfg, *, eps_max=0.05, return_cc=False, prefiltered window=window, eps_max=eps_max, prefiltered=prefiltered, + interp=interp, ) else: dvv = measure( @@ -270,6 +282,7 @@ def run_pipeline(ccfs, t, fs, cfg, *, eps_max=0.05, return_cc=False, prefiltered window=window, block_days=int(k), prefiltered=prefiltered, + interp=interp, ) else: raise ValueError(ref) diff --git a/src/codameter/golden.py b/src/codameter/golden.py index 0662d0b..d963504 100644 --- a/src/codameter/golden.py +++ b/src/codameter/golden.py @@ -77,8 +77,9 @@ def _default_data_dir() -> Path: # frozen "expected" metrics (e.g. the current-vs-reference interpolation # fix below) -- forces per-user caches to regenerate rather than silently # comparing against stale expectations. Not bumped for the v0.4.0 sign-flip -# itself; see CHANGELOG.md. -MANIFEST_VERSION = 3 +# itself; see CHANGELOG.md. Version 4: band-limited impose_dvv and +# interp="auto" in the stretching estimators. +MANIFEST_VERSION = 4 # Whether DATA_DIR is the regenerable per-user cache (pip-installed, no source # tree, no explicit override) as opposed to an authoritative committed source or diff --git a/src/codameter/synthetic_demo.py b/src/codameter/synthetic_demo.py index e84988d..bbec33f 100644 --- a/src/codameter/synthetic_demo.py +++ b/src/codameter/synthetic_demo.py @@ -38,6 +38,7 @@ from __future__ import annotations +import functools import warnings from dataclasses import dataclass, field from pathlib import Path @@ -203,17 +204,254 @@ def make_coda( return t, coda -def impose_dvv(ref: np.ndarray, t: np.ndarray, dvv: float) -> np.ndarray: +# --------------------------------------------------------------------------- +# Band-limited fractional resampling +# --------------------------------------------------------------------------- +# Linear interpolation between samples is a low-pass filter whose amplitude +# and delay depend on the fractional position of the query point. At 50 Hz +# sampling it biases stretching dv/v by 13-34 % at 8-20 Hz for |dv/v| = 0.1 % +# and makes impose_dvv inject 0.56-0.78x the requested change there. The +# kernel below is a Kaiser-windowed sinc with 2*_BL_HALF taps. With half-width +# 8 and beta 5 the complex response error |H - 1| stays below 0.005 up to +# 0.8 Nyquist for every fractional offset (0.0016 at 0.6 Nyquist). Eight +# taps cannot reach 0.02 at 0.8 Nyquist with any Kaiser beta. +_BL_HALF = 8 +_BL_BETA = 5.0 +# interp="auto" switches the stretching estimators to the band-limited +# kernel when band[1] / fs exceeds this ratio. Below it the linear gather is +# kept bit-identical; at 0.1 the linear bias is still 2-5 %. +_AUTO_BANDLIMITED_FRAC = 0.05 +# Above this band[1] / fs (0.8 Nyquist) the kernel error grows fast: 0.0044 +# at f/fs 0.40, 0.26 at 0.45. The estimators warn when the band reaches it. +_BL_MAX_FRAC = 0.4 +# An axis counts as uniform when every sample lies within this fraction of +# dt of the straight line through its end points (or within the rounding of +# its own float type, whichever is larger). A position error of 1e-3 dt +# shifts the phase by at most 2*pi*0.4*1e-3 = 0.0025 rad at 0.8 Nyquist. +_UNIFORM_RTOL = 1e-3 + + +def _uniform_grid(t: np.ndarray) -> tuple[float, float]: + """Return ``(t0, dt)`` of a uniformly sampled axis, or raise ValueError. + + ``t0`` and ``dt`` are computed in float64. Float32 axes (common for lags + read from HDF5, ASDF or zarr) carry rounding of up to about 1e-4 dt per + sample; they are accepted and treated as the exact uniform grid. + """ + t0, dt, _ = _grid_fit(t) + return t0, dt + + +def _grid_fit(t: np.ndarray) -> tuple[float, float, float]: + """:func:`_uniform_grid` plus ``snap``, the on-grid tolerance in samples. + + ``snap`` is 1e-9 plus the largest departure of ``t`` from its uniform + line, in samples, so a query at one of the axis' own samples is taken + as on-grid even when the axis is float32 or slightly irregular. + """ + t_in = np.asarray(t) + t = t_in.astype(np.float64) + if t.ndim != 1 or t.size < 2: + raise ValueError("band-limited resampling needs a 1-D axis of >= 2 samples") + dt = (t[-1] - t[0]) / (t.size - 1) + if not np.isfinite(dt) or dt <= 0: + raise ValueError( + "band-limited resampling needs a uniformly sampled, increasing " + "axis; pass interp='linear' for an irregular axis" + ) + resid = np.max(np.abs(t - (t[0] + dt * np.arange(t.size)))) + prec = ( + 4.0 * np.finfo(t_in.dtype).eps * float(np.max(np.abs(t))) + if np.issubdtype(t_in.dtype, np.floating) + else 0.0 + ) + if not resid <= max(_UNIFORM_RTOL * dt, prec): + raise ValueError( + "band-limited resampling needs a uniformly sampled, increasing " + f"axis (largest departure {resid / dt:.2g} dt); pass " + "interp='linear' for an irregular axis" + ) + return float(t[0]), float(dt), 1e-9 + float(resid / dt) + + +def _is_uniform(t: np.ndarray) -> bool: + """True when :func:`_uniform_grid` accepts ``t``.""" + try: + _uniform_grid(t) + except ValueError: + return False + return True + + +@functools.lru_cache(maxsize=1) +def _kaiser_table() -> tuple[np.ndarray, np.ndarray]: + """Kaiser window on ``[-_BL_HALF, _BL_HALF]``, tabulated at 2**15 points. + + ``scipy.special.i0`` costs about 15 ms per 80 000 values; a linear lookup + in this table is much faster and differs from it by < 1e-8. + """ + from scipy.special import i0 + + grid = np.linspace(-_BL_HALF, _BL_HALF, 2**15 + 1) + arg = np.sqrt(np.clip(1.0 - (grid / _BL_HALF) ** 2, 0.0, None)) + return grid, i0(_BL_BETA * arg) / i0(_BL_BETA) + + +def _bandlimited_taps( + pos: np.ndarray, n: int, snap: float = 1e-9 +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Tap indices, weights and on-grid mask for fractional positions ``pos``. + + Positions are clamped to ``[0, n - 1]`` and tap indices to the array, so + the signal is extended by its end values, the same convention as + ``np.interp``. At integer positions (``exact`` True) the weights are + exactly one tap of 1.0, so a zero shift returns the input unchanged. + Positions within ``snap`` samples of an integer count as integer. + """ + pos = np.clip(np.asarray(pos, float), 0.0, n - 1.0) + # Snap positions within the axis' rounding of a sample onto it. + near = np.round(pos) + pos = np.where(np.abs(pos - near) <= snap, near, pos) + j0 = np.floor(pos) + mu = pos - j0 + k = np.arange(-_BL_HALF + 1, _BL_HALF + 1) + x = k[None, :] - mu[:, None] + grid, table = _kaiser_table() + u = (x - grid[0]) * ((grid.size - 1) / (grid[-1] - grid[0])) + iu = np.clip(u.astype(np.int64), 0, grid.size - 2) + fu = u - iu + # sinc(k - mu) = -(-1)**k * sin(pi*mu) / (pi*(k - mu)): one sine per row. + with np.errstate(divide="ignore", invalid="ignore"): + sinc = (-np.sin(np.pi * mu))[:, None] * ((-1.0) ** k)[None, :] / (np.pi * x) + w = sinc * (table[iu] * (1.0 - fu) + table[iu + 1] * fu) + # On-grid queries (mu == 0) take the sample itself, exactly. + exact = mu == 0.0 + w[exact] = k == 0 + idx = np.clip(j0.astype(np.int64)[:, None] + k[None, :], 0, n - 1) + return idx, w, exact + + +def _bandlimited_operator(tq: np.ndarray, t: np.ndarray): + """Sparse ``[len(tq), len(t)]`` matrix resampling a trace on ``t`` at ``tq``.""" + from scipy.sparse import csr_matrix + + t0, dt, snap = _grid_fit(t) + idx, w, _ = _bandlimited_taps((np.asarray(tq, float) - t0) / dt, t.size, snap) + rows = np.repeat(np.arange(idx.shape[0]), idx.shape[1]) + op = csr_matrix((w.ravel(), (rows, idx.ravel())), shape=(idx.shape[0], t.size)) + # Drop the zero weights of on-grid rows, so a NaN in a neighbouring + # sample does not leak into an exact query (0 * NaN is NaN). + op.eliminate_zeros() + return op + + +def interp_bandlimited(tq: np.ndarray, t: np.ndarray, x: np.ndarray) -> np.ndarray: + """Band-limited counterpart of ``np.interp(tq, t, x)`` on a uniform axis. + + ``x`` may be 1-D or a stack ``[..., len(t)]`` resampled along its last + axis; real or complex. ``t`` must be uniformly sampled (float32 axes are + accepted, see :func:`_uniform_grid`). Uses a Kaiser-windowed sinc with + ``2 * _BL_HALF`` = 16 taps. + + Accuracy: the complex response error ``|H - 1|`` is below 0.005 up to + 0.8 Nyquist (f/fs 0.4) for every fractional offset, but grows to 0.26 at + f/fs 0.45. Near DC it is about 0.001 (the weights sum to 0.9988-1.0), + slightly worse than linear interpolation (0.0005 at f/fs 0.01); the + kernel pays off above about 0.05 fs. + + Edges and gaps: queries outside ``t`` are clamped to the end samples, as + ``np.interp`` does, and taps that reach past either end (up to 8 + samples) read the end sample. A query that falls exactly on a sample + returns that sample. Any other query reads 16 samples, so one NaN in + ``x`` makes up to 16 output samples NaN (``np.interp``: 2). + """ + x = np.asarray(x) + x = x.astype(np.result_type(x, float), copy=False) + t0, dt, snap = _grid_fit(t) + tq = np.asarray(tq, float) + idx, w, exact = _bandlimited_taps((tq.ravel() - t0) / dt, t.size, snap) + out = np.einsum("...qk,qk->...q", x[..., idx], w) + # On-grid rows become a plain gather, so NaNs nearby cannot reach them. + if exact.any(): + out[..., exact] = x[..., idx[exact, _BL_HALF - 1]] + return out.reshape(x.shape[:-1] + tq.shape) + + +def _resolve_interp( + interp: str, + band: tuple[float, float], + fs: float, + t: np.ndarray | None = None, +) -> str: + """Map ``interp`` ('auto' | 'linear' | 'bandlimited') to a concrete kernel. + + Under ``'auto'`` an axis ``t`` that is not uniformly sampled falls back to + linear with a ``UserWarning``; an explicit ``'bandlimited'`` raises there + instead (in :func:`_uniform_grid`). Band-limited mode warns when + ``band[1] / fs`` exceeds 0.4, where the kernel loses accuracy. + """ + if interp == "auto": + mode = "bandlimited" if band[1] / fs > _AUTO_BANDLIMITED_FRAC else "linear" + if mode == "bandlimited" and t is not None and not _is_uniform(t): + warnings.warn( + "interp='auto': the lag axis is not uniformly sampled, so the " + "band-limited kernel cannot be used; falling back to linear " + "interpolation, which biases dv/v above about 0.1 fs.", + stacklevel=3, + ) + mode = "linear" + elif interp in ("linear", "bandlimited"): + mode = interp + else: + raise ValueError( + f"interp must be 'auto', 'linear' or 'bandlimited', got {interp!r}" + ) + if mode == "bandlimited" and band[1] / fs > _BL_MAX_FRAC: + warnings.warn( + f"band upper edge {band[1]:g} Hz is {band[1] / fs:.2f} fs, above " + f"{_BL_MAX_FRAC:g} fs (0.8 Nyquist) where the band-limited kernel " + "is accurate to 0.5 %; expect a dv/v bias of several percent.", + stacklevel=3, + ) + return mode + + +def _resample(tq: np.ndarray, t: np.ndarray, x: np.ndarray, interp: str) -> np.ndarray: + """``np.interp`` or :func:`interp_bandlimited`, chosen by ``interp``.""" + if interp == "linear": + return np.interp(tq, t, x) + if interp == "bandlimited": + return interp_bandlimited(tq, t, x) + raise ValueError(f"interp must be 'linear' or 'bandlimited', got {interp!r}") + + +def _query_axis(t: np.ndarray, interp: str) -> np.ndarray: + """Lag axis used to form query points: float64 for the band-limited path. + + The linear path keeps ``t`` as given, so its output is unchanged; the + band-limited path avoids rounding the queries back to a float32 axis. + """ + return np.asarray(t, float) if interp == "bandlimited" else t + + +def impose_dvv( + ref: np.ndarray, t: np.ndarray, dvv: float, *, interp: str = "bandlimited" +) -> np.ndarray: """Apply a homogeneous velocity change by stretching the coda in lapse time. **Sign convention (physical dv/v)**: ``dvv`` is the fractional velocity change. A velocity *increase* (``dvv > 0``) shortens travel times, so a feature at reference lapse ``tau`` appears at ``tau / (1 + dvv)`` on the current waveform -- equivalently, ``current(t) = reference(t*(1+dvv))`` - for every ``t``, which is exactly the ``np.interp`` call below: the - output at time ``t`` is the reference sampled at ``t*(1+dvv)``. This is - the exact time-ratio relation implied by ``t_current/t_reference = - 1/(1+dvv)``, not a first-order approximation. + for every ``t``: the output at time ``t`` is the reference sampled at + ``t*(1+dvv)``. This is the exact time-ratio relation implied by + ``t_current/t_reference = 1/(1+dvv)``, not a first-order approximation. + + ``interp='bandlimited'`` (default) resamples with a windowed sinc + (:func:`interp_bandlimited`). ``interp='linear'`` reproduces the + ``np.interp`` call used before this option existed; it injects too + little stretch above about 0.1 fs (0.56x the requested dv/v at + 11.3-20 Hz, fs 50 Hz, dv/v -0.1 %). The stretching estimators invert this relation the other way: they resample the *current* waveform (not the reference) at trial positions @@ -222,11 +460,16 @@ def impose_dvv(ref: np.ndarray, t: np.ndarray, dvv: float) -> np.ndarray: first-order accurate). (Before v0.4.0 this function used the epsilon convention: positive argument meant coda dilation, i.e. a slowdown.) """ - return np.interp(t * (1.0 + dvv), t, ref) + return _resample(_query_axis(t, interp) * (1.0 + dvv), t, ref, interp) def impose_dvv_branch( - ref: np.ndarray, t: np.ndarray, dvv_causal: float, dvv_acausal: float + ref: np.ndarray, + t: np.ndarray, + dvv_causal: float, + dvv_acausal: float, + *, + interp: str = "bandlimited", ) -> np.ndarray: """Apply *different* velocity changes to the causal and acausal branches. @@ -237,12 +480,14 @@ def impose_dvv_branch( other --- not because either branch is "wrong", but because they measure partly different quantities. This stretches each branch about zero lag by its own ``dv/v`` so a heterogeneous change can be imposed and its ground truth is - known per branch (see :func:`fig_branch_asymmetry`). + known per branch (see :func:`fig_branch_asymmetry`). ``interp`` is as in + :func:`impose_dvv`. """ out = np.empty_like(ref) causal = t >= 0 - out[causal] = np.interp(t[causal] * (1.0 + dvv_causal), t, ref) - out[~causal] = np.interp(t[~causal] * (1.0 + dvv_acausal), t, ref) + tq = _query_axis(t, interp) + out[causal] = _resample(tq[causal] * (1.0 + dvv_causal), t, ref, interp) + out[~causal] = _resample(tq[~causal] * (1.0 + dvv_acausal), t, ref, interp) return out @@ -259,6 +504,7 @@ def daily_ccfs( decorr: float = 0.0, gen_band: tuple[float, float] = (0.05, 10.0), seed: int = 1, + interp: str = "bandlimited", ) -> np.ndarray: """Generate a stack of noisy daily CCFs with imposed, per-component dv/v. @@ -274,6 +520,8 @@ def daily_ccfs( Fraction of an independent fresh coda added each day, modelling non-repeatable noise sources / changing scatterers (waveform decorrelation), which biases as well as scatters. + interp + Resampling kernel of :func:`impose_dvv` ('bandlimited' or 'linear'). """ rng = np.random.default_rng(seed) ndays = len(dvv_series[0]) @@ -283,7 +531,7 @@ def daily_ccfs( for d in range(ndays): sig = np.zeros(nlag) for comp, series in zip(components, dvv_series, strict=False): - sig = sig + impose_dvv(comp, t, float(series[d])) + sig = sig + impose_dvv(comp, t, float(series[d]), interp=interp) if decorr > 0: fresh = bandpass(rng.standard_normal(nlag), fs, *gen_band) fresh *= np.exp(-np.abs(t) / 12.0) @@ -305,6 +553,7 @@ def branch_daily_ccfs( snr: float = 8.0, gen_band: tuple[float, float] = (0.05, 10.0), seed: int = 1, + interp: str = "bandlimited", ) -> np.ndarray: """Daily CCFs whose causal and acausal branches carry *different* dv/v(t). @@ -313,7 +562,8 @@ def branch_daily_ccfs( both arguments reproduces a homogeneous (branch-symmetric) medium; passing a strong causal and a weak acausal series models a change localized in the volume the causal branch samples (the heterogeneous case in - :func:`fig_branch_asymmetry`). + :func:`fig_branch_asymmetry`). ``interp`` selects the resampling kernel + of :func:`impose_dvv_branch`. """ if ref.shape != t.shape: raise ValueError( @@ -331,7 +581,9 @@ def branch_daily_ccfs( ref_rms = np.sqrt(np.mean(ref**2)) out = np.empty((ndays, t.size)) for d in range(ndays): - sig = impose_dvv_branch(ref, t, float(dvv_causal[d]), float(dvv_acausal[d])) + sig = impose_dvv_branch( + ref, t, float(dvv_causal[d]), float(dvv_acausal[d]), interp=interp + ) noise = bandpass(rng.standard_normal(t.size), fs, *gen_band) noise *= (ref_rms / snr) / np.sqrt(np.mean(noise**2)) out[d] = sig + noise @@ -357,6 +609,7 @@ def _stretch_window( window: tuple[float, float], eps_max: float, branch: str = "both", + margin: float = 0.0, *, min_samples: int = 8, ) -> tuple[np.ndarray, tuple[float, float]]: @@ -374,6 +627,11 @@ def _stretch_window( changing valid-support size cannot spuriously change which epsilon looks like the best-correlated one. + ``margin`` (seconds) is kept free beyond the last query point. The + band-limited kernel reads ``_BL_HALF`` samples past it, so the + estimators pass ``_BL_HALF * dt`` in that mode; with 0 the linear + gather's support is unchanged. + 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"`` @@ -385,7 +643,7 @@ def _stretch_window( ``(w0, w1)`` is the (possibly shrunk) window actually used. """ w0, w1 = window - tmax = float(np.max(np.abs(t))) if t.size else 0.0 + tmax = float(np.max(np.abs(t))) - margin if t.size else 0.0 safe_w1 = min(w1, tmax / (1.0 + eps_max)) if eps_max > -1.0 else w1 if safe_w1 < w0: raise ValueError( @@ -397,8 +655,8 @@ def _stretch_window( warnings.warn( f"coda window upper edge {w1:g} shrunk to {safe_w1:.6g} so every " f"trial epsilon (|eps| <= {eps_max:g}) stays within the current " - "trace's recorded support (t_current = (1+eps)*t); no sample is " - "extrapolated. Pass a narrower window or a smaller eps_max to " + "trace's recorded support (t_current = (1+eps)*t), including the " + "resampling kernel's reach; no sample is extrapolated. Pass a narrower window or a smaller eps_max to " "silence this.", stacklevel=3, ) @@ -415,6 +673,28 @@ def _stretch_window( return sel, (w0, w1) +def _stretch_select( + t: np.ndarray, + window: tuple[float, float], + eps_max: float, + branch: str, + mode: str, +) -> tuple[np.ndarray, np.ndarray]: + """Window mask and lag values for the estimators' resampling kernel. + + Linear mode is :func:`_stretch_window` and ``t[sel]``, as before. + Band-limited mode keeps ``_BL_HALF * dt`` clear of the trace end and + returns the window lags in float64, so a float32 axis is not rounded + again when the trial positions ``(1 + eps) * t`` are formed. + """ + if mode != "bandlimited": + sel, _ = _stretch_window(t, window, eps_max, branch) + return sel, t[sel] + _, dt = _uniform_grid(t) + sel, _ = _stretch_window(t, window, eps_max, branch, margin=_BL_HALF * dt) + return sel, np.asarray(t, float)[sel] + + def _parabolic(y: np.ndarray, i: int) -> float: """Sub-sample peak offset (in index units) from a 3-point parabola fit.""" if i <= 0 or i >= len(y) - 1: @@ -436,6 +716,7 @@ def stretching_cc( eps_max: float = 0.06, n_eps: int = 161, prefiltered: bool = False, + interp: str = "auto", ) -> tuple[np.ndarray, np.ndarray]: """The full correlation-coefficient image ``CC(epsilon, time)``. @@ -458,26 +739,43 @@ def stretching_cc( band-passed at ``band`` and the internal band-pass is skipped (valid because band-passing is linear and commutes with the linear stacking that builds references — see :func:`codameter.deviations.run_pipeline`). + + ``interp`` sets how the current trace is resampled at the trial + positions. ``'linear'`` is the linear gather used before this option + existed (bit-identical). ``'bandlimited'`` uses the windowed-sinc kernel + of :func:`interp_bandlimited`. ``'auto'`` (default) picks band-limited + when ``band[1] / fs > 0.05`` and linear otherwise. Linear resampling + over-reads dv/v by 13-34 % at 8-20 Hz with fs 50 Hz and |dv/v| = 0.1 %. + The band-limited kernel is accurate up to ``band[1] / fs = 0.4`` (0.8 + Nyquist) and a warning is raised above that; under ``'auto'`` an + irregular lag axis falls back to linear with a warning. In band-limited + mode the window keeps 8 extra samples clear of the trace end (see + :func:`_stretch_window`). """ + mode = _resolve_interp(interp, band, fs, t) cur_mat = np.atleast_2d(np.asarray(cur_mat, float)) curf_full = cur_mat if prefiltered else bandpass(cur_mat, fs, *band) reff = ref if prefiltered else bandpass(ref, fs, *band) es = np.linspace(-eps_max, eps_max, n_eps) - sel, _ = _stretch_window(t, window, eps_max, branch) - tsel = t[sel] + sel, tsel = _stretch_select(t, window, eps_max, branch, mode) refw = reff[sel] refw = refw / (np.linalg.norm(refw) + 1e-12) cc = np.empty((curf_full.shape[0], n_eps)) + if mode == "bandlimited": + cur_t = np.ascontiguousarray(curf_full.T) for ei, e in enumerate(es): - # Gather indices/weights of np.interp((1+e)*t, t, .) on the window, - # clamped at the grid ends exactly as np.interp clamps -- unreached - # in practice since _stretch_window keeps every trial in-bounds. - q = (1.0 + e) * tsel - j = np.clip(np.searchsorted(t, q, side="right") - 1, 0, t.size - 2) - w = np.clip((q - t[j]) / (t[j + 1] - t[j]), 0.0, 1.0) - trials = curf_full[:, j] * (1.0 - w) + curf_full[:, j + 1] * w + if mode == "bandlimited": + trials = (_bandlimited_operator((1.0 + e) * tsel, t) @ cur_t).T + else: + # Gather indices/weights of np.interp((1+e)*t, t, .) on the window, + # clamped at the grid ends exactly as np.interp clamps -- unreached + # in practice since _stretch_window keeps every trial in-bounds. + q = (1.0 + e) * tsel + j = np.clip(np.searchsorted(t, q, side="right") - 1, 0, t.size - 2) + w = np.clip((q - t[j]) / (t[j + 1] - t[j]), 0.0, 1.0) + trials = curf_full[:, j] * (1.0 - w) + curf_full[:, j + 1] * w trials = trials / (np.linalg.norm(trials, axis=1, keepdims=True) + 1e-12) cc[:, ei] = trials @ refw return es, cc # [ndays, n_eps] @@ -654,14 +952,15 @@ def measure_stretching( eps_max: float = 0.06, n_eps: int = 161, prefiltered: bool = False, + interp: str = "auto", ) -> tuple[np.ndarray, np.ndarray]: """Stretching dv/v: grid-search the stretch maximizing windowed correlation. ``ref`` is a single reference vector (fixed-reference scheme). ``branch`` selects the causal, acausal, or both coda branches — measuring the two branches separately is the standard clock-error diagnostic. Returns the - per-day dv/v and the peak correlation coefficient. ``prefiltered`` is - forwarded to :func:`stretching_cc`. + per-day dv/v and the peak correlation coefficient. ``prefiltered`` and + ``interp`` are forwarded to :func:`stretching_cc`. """ es, cc = stretching_cc( cur_mat, @@ -674,6 +973,7 @@ def measure_stretching( eps_max=eps_max, n_eps=n_eps, prefiltered=prefiltered, + interp=interp, ) return peak_dvv(es, cc) @@ -723,6 +1023,7 @@ def measure_stretching_trailing( eps_max: float = 0.06, n_eps: int = 161, prefiltered: bool = False, + interp: str = "auto", min_frac: float = 0.5, ) -> tuple[np.ndarray, np.ndarray]: """Vectorized stretching against a trailing reference (previous ``ref_days``). @@ -739,7 +1040,7 @@ def measure_stretching_trailing( band-pass runs over the whole matrix in one FFT. Returns ``(dvv, cc)`` over the full length of ``cur_mat``; the ``ref_days`` - warm-up epochs are NaN. + warm-up epochs are NaN. ``interp`` is as in :func:`stretching_cc`. 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, @@ -751,6 +1052,7 @@ def measure_stretching_trailing( """ if not 0.0 <= min_frac <= 1.0: raise ValueError(f"min_frac must lie in [0, 1], got {min_frac}") + mode = _resolve_interp(interp, band, fs, t) cur_mat = np.atleast_2d(np.asarray(cur_mat, float)) ndays, nlag = cur_mat.shape dvv = np.full(ndays, np.nan) @@ -772,8 +1074,7 @@ def measure_stretching_trailing( 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) - tsel = t[sel] + sel, tsel = _stretch_select(t, window, eps_max, branch, mode) refw = reffs[:, sel] refw = refw / (np.linalg.norm(refw, axis=1, keepdims=True) + 1e-12) @@ -783,14 +1084,19 @@ def measure_stretching_trailing( es = np.linspace(-eps_max, eps_max, n_eps) cc_img = np.empty((ndays - ref_days, n_eps)) + if mode == "bandlimited": + cur_t = np.ascontiguousarray(curf.T) for ei, e in enumerate(es): - # Gather indices/weights of np.interp((1+e)*t, t, .) on the window, - # clamped at the grid ends exactly as np.interp clamps -- unreached - # in practice since _stretch_window keeps every trial in-bounds. - q = (1.0 + e) * tsel - j = np.clip(np.searchsorted(t, q, side="right") - 1, 0, t.size - 2) - w = np.clip((q - t[j]) / (t[j + 1] - t[j]), 0.0, 1.0) - trials = curf[:, j] * (1.0 - w) + curf[:, j + 1] * w + if mode == "bandlimited": + trials = (_bandlimited_operator((1.0 + e) * tsel, t) @ cur_t).T + else: + # Gather indices/weights of np.interp((1+e)*t, t, .) on the window, + # clamped at the grid ends exactly as np.interp clamps -- unreached + # in practice since _stretch_window keeps every trial in-bounds. + q = (1.0 + e) * tsel + j = np.clip(np.searchsorted(t, q, side="right") - 1, 0, t.size - 2) + w = np.clip((q - t[j]) / (t[j + 1] - t[j]), 0.0, 1.0) + trials = curf[:, j] * (1.0 - w) + curf[:, j + 1] * w trials = trials / (np.linalg.norm(trials, axis=1, keepdims=True) + 1e-12) cc_img[:, ei] = np.einsum("ij,ij->i", trials, refw) dvv[ref_days:], cc_peak[ref_days:] = peak_dvv(es, cc_img) @@ -1059,6 +1365,7 @@ def measure_wts( w0: float = 6.0, eps_max: float = 0.06, n_eps: int = 121, + interp: str = "auto", ) -> np.ndarray: """WTS dv/v: stretching applied per scale of the wavelet transform. @@ -1068,22 +1375,30 @@ def measure_wts( (reference fixed, as in :func:`stretching_cc`) -- the stretch that best aligns them is found per scale and pooled, power-weighted (NoisePy ``wts_dvv``). Being a stretching variant it is robust to large dv/v, - like time-domain TS. + like time-domain TS. ``interp`` is as in :func:`stretching_cc`. """ cur_mat = np.atleast_2d(cur_mat) reg, tt, freqs, _ = _cwt_setup(t, window, band, nfreq) - wsel, _ = _stretch_window(tt, window, eps_max, branch="causal") + mode = _resolve_interp(interp, band, fs, tt) + wsel, ttsel = _stretch_select(tt, window, eps_max, "causal", mode) Wref = _morlet_cwt(ref[reg], fs, freqs, w0).real refbank = Wref[:, wsel] refbank = refbank / (np.linalg.norm(refbank, axis=1, keepdims=True) + 1e-12) es = np.linspace(-eps_max, eps_max, n_eps) - ttsel = tt[wsel] + if mode == "bandlimited": + # One stacked [n_eps * n_win, n_tt] operator, built once for all days. + op = _bandlimited_operator(np.concatenate([(1.0 + e) * ttsel for e in es]), tt) out = np.full(cur_mat.shape[0], np.nan) for d in range(cur_mat.shape[0]): Wcur = _morlet_cwt(cur_mat[d, reg], fs, freqs, w0).real num = den = 0.0 for k in range(freqs.size): - trials = np.stack([np.interp((1.0 + e) * ttsel, tt, Wcur[k]) for e in es]) + if mode == "bandlimited": + trials = (op @ Wcur[k]).reshape(es.size, ttsel.size) + else: + trials = np.stack( + [np.interp((1.0 + e) * ttsel, tt, Wcur[k]) for e in es] + ) trials /= np.linalg.norm(trials, axis=1, keepdims=True) + 1e-12 cc = trials @ refbank[k] i = int(np.argmax(cc)) @@ -1187,19 +1502,27 @@ def make_freqdep_coda( def add_clock_drift( - ccfs: np.ndarray, t: np.ndarray, *, drift_s_per_day: float, onset_day: int = 0 + ccfs: np.ndarray, + t: np.ndarray, + *, + drift_s_per_day: float, + onset_day: int = 0, + interp: str = "bandlimited", ) -> np.ndarray: """Inject a station-timing (clock) error: a growing shift of the whole CCF. A clock error delays the entire correlation by τ(day), moving the zero-lag peak. Unlike a velocity change it is a *constant* lag (independent of lapse), so it appears with opposite sign on the causal and acausal branches — the - diagnostic that separates it from a real dv/v. + diagnostic that separates it from a real dv/v. The shift uses the + band-limited kernel by default; ``interp='linear'`` gives the former + ``np.interp`` shift. """ out = np.empty_like(ccfs) + tq = _query_axis(t, interp) for d in range(ccfs.shape[0]): tau = drift_s_per_day * max(0, d - onset_day) - out[d] = np.interp(t - tau, t, ccfs[d]) + out[d] = _resample(tq - tau, t, ccfs[d], interp) return out @@ -1250,6 +1573,7 @@ def measure_inversion( max_lag_blocks: int = 10, smooth: float = 5.0, prefiltered: bool = False, + interp: str = "auto", ) -> np.ndarray: """Brenguier et al. (2014)-style joint inversion for a continuous dv/v series. @@ -1258,7 +1582,8 @@ def measure_inversion( system ``x_i − x_j = m_ij`` (coherence-weighted, with a smoothness penalty) for the per-block series ``x``. Using many references makes the result robust to the choice of any single one, and — unlike a moving reference — it - preserves the long-term trend. + preserves the long-term trend. ``interp`` is passed to + :func:`measure_stretching`. """ ndays = ccfs.shape[0] edges = np.arange(0, ndays - block_days + 1, block_days) @@ -1279,6 +1604,7 @@ def measure_inversion( eps_max=0.03, n_eps=81, prefiltered=prefiltered, + interp=interp, ) for i in range(j + 1, min(m, j + max_lag_blocks + 1)): rows += [eq, eq] diff --git a/tests/data/golden/manifest.json b/tests/data/golden/manifest.json index eb7ddce..b5f20e1 100644 --- a/tests/data/golden/manifest.json +++ b/tests/data/golden/manifest.json @@ -1,5 +1,5 @@ { - "version": 3, + "version": 4, "grades": [ "easy", "medium", @@ -36,7 +36,7 @@ "gate": true }, "eps_max": 0.06, - "rms": 0.00016366904839408612 + "rms": 0.00016366662661155166 } }, { @@ -69,7 +69,7 @@ "gate": true }, "eps_max": 0.05, - "rms": 0.00023685666694590966 + "rms": 0.00023665386188895124 } }, { @@ -102,7 +102,7 @@ "gate": true }, "eps_max": 0.03, - "rms": 0.0003411112016349412, + "rms": 0.0003410257632020687, "rms_wrong_layer": 0.0010007890743546153 }, "two_layer": true, diff --git a/tests/test_stretching_interpolation.py b/tests/test_stretching_interpolation.py index 2ea5cf1..ccdd0c6 100644 --- a/tests/test_stretching_interpolation.py +++ b/tests/test_stretching_interpolation.py @@ -13,8 +13,11 @@ that would pass even if generator and estimator were *both* wrong in the same way (this is exactly the pre-v0.4.0 failure mode: internally coherent, anticorrelated with reality). ``test_independent_analytic_oracle_*`` below -is deliberately built without calling ``impose_dvv`` or ``make_coda`` at -all, so it does not share that blind spot. +is deliberately built without calling ``impose_dvv``, ``make_coda`` or any +interpolator: the current trace is the closed-form coda evaluated at +``t * (1 + dvv)``, so it does not share that blind spot. The high-frequency +oracle (8-16 Hz and 11.3-20 Hz at fs 50 Hz) locks the band-limited +resampling: linear interpolation over-reads dv/v there by 13-34 %. """ from __future__ import annotations @@ -25,7 +28,10 @@ import numpy as np import pytest from codameter.synthetic_demo import ( + _BL_HALF, Synth, + _bandlimited_operator, + _stretch_select, _stretch_window, _window_mask, bandpass, @@ -33,9 +39,12 @@ dvv_to_epsilon, eps_to_dvv, impose_dvv, + impose_dvv_branch, + interp_bandlimited, make_coda, measure_stretching, measure_stretching_trailing, + measure_wts, peak_dvv, stretching_cc, ) @@ -85,8 +94,9 @@ def test_independent_analytic_oracle_recovers_dvv(dvv_true): bug (the actual pre-v0.4.0 failure) cannot hide behind this test.""" t = np.arange(-2500, 2501) / FS # +/-50 s, independent of Synth() reference = _handbuilt_coda(t) - # Physical relation applied by hand: current(t) = reference(t*(1+dvv)). - current = np.interp(t * (1.0 + dvv_true), t, reference)[None, :] + # Physical relation in closed form: current(t) = reference(t*(1+dvv)), + # evaluated analytically, with no interpolation of sampled data. + current = _handbuilt_coda(t * (1.0 + dvv_true))[None, :] rec, cc = measure_stretching( current, reference, t, band=BAND, fs=FS, window=WINDOW, eps_max=0.06 ) @@ -94,6 +104,346 @@ def test_independent_analytic_oracle_recovers_dvv(dvv_true): assert cc[0] > 0.99 +def _tone_coda(t: np.ndarray, freqs: np.ndarray, phases: np.ndarray) -> np.ndarray: + """Closed-form symmetric coda: a sum of tones with a 6 s decay.""" + a = np.abs(t)[:, None] + return np.cos(2 * np.pi * freqs[None, :] * a + phases[None, :]).sum(1) * np.exp( + -np.abs(t) / 6.0 + ) + + +def _tones(band, seed, n=40): + rng = np.random.default_rng(seed) + freqs = rng.uniform(band[0] * 1.05, band[1] * 0.95, n) + return freqs, rng.uniform(0.0, 2 * np.pi, n) + + +HF_CASES = [((8.0, 16.0), (1.0, 6.0)), ((11.3, 20.0), (1.0, 4.0))] + + +@pytest.mark.parametrize("band,window", HF_CASES) +@pytest.mark.parametrize("dvv_true", [-0.001, -0.005]) +def test_independent_analytic_oracle_high_frequency(band, window, dvv_true): + """Closed-form oracle at fs 50 Hz, 8-16 and 11.3-20 Hz: |gain - 1| < 0.02. + + Before band-limited resampling the default estimator read 1.13 (8-16 Hz) + and 1.34 (11.3-20 Hz) times the true dv/v at -0.1 %, and 0.94 at + 11.3-20 Hz and -0.5 %. + """ + t = np.arange(-1250, 1251) / FS + for seed in range(3): + freqs, phases = _tones(band, seed) + reference = _tone_coda(t, freqs, phases) + current = _tone_coda(t * (1.0 + dvv_true), freqs, phases) + rec, cc = measure_stretching( + current[None, :], reference, t, band=band, fs=FS, window=window + ) + gain = rec[0] / dvv_true + assert abs(gain - 1.0) < 0.02, f"seed {seed}: gain {gain:.3f}" + assert cc[0] > 0.99 + + +@pytest.mark.parametrize("band,window", HF_CASES) +@pytest.mark.parametrize("dvv_true", [-0.001, -0.005]) +def test_impose_dvv_matches_closed_form_high_frequency(band, window, dvv_true): + """impose_dvv injects the requested stretch at 8-20 Hz (fs 50 Hz). + + Checked two ways: the injected trace is close to the closed-form stretch + sample by sample, and the band-limited estimator reads it back with + |gain - 1| < 0.02. Linear injection gave 0.78x (8-16 Hz) and 0.56x + (11.3-20 Hz) of the requested -0.1 %. + """ + t = np.arange(-1250, 1251) / FS + freqs, phases = _tones(band, 7) + reference = _tone_coda(t, freqs, phases) + exact = _tone_coda(t * (1.0 + dvv_true), freqs, phases) + injected = impose_dvv(reference, t, dvv_true) + sel = _window_mask(t, window) + rel = np.linalg.norm((injected - exact)[sel]) / np.linalg.norm(exact[sel]) + assert rel < 0.01 + rec, _ = measure_stretching( + injected[None, :], reference, t, band=band, fs=FS, window=window + ) + assert abs(rec[0] / dvv_true - 1.0) < 0.02 + + +def test_interp_bandlimited_accuracy_at_08_nyquist(): + """Kernel amplitude/delay error < 0.02 at 0.8 Nyquist, all fractional offsets.""" + n = np.arange(4000, dtype=float) + q = 1000.0 + np.arange(2000) + np.linspace(0.0, 1.0, 2000) + for fr in (0.1, 0.3, 0.4): + x = np.cos(2 * np.pi * fr * n + 0.4) + err = np.max( + np.abs(interp_bandlimited(q, n, x) - np.cos(2 * np.pi * fr * q + 0.4)) + ) + assert err < 0.02, (fr, err) + + +def test_interp_bandlimited_exact_on_grid_and_stacks(): + t = np.arange(-500, 501) / FS + x = np.random.default_rng(0).standard_normal((3, t.size)) + assert np.array_equal(interp_bandlimited(t, t, x), x) + assert np.array_equal(interp_bandlimited(t[:-2] + 2 / FS, t, x[1]), x[1, 2:]) + assert np.array_equal(impose_dvv(x[0], t, 0.0), x[0]) + q = t * 1.003 + stacked = interp_bandlimited(q, t, x) + assert np.allclose(stacked[2], interp_bandlimited(q, t, x[2]), rtol=0, atol=1e-14) + with pytest.raises(ValueError): + interp_bandlimited( + q, np.sort(np.random.default_rng(1).uniform(-10, 10, t.size)), x[0] + ) + + +def test_linear_mode_reproduces_np_interp(): + """interp='linear' is the former code path, bit for bit.""" + s = Synth() + for dvv in (0.003, -0.02): + assert np.array_equal( + impose_dvv(s.ref, s.t, dvv, interp="linear"), + np.interp(s.t * (1.0 + dvv), s.t, s.ref), + ) + causal = s.t >= 0 + legacy = np.empty_like(s.ref) + legacy[causal] = np.interp(s.t[causal] * 1.01, s.t, s.ref) + legacy[~causal] = np.interp(s.t[~causal] * 0.995, s.t, s.ref) + assert np.array_equal( + impose_dvv_branch(s.ref, s.t, 0.01, -0.005, interp="linear"), legacy + ) + + +def _legacy_linear_stretching_cc(cur_mat, ref, t, *, band, fs, window, eps_max, n_eps): + """Copy of the linear gather in stretching_cc before the interp option.""" + cur_mat = np.atleast_2d(np.asarray(cur_mat, float)) + curf_full = bandpass(cur_mat, fs, *band) + reff = bandpass(ref, fs, *band) + es = np.linspace(-eps_max, eps_max, n_eps) + sel, _ = _stretch_window(t, window, eps_max, "both") + tsel = t[sel] + refw = reff[sel] + refw = refw / (np.linalg.norm(refw) + 1e-12) + cc = np.empty((curf_full.shape[0], n_eps)) + for ei, e in enumerate(es): + q = (1.0 + e) * tsel + j = np.clip(np.searchsorted(t, q, side="right") - 1, 0, t.size - 2) + w = np.clip((q - t[j]) / (t[j + 1] - t[j]), 0.0, 1.0) + trials = curf_full[:, j] * (1.0 - w) + curf_full[:, j + 1] * w + trials = trials / (np.linalg.norm(trials, axis=1, keepdims=True) + 1e-12) + cc[:, ei] = trials @ refw + return es, cc + + +@pytest.mark.parametrize("band", [(0.3, 2.0), (8.0, 16.0)]) +def test_linear_interp_is_bit_identical_to_legacy(band): + s = Synth() + cur = daily_ccfs(s.t, [s.ref], [np.array([0.002, -0.004])], fs=FS, seed=3) + kw = dict(band=band, fs=FS, window=(3.0, 20.0), eps_max=0.03, n_eps=61) + _, cc_old = _legacy_linear_stretching_cc(cur, s.ref, s.t, **kw) + _, cc_new = stretching_cc(cur, s.ref, s.t, interp="linear", **kw) + assert np.array_equal(cc_old, cc_new) + + +def test_auto_interp_switch(): + """'auto' keeps the linear gather at band[1]/fs <= 0.05, else band-limited.""" + s = Synth() + cur = daily_ccfs(s.t, [s.ref], [np.array([0.003])], fs=FS, seed=4) + kw = dict(fs=FS, window=(3.0, 20.0), eps_max=0.03, n_eps=61) + for band, expect in ( + ((0.3, 2.0), "linear"), + ((1.0, 2.5), "linear"), + ((1.0, 2.6), "bandlimited"), + ((8.0, 16.0), "bandlimited"), + ): + _, auto = stretching_cc(cur, s.ref, s.t, band=band, **kw) + _, fixed = stretching_cc(cur, s.ref, s.t, band=band, interp=expect, **kw) + assert np.array_equal(auto, fixed), band + with pytest.raises(ValueError): + stretching_cc(cur, s.ref, s.t, band=(0.3, 2.0), interp="cubic", **kw) + + +def test_trailing_and_wts_accept_interp(): + """The trailing fast path and WTS honour interp and stay close at high f.""" + t = np.arange(-1250, 1251) / FS + freqs, phases = _tones((8.0, 16.0), 2) + ref = _tone_coda(t, freqs, phases) + dvv = -0.002 + rows = np.vstack([ref] * 5 + [_tone_coda(t * (1.0 + dvv), freqs, phases)]) + kw = dict(band=(8.0, 16.0), fs=FS, window=(1.0, 6.0), eps_max=0.03, n_eps=121) + d_bl, c_bl = measure_stretching_trailing(rows, t, ref_days=5, **kw) + assert abs(d_bl[5] / dvv - 1.0) < 0.02 + d_loop, c_loop = measure_stretching(rows[5], rows[:5].mean(axis=0), t, **kw) + assert d_bl[5] == pytest.approx(d_loop[0], abs=1e-10) + assert c_bl[5] == pytest.approx(c_loop[0], abs=1e-10) + d_lin, _ = measure_stretching_trailing(rows, t, ref_days=5, interp="linear", **kw) + assert abs(d_lin[5] - d_bl[5]) > 1e-6 + w_bl = measure_wts(rows[5:], ref, t, nfreq=6, **kw) + w_lin = measure_wts(rows[5:], ref, t, nfreq=6, interp="linear", **kw) + assert np.isfinite(w_bl[0]) and np.isfinite(w_lin[0]) + assert abs(w_bl[0] / dvv - 1.0) <= abs(w_lin[0] / dvv - 1.0) + 0.02 + + +def test_bandlimited_trailing_skips_missing_day(): + """A missing day stays NaN on the band-limited trailing path (#57 with #56). + + The sparse operator acts on each day's column alone, so the NaN row does + not leak into other days, and later references skip it as in linear mode. + """ + t = np.arange(-1250, 1251) / FS + freqs, phases = _tones((8.0, 16.0), 2) + rows = np.vstack( + [_tone_coda(t * (1.0 - 0.0005 * (d % 3)), freqs, phases) for d in range(14)] + ) + gap = rows.copy() + gap[8] = np.nan + kw = dict(band=(8.0, 16.0), fs=FS, window=(1.0, 6.0), eps_max=0.03, n_eps=121) + clean, _ = measure_stretching_trailing(rows, t, ref_days=5, **kw) + dvv, cc = measure_stretching_trailing(gap, t, ref_days=5, **kw) + assert np.isnan(dvv[8]) and np.isnan(cc[8]) + assert np.isfinite(dvv[9:]).all() and np.isfinite(cc[9:]).all() + np.testing.assert_array_equal(dvv[:8], clean[:8]) + for d in (9, 11, 13): + keep = [i for i in range(d - 5, d) if i != 8] + d_loop, _ = measure_stretching(gap[d], gap[keep].mean(axis=0), t, **kw) + assert dvv[d] == pytest.approx(d_loop[0], abs=1e-10) + + +def test_float32_lag_axis_is_accepted(): + """Float32 lags (HDF5, ASDF, zarr) worked with np.interp and must still work. + + Their spacing errors reach about 1e-4 dt, which a 1e-6 dt uniformity + check rejected under the default interp. + """ + t = np.arange(-1250, 1251) / FS + t32 = t.astype(np.float32) + freqs, phases = _tones((8.0, 16.0), 5) + ref = _tone_coda(t, freqs, phases) + a = impose_dvv(ref, t32, -0.001) + b = impose_dvv(ref, t, -0.001) + assert np.max(np.abs(a - b)) < 1e-3 * np.max(np.abs(ref)) + cur = _tone_coda(t * (1.0 - 0.001), freqs, phases) + kw = dict(band=(8.0, 16.0), fs=FS, window=(1.0, 6.0)) + rec32, _ = measure_stretching(cur[None, :], ref, t32, **kw) + rec64, _ = measure_stretching(cur[None, :], ref, t, **kw) + assert abs(rec32[0] / -0.001 - 1.0) < 0.02 + assert rec32[0] == pytest.approx(rec64[0], abs=1e-6) + long32 = (np.arange(-150000, 150001) / FS).astype(np.float32) # +/-3000 s + assert interp_bandlimited(long32[:5], long32, np.ones(long32.size)).size == 5 + + +@pytest.mark.parametrize("axis", ["float32", "jittered"]) +def test_own_samples_are_exact_on_accepted_axes(axis): + """A query at the axis' own samples is a gather on any axis that is accepted. + + Float32 lags sit up to about 1e-4 dt off the uniform line, and an + accepted float64 axis may sit up to 1e-3 dt off it. Snapping only within + 1e-9 samples left those queries interpolated: impose_dvv(dvv=0) moved the + trace by up to 4e-4 and one NaN spread to 17 samples (#56, Copilot). + """ + t = np.arange(-2500, 2501) / FS + if axis == "float32": + tt = t.astype(np.float32) + else: + tt = t + np.random.default_rng(4).uniform(-5e-4, 5e-4, t.size) / FS + x = np.random.default_rng(5).standard_normal(t.size) + np.testing.assert_array_equal(interp_bandlimited(tt, tt, x), x) + np.testing.assert_array_equal(impose_dvv(x, tt, 0.0), x) + xn = x.copy() + xn[2500] = np.nan + assert np.isnan(interp_bandlimited(tt, tt, xn)).sum() == 1 + op = _bandlimited_operator(np.asarray(tt, float), tt) + assert np.isnan(op @ xn).sum() == 1 + # Off-grid queries are still interpolated. + assert not np.array_equal(impose_dvv(x, tt, 0.001), x) + + +def test_auto_falls_back_to_linear_on_irregular_axis(): + t = np.arange(-1250, 1251) / FS + t_irr = t + np.random.default_rng(3).uniform(-0.2, 0.2, t.size) / FS + freqs, phases = _tones((8.0, 16.0), 6) + ref = _tone_coda(t_irr, freqs, phases) + cur = _tone_coda(t_irr * 0.999, freqs, phases) + kw = dict(band=(8.0, 16.0), fs=FS, window=(1.0, 6.0), n_eps=61) + with pytest.warns(UserWarning, match="not uniformly sampled"): + _, cc_auto = stretching_cc(cur, ref, t_irr, **kw) + _, cc_lin = stretching_cc(cur, ref, t_irr, interp="linear", **kw) + assert np.array_equal(cc_auto, cc_lin) + with pytest.raises(ValueError, match="uniformly sampled"): + stretching_cc(cur, ref, t_irr, interp="bandlimited", **kw) + + +def test_interp_bandlimited_complex_input(): + t = np.arange(-500, 501) / FS + rng = np.random.default_rng(8) + xr, xi = rng.standard_normal((2, t.size)) + q = t * 1.002 + out = interp_bandlimited(q, t, xr + 1j * xi) + assert np.iscomplexobj(out) + expect = interp_bandlimited(q, t, xr) + 1j * interp_bandlimited(q, t, xi) + assert np.allclose(out, expect, rtol=0, atol=1e-13) + assert np.allclose(impose_dvv(xr + 1j * xi, t, 0.002), expect, rtol=0, atol=1e-13) + + +def test_nan_footprint(): + """On-grid queries stay exact next to a NaN; off-grid ones spread it to 16.""" + t = np.arange(-500, 501) / FS + x = np.random.default_rng(9).standard_normal(t.size) + x[600] = np.nan + same = impose_dvv(x, t, 0.0) + assert np.isnan(same).sum() == 1 + assert np.array_equal(same[~np.isnan(x)], x[~np.isnan(x)]) + assert np.isnan(impose_dvv(x, t, 0.001)).sum() <= 2 * _BL_HALF + shift = interp_bandlimited(t[:-3] + 3 / FS, t, x) + assert np.isnan(shift).sum() == 1 + + +def test_bandlimited_window_keeps_kernel_inside_trace(): + """The 16-tap kernel never reads past the trace end in band-limited mode.""" + t = np.arange(-500, 501) / FS # +/-10 s + eps_max = 0.06 + with pytest.warns(UserWarning, match="shrunk"): + sel, tsel = _stretch_select(t, (2.0, 9.8), eps_max, "both", "bandlimited") + reach = np.max(np.abs(tsel)) * (1.0 + eps_max) + _BL_HALF / FS + assert reach <= 10.0 + 1e-9 + with pytest.warns(UserWarning, match="shrunk"): + sel_lin, _ = _stretch_select(t, (2.0, 9.8), eps_max, "both", "linear") + assert sel_lin.sum() > sel.sum() + + +def test_bandlimited_warns_above_08_nyquist(): + t = np.arange(-1250, 1251) / FS + freqs, phases = _tones((16.0, 24.0), 1) + ref = _tone_coda(t, freqs, phases) + with pytest.warns(UserWarning, match="0.8 Nyquist"): + measure_stretching( + ref[None, :], ref, t, band=(16.0, 24.0), fs=FS, window=(1, 4) + ) + + +def test_run_pipeline_honours_interp_key(): + """cfg['interp'] reaches the fixed, moving and inversion stretching paths.""" + from codameter.deviations import run_pipeline + + t = np.arange(-1000, 1001) / FS + freqs, phases = _tones((8.0, 16.0), 4) + days = np.arange(80) # the moving reference needs 45 warm-up days + truth = -0.002 * (days > 60) + rng = np.random.default_rng(11) + ccfs = np.stack( + [_tone_coda(t * (1.0 + d), freqs, phases) for d in truth] + ) + 0.05 * rng.standard_normal((days.size, t.size)) + base = dict( + estimator="stretching (TS)", band=(8.0, 16.0), window=(1.0, 6.0), stack=1 + ) + for ref in ("fixed", "moving", "inversion"): + cfg = dict(base, reference=ref, gate=False) + auto, _ = run_pipeline(ccfs, t, FS, cfg) + lin, _ = run_pipeline(ccfs, t, FS, dict(cfg, interp="linear")) + bl, _ = run_pipeline(ccfs, t, FS, dict(cfg, interp="bandlimited")) + ok = np.isfinite(auto) + assert ok.sum() >= 20, ref + assert np.array_equal(auto[ok], bl[ok]), ref + assert np.max(np.abs(auto[ok] - lin[ok])) > 1e-6, ref + + # --------------------------------------------------------------------------- # 3. Reciprocity: current-interpolated vs. reference-interpolated (req. 10) # ---------------------------------------------------------------------------