Add P6 benchmark code, locked protocol_bench, T2 study and lock inputs
- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
(sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- The eight protocol_bench inputs force-added from outputs/ (warp prior,
wavelets, horizon cache, budgets) so load_protocol() and summarize work
after a fresh clone. The 102 P2r reference artifacts (1.4 GB of particle
npz) are not in git; they are only checked by posterior/train stages.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.
Main S1 runs are still training at this commit; results follow.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
23
AGENTS.md
23
AGENTS.md
@@ -106,6 +106,12 @@ Read first: `docs/plan.md` (plan, gates, decisions; §6 roadmap, §10 forbidden
|
||||
`.gitignore`, and the 29/10 paper/docs edits. Run logs `logs/*.out` stay
|
||||
untracked, as before (`docs/plan.md` §12 item 25).
|
||||
|
||||
- **P6 (level-B benchmark) started early on 29/10/2026** (`docs/plan.md` §12 item 26; uncommitted). Subagents: Fable for reasoning-heavy work, Opus for routine work.
|
||||
- p6-gen done: `misspec=` in `ml_porosity/data/synth_d2.py` (rock physics, wavelet, drift); `misspec=None` reproduces the P2r fingerprints bit for bit (`tests/test_d2_misspec.py`); presets in `configs/d2_synth_bench.yaml` are still PLACEHOLDER; QC in `scripts/33_bench_generator_qc.py`, notes in `docs/research/bench-generator.md`. The uniform rock-physics error is absorbed by the profiled-α likelihood (control only).
|
||||
- T2 done (exploratory; declared and hashed before computing; results `docs/research/t2-results.md`, `outputs/t2/summary.md`). B3d-Sa's label error is Berkson at c = 1, so 1/B_b applies and the H2b gain does not exceed the population correction; a GP-noise bank with the posterior's mean and covariance gets most of the c = 1 gain (label augmentation); implicit re-registration is real (8/8 wide cells); no evidence for the multimodal mechanism; about a third of the PM–Oracle gap is training length. Never use T2 to reselect P2r budgets.
|
||||
- Runner built (`ml_porosity/benchmark/`, `scripts/34_run_bench.py`, `35_bench_calibration.py`, `scripts/run_bench.sh`; design `docs/research/bench-protocol.md`); a P2r cell reproduces bit for bit through it. S2 levels chosen on dev 902–905. `configs/protocol_bench.yaml` is **locked** (29/10 14:39 UTC; sha256 aa763f0a…; TCN budgets 125 from dev; L1 levels above the declared band are disclosed). **Main runs started 29/10 14:43 UTC; all four drivers were SIGTERMed at 15:27 when the agent session ended** (setsid nohup is not enough). Relaunched in the user's tmux server (15:41 on cuda:0; resized at 16:07 UTC when the other project released both GPUs): `p6_s2` (S2, cuda:1, 6 workers), `p6_s1a` (S1 R10/Rm5/R0, cuda:0, 5 workers), `p6_s1b` (S1 R0h/R10tb, cuda:1, 2 workers), `p6_s348` (S3+S4+S8 train, cuda:0, 4 workers); logs `logs/bench_{s2_cuda1,s1a_cuda0,s1b_cuda1,s348_cuda0}.out`. Worker count is bounded by 40 CPUs (2 threads each). Since 16:22 UTC `operations/p6_supervisor.py` (tmux `p6_supervisor`, log `logs/p6_supervisor.out`, state `logs/p6_supervisor_state.json`) checks every 5 min: it relaunches dead unfinished drivers on the card with most free memory (keeping 2.5 GB free, at most 5 restarts each) and gives the workers of a finished driver to the one with most jobs left (21 workers total since 22:26 UTC, when S1 group B was boosted from 2 to 6 workers as the critical path). To change drivers by hand, stop the supervisor first and keep its state file consistent. The GPU co-tenant is the user's own `vinhnt` job (about 80 GB per card at 16:20 UTC); never touch it. Never run two drivers over the same study/regimes (the runner does not claim jobs). Drivers resume by fingerprint: restart a stopped driver with the same command; never edit locked code or inputs. New code files break the F3/Volve code-hash checks of the working tree; acceptable because P3/P4 are never rerun.
|
||||
- Another project held about 125–142 GB on each H200 from about 13:00 to 16:00 UTC on 29/10 and released it by 16:06; if it returns, keep at least 2.5 GB free per card (about 1.56 GB per SMC worker, 0.7 GB per training worker).
|
||||
|
||||
## Next
|
||||
|
||||
Schedule: `docs/plan.md` §6.1 (level B, 29/10 → 14/11/2026). Cut-scope order
|
||||
@@ -115,18 +121,7 @@ if late is given there; never cut thresholds.
|
||||
Add the F3 and Volve dataset citations to `paper/refs.bib`. The length pass
|
||||
for the venue was dropped by the user on 29/10/2026 (plan §12 item 25): do
|
||||
not schedule it. The rest of these two days is buffer.
|
||||
2. **T2 mechanism study (1/11), exploratory:** declare
|
||||
`docs/research/t2-mechanism.md` before running. The question is now
|
||||
whether any bank gain remains beyond the population correction of the
|
||||
Berkson structure. Five tests, as in the Sec. 6.4 todoblock: (i)
|
||||
responsibility-weighted warp error vs. mean-warp error; (ii) random GP-noise
|
||||
bank control; (iii) multimodal-cell split; (iv) Berkson-vs-classical
|
||||
covariance test for the bulk offset of B3d-Sa and B3c-R, which decides which
|
||||
bound applies; (v) B3d-Sa retrained at the Oracle's 500 iterations. The
|
||||
declaration must disclose what was already inspected post hoc on 29/10
|
||||
(`outputs/p2r/posthoc/`): the Oracle/B3d-Sa and M2-Sa/B3d-Sa ratios and
|
||||
every bound, (a), (b), b60 and cross-spectral, at σ_post and at the warp
|
||||
error.
|
||||
2. **T2 mechanism study: done on 29/10/2026** (see Status). Write the paper's Sec. 6.4 todoblock from `docs/research/t2-results.md`.
|
||||
3. **protocol_bench (2–3/11):** add misspecification parameters to
|
||||
`ml_porosity/data/synth_d2.py` without changing the default path (P2r must
|
||||
still reproduce); dev on new realizations 902–905 only; lock
|
||||
@@ -135,7 +130,7 @@ if late is given there; never cut thresholds.
|
||||
misspec axes (R10, Rm5; c = 1; N ∈ {4, 16}; Oracle, B3c-R, B3d-Sa, M2-Sa),
|
||||
S3 (B4 under the SMC posterior), S4 (second backbone), S8 (controlled
|
||||
cycle-skip regime). Realizations 8–15 for all main cells.
|
||||
4. **Runs (4–7/11)** on both GPUs, detached with `setsid nohup`, via a
|
||||
4. **Runs (4–7/11)** on both GPUs, detached in tmux, via a
|
||||
`scripts/run_bench.sh` driver with runlog. Report results as they come out.
|
||||
5. **S7 packaging (8–10/11):** one command to generate, one to score, reference
|
||||
tables, README, hashes, Zenodo deposit; then rewrite the results sections.
|
||||
@@ -153,7 +148,7 @@ if late is given there; never cut thresholds.
|
||||
- **Decisions:** decide from evidence and proceed. Do not block on supervisor (GVHD) sign-off.
|
||||
- **Keep docs in sync (every task):** whenever you change anything (a run starts, finishes, fails or is stopped; a result, decision, deadline, protocol, script or file is added or changed), update in the same turn every file that states it: `report.html` (task status and notes, result cards, FINDS, DECISIONS, LOG), `docs/plan.md` (§0, §6 roadmap, §12 decision log), `AGENTS.md` (Status, Next), and where relevant `README.md` (scripts, run commands), `paper/README.md` (number sources), `docs/technical_overview.md` and `docs/research/*.md`. Before ending the turn, grep these files for older statements about the same item (for example "running", old counts or dates) and correct them, so no two files disagree. After editing `report.html`, check that its data block still parses (balanced brackets and quotes).
|
||||
- **GPU (shared server):** choose cuda:0 or cuda:1 by free memory and load. Never touch other users' jobs. Set `OMP_NUM_THREADS`, `MKL_NUM_THREADS` and `OPENBLAS_NUM_THREADS` explicitly when running by hand (the machine default is 40).
|
||||
- **Long runs:** detach multi-hour runs with `setsid nohup ... &` so they survive the agent session. Wrap runs with `scripts/runlog.sh` or the `run_p*.sh` drivers. Scripts 11/14/15 resume by skipping finished cells.
|
||||
- **Long runs:** start multi-hour runs inside the user's tmux server (`tmux new-session -d -s <name> -c <repo> "<cmd> >> logs/<name>.out 2>&1"`) so they survive the agent session; on 29/10 `setsid nohup` runs were killed when the session ended. Wrap runs with `scripts/runlog.sh` or the `run_p*.sh` drivers. Scripts 11/14/15 resume by skipping finished cells.
|
||||
- `code_thesis/` is the unchanged thesis-code archive (renamed from `test 2/`): do not modify its contents.
|
||||
- **User constraint:** do not rerun `04_wavelet_tie.py` or
|
||||
`09_fit_warp_prior_f3.py`, or overwrite their historical artifacts. P3 uses
|
||||
|
||||
10
README.md
10
README.md
@@ -63,6 +63,12 @@ scripts/run_p2r_dev.sh # chuẩn bị P2r (chạy lại P2) trên dev 900/9
|
||||
scripts/run_p2r_main.sh # lưới chính P2r trên realization 8–15
|
||||
scripts/run_p4.sh # P4 Volve: register, train, summarize nhánh σ_a chính (DEVICE mặc định cuda:1)
|
||||
ARMS=sensitivity scripts/run_p4.sh register train # nhánh σ_a = 3,5 / 14 ms; sau đó ARMS=all scripts/run_p4.sh summarize
|
||||
scripts/run_bench.sh lock # P6 protocol_bench: khoá lần đầu (sau khi duyệt bản nháp)
|
||||
STUDIES="S1" DEVICE=cuda:0 WORKERS=4 scripts/run_bench.sh posterior train # S1 trên cuda:0; các study khác tương tự (STUDIES, REGIMES, PRESETS, RIDS, DEV=1)
|
||||
scripts/run_bench.sh summarize | status | repro # tổng hợp theo luật đã khai báo; tiến độ; ô tái lập P2r
|
||||
# Run dài: chạy trong tmux server của người dùng, ví dụ tmux new-session -d -s p6_s2 -c $PWD "env STUDIES=S2 DEVICE=cuda:0 WORKERS=2 MEM_GB=2 scripts/run_bench.sh posterior train >> logs/bench_s2_cuda0.out 2>&1"
|
||||
# (setsid nohup bị dừng khi phiên agent kết thúc, 29/10). operations/p6_s1_watcher.sh khởi động S1 khi GPU có chỗ trống (đã dùng 15:43–16:06 UTC 29/10, rồi bỏ khi GPU trống).
|
||||
# operations/p6_supervisor.py (tmux p6_supervisor): mỗi 5 phút chạy lại driver P6 chết và dồn worker khi một study xong; log logs/p6_supervisor.out.
|
||||
```
|
||||
|
||||
Log và runtime: mỗi lần chạy `run_p*.sh` tạo `logs/runs/<YYYYmmdd-HHMMSS>_p*/`, mỗi bước là một thư mục con có `log.txt` (stdout + stderr, cả của worker, đầu dòng có thời gian đã trôi) và `meta.json` (lệnh, git commit + hash mã nguồn, biến luồng, thiết bị, wall/CPU time, RSS và VRAM đỉnh, mã thoát). Mỗi bước thêm một dòng vào `logs/index.csv`. Chạy lẻ một script thì bọc bằng `scripts/runlog.sh`:
|
||||
@@ -113,5 +119,9 @@ Biến môi trường máy đặt sẵn `OMP_NUM_THREADS=40` (cả MKL, OpenBLAS
|
||||
| `python -P scripts/29_teapot_pilot.py` | Pilot P-a Teapot (Deviation 2): hình học, độ phủ horizon, σ̂_knot trên giếng dev (inline ≤ 200), không đọc porosity → `outputs/teapot/pilot_pa/` |
|
||||
| `scripts/30_t4_coverage.py` | T4 post hoc, mô tả: tỉ số phân tán ξ (cột `kappa`), coverage90 và phần do số vòng lặp của các ensemble 5 seed, từ `outputs/p2r/train/*/cells/*.npz` và dev P2 → `outputs/t4/` |
|
||||
| `scripts/31_p2r_posthoc.py` | Post hoc H2b, đọc `outputs/p2r/summary/` và dự đoán Oracle trong `outputs/p2r/train/<regime>/cells/*.npz` (khoảng 6 phút): tỉ số Oracle / B3d-Sa / M2-Sa, phần khoảng cách đã đóng; cận 1/B cho cấu trúc (a) classical (đã đăng ký) và (b) Berkson (thêm biến thể giữ hệ số ở 60 Hz và biến thể phổ chéo), tại σ_post và tại sai số warp; cờ vượt mép lưới B → `outputs/p2r/posthoc/{bound.csv, blur_ab.csv, meta.json}` |
|
||||
| `scripts/32_t2_mechanism.py` | T2 (P6, exploratory, khai báo trước ở `docs/research/t2-mechanism.md`): năm phép kiểm cơ chế của lợi ích bank trên realization 8–15 của P2r; `--tests i ii v` huấn luyện lại (GPU), `--tests iii iv` đọc particle (CPU, khoảng 7 phút); tự kiểm tái lập so với `outputs/p2r/train/` → `outputs/t2/`. Kết quả: `docs/research/t2-results.md` |
|
||||
| `scripts/33_bench_generator_qc.py` | QC bộ sinh cho S2 (P6, `p6-gen`; CPU, khoảng 1 phút): với realization dev 902 và từng preset misspec trong `configs/d2_synth_bench.yaml`, đo thay đổi AI thật, wavelet thật (pha hằng khớp nhất, tần số đỉnh, băng 90 %), warp thật (RMS, bước nhảy, jitter), sai số mô hình mà registration thấy tại warp thật (wavelet F3 danh nghĩa và thành viên tốt nhất trong họ wavelet thống kê + pha hằng, quy ra dB), tie chỉ anchor (Laplace, N = 4); `--sweep` quét từng núm đơn; `--smc --device cuda:1` (hoặc `cpu`) chạy registration + SMC tie posterior như P2r cho từng preset ở R10/Rm5, N = 4, nối tiếp ô đã xong → `outputs/bench/dev/{generator_qc.json, generator_qc.png, generator_sweep.json, smc_qc_rid902.json}`. Thiết kế: `docs/research/bench-generator.md` |
|
||||
| `scripts/34_run_bench.py <stage…> [--studies S1 S2 S3 S4 S8] [--device] [--workers] [--gpu-mem-gb] [--dev --rids 902…]` | Runner của `configs/protocol_bench.yaml` (P6, mức B): `lock` (khoá: `.sha256` + `.lock.json` gồm code, môi trường, input, artifact P2r tham chiếu, fingerprint bộ sinh danh nghĩa), `posterior` (SMC như scripts/14, nhánh estR, P = 1024, lưu hạt γ = 1/κ), `train` (như scripts/15 + B4a–d, nhánh S8 hai mode, backbone TCN), `summarize` (luật đã khai báo trước → `outputs/bench/summary/`), `repro` (ô tái lập P2r → `outputs/bench/repro/comparison.json`), `dev-budgets` (ngân sách TCN trên dev). Realization 8–15 chỉ chạy sau khi khoá; `--dev` chỉ nhận 900–905 và ghi vào `outputs/bench/dev/`. Resume theo fingerprint + checksum. Mã: `ml_porosity/benchmark/` |
|
||||
| `scripts/35_bench_calibration.py [--rids 902 903 904 905]` | Bảng hiệu chuẩn mức S2 (dev): gộp `outputs/bench/dev/smc_qc_rid*.json` (scripts/33 `--smc`) thành `calibration.{csv,md}`: sai số mô hình trong họ so với nhiễu regime, SMC warp RMSE / coverage90 / σ_post / overconfidence, phase_R, B3c, theo preset × regime |
|
||||
|
||||
`code_thesis/` là bản lưu trữ code luận văn. Giữ nguyên nội dung để đối chiếu: các script này còn đường dẫn máy cũ và ghi vào `outputs/`, nên cần một bản sao đã điều chỉnh đường dẫn nếu muốn chạy lại. Kiểm tra bộ artifact hiện có bằng `python scripts/00_data_manifest.py --dataset thesis --check`.
|
||||
|
||||
107
configs/d2_synth_bench.yaml
Normal file
107
configs/d2_synth_bench.yaml
Normal file
@@ -0,0 +1,107 @@
|
||||
# D2 for protocol_bench (phase P6, S1/S2/S3/S4/S8): GENERATOR IDENTICAL to configs/d2_synth_p2r.yaml and therefore to
|
||||
# configs/d2_synth.yaml (protocol_p2). This file differs only in comments, the `regimes` block (copied from p2r) and
|
||||
# the `misspec_presets` block at the end; every key read by ml_porosity/data/synth_d2.py keeps its value, so the same
|
||||
# realization yields the same data when no preset is applied (tests/test_d2_misspec.py). Do not edit the locked
|
||||
# configs/d2_synth.yaml or configs/d2_synth_p2r.yaml.
|
||||
horizons: [Shallow, FS8, FS7, Truncation, MFS4] # 5 horizons covering ≥ 95% of the survey (Top-Foresets 74%, FS6 49%)
|
||||
horizon_cache: outputs/d2/horizon_grid.npz
|
||||
min_gap_ms: 8 # drop bins where two consecutive horizons are < 8 ms apart or out of order
|
||||
sub_unit_ms: 60 # nominal sub-unit thickness (unit boundaries = markers/anchors)
|
||||
model_t_ms: [-300, 2400] # earth-model domain in true time; wide enough that t(τ) of the 100–1650 ms log stays inside at drift ×2
|
||||
log_tau_ms: [100, 1650] # log domain in sonic time τ
|
||||
fine_dt_ms: 0.5
|
||||
warp_dtau_ms: 4.0 # grid of g
|
||||
dt_ms: 4
|
||||
ext_window_ms: [400, 1300] # seismic + anchors (as in F3)
|
||||
main_window_ms: [600, 1100] # input/labels/scoring (as in F3)
|
||||
patch_radius: 1
|
||||
|
||||
wells:
|
||||
n_test: 8
|
||||
n_train_pool: 16 # N_train ∈ {2, 4, 8, 16}, nested draws from the pool
|
||||
min_dist_test_m: 1000 # test wells ≥ 1 km from every other well (spatial block split)
|
||||
min_dist_train_m: 500
|
||||
|
||||
property:
|
||||
phi0: 0.32
|
||||
phi0_sd: 0.01
|
||||
slope_per_100ms: -0.008
|
||||
unit_offset_sd: 0.02
|
||||
unit_lateral_sd: 0.01
|
||||
grf: # sum of OU processes in stratigraphic coordinates
|
||||
- {sd: 0.010, ell_ms: 10.0}
|
||||
- {sd: 0.006, ell_ms: 2.0}
|
||||
clip: [0.05, 0.45]
|
||||
|
||||
wavelet: statistical # outputs/wavelets.npz (zero phase, 128 ms) from scripts/04
|
||||
snr_db: 10 # generator default; the protocol takes SNR from the regimes below
|
||||
|
||||
drift:
|
||||
prior_json: outputs/p2/warp_prior_f3.json # Matérn-3/2 fit on F3 anchors (scripts/09)
|
||||
factors: [0, 0.5, 1, 2]
|
||||
|
||||
anchors:
|
||||
density: full
|
||||
sigma_a_ms: 7.0 # robust σ (MAD) of marker–horizon differences at the 4 F3 wells (18 pairs): 6.9 ms
|
||||
|
||||
regimes: # identical to configs/d2_synth_p2r.yaml
|
||||
R10: {snr_db: 10, anchor_density: full} # P2 default; narrow posterior (dev σ_post ≈ 0.85 ms at c = 1)
|
||||
R0: {snr_db: 0, anchor_density: full} # dev σ_post ≈ 1.9 ms at c = 1
|
||||
Rm5: {snr_db: -5, anchor_density: full} # close to F3 under the protocol prior (dev σ_post ≈ 3.0 ms, F3 2.5–3.4 ms)
|
||||
R0h: {snr_db: 0, anchor_density: half} # sparse anchors: dev σ_post ≈ 1.8 / 4.5 ms at c = 1 / 2
|
||||
R10tb: {snr_db: 10, anchor_density: topbottom} # top–bottom anchors only: dev σ_post ≈ 2.6 / 11 ms (multimodal, overconfident posterior)
|
||||
|
||||
# S2 misspecification presets (plan §12 item 22, decision 2; docs/research/bench-generator.md; levels fixed on dev
|
||||
# realizations 902–905 on 29/10/2026, docs/research/bench-protocol.md §3). Each preset is a `misspec` argument of
|
||||
# D2Realization (keys and defaults: synth_d2.MISSPEC_DEFAULTS; a `note` key is ignored). Main cells of protocol_bench
|
||||
# S2: rp_L1, rp_L2, wv_L1, wv_L2, wv_Q, dr_L1, dr_L2. The control presets (*_C) document what the registration's model
|
||||
# family absorbs; they are never main cells. The cand_* presets below are the calibration candidates (dev evidence
|
||||
# only; kept so that the calibration is reproducible). Realizations 8–15 were not used to choose any level.
|
||||
misspec_presets:
|
||||
rp_C: # control: uniform coefficient error only. The profiled amplitude α of the tie likelihood
|
||||
note: "control: uniform φ–DT / density coefficient error (plan §5.5 literal axis); absorbed by the profiled amplitude (QC: in-family error 0.073 = nominal)"
|
||||
rock_physics: {dt_slope_factor: 1.15, dt_intercept_factor: 1.15, rho_slope_factor: 1.2}
|
||||
rp_L1: # per-unit intercept scatter (lithology-dependent matrix slowness); uniform factors dropped (invisible)
|
||||
note: "L1: unit_dt_intercept_sd 0.10 (DT_matrix ±18 µs/m per unit; in-family model error 0.39 = 1.2 × R10 noise, 0.22 × Rm5 noise); dev SMC at R10 (rids 903–905, N = 4): warp RMSE ×1.27, cov90 0.85"
|
||||
rock_physics: {unit_dt_intercept_sd: 0.10}
|
||||
rp_L2:
|
||||
note: "L2: unit_dt_intercept_sd 0.15 (±27 µs/m; model error 0.53 = 1.7 × R10 noise, 0.30 × Rm5); dev SMC at R10 (rids 902–905): warp RMSE ×1.66, cov90 0.81. Expected null at Rm5 (model error far below the noise)"
|
||||
rock_physics: {unit_dt_intercept_sd: 0.15}
|
||||
wv_C: # control: constant phase + peak-frequency factor, both inside the registration's family
|
||||
note: "control: constant 45° phase and peak frequency ×1.2: absorbed by the statistical wavelet + constant-phase fit (15° grid)"
|
||||
wavelet: {phase_deg: 45.0, peak_freq_factor: 1.2}
|
||||
wv_L1: # frequency-dependent phase (phase sub-axis), nominal amplitude spectrum
|
||||
note: "L1: minphase_frac 0.5 (half of the minimum-phase spectrum; model error 0.34 = 1.08 × R10 noise); dev SMC at R10 (rids 902–905): warp RMSE ×3.2, cov90 0.11 (overconfident) but still ahead of the point ties (2.1 vs 4.3 ms)"
|
||||
wavelet: {minphase_frac: 0.5}
|
||||
wv_L2:
|
||||
note: "L2: minphase_frac 1.0 (minimum-phase version of the nominal wavelet; model error 0.61 = 1.9 × R10 noise); dev SMC at R10 (rids 902–905): warp RMSE ×5.9, cov90 0.03, ahead of B3c in 3/4 rids only"
|
||||
wavelet: {minphase_frac: 1.0}
|
||||
wv_Q: # bandwidth sub-axis: time-variant constant-Q attenuation (stationary statistical wavelet is wrong at both ends of the window)
|
||||
note: "bandwidth cell (single level): Q 80 from t_ref = 400 ms with Futterman dispersion (peak 59 → 32 Hz over 600–1100 ms; model error 0.45 = 1.4 × R10 noise); dev SMC at R10 (rids 902–905): warp RMSE ×1.57, cov90 0.84, σ_post ×1.8 (the posterior widens rather than collapses)"
|
||||
wavelet: {Q: 80.0, Q_t_ref_ms: 400.0, Q_dispersion: true}
|
||||
dr_L1: # mechanism 1: the truth is drawn from scaled hyperparameters (σ_b 58 ms > the registration's fixed 50 ms; rougher g); partly absorbed by MAP-II
|
||||
note: "L1 (hyperparameter mechanism): sigma_b ×3, sigma_g ×1.5, ell ×0.5 (same z_g, z_b); dev SMC at R10 (rids 902–905): warp RMSE ×2.2 (1.1–2.1 ms), cov90 0.75"
|
||||
drift: {sigma_b_factor: 3.0, sigma_g_factor: 1.5, ell_factor: 0.5}
|
||||
dr_L2: # mechanism 2: components outside the GP family (step at Truncation, short-correlation jitter); the step does not scale with c
|
||||
note: "L2 (structural mechanism): step 8 ms just below Truncation (12 ms anomaly) plus Matérn-3/2 jitter sd 1 ms, ell 8 ms; dev SMC at R10 (rids 902–905): warp RMSE ×3.3 (1.3–4.1 ms), cov90 0.61"
|
||||
drift: {step_ms: 8.0, step_width_ms: 12.0, step_horizon: Truncation, jitter_sd_ms: 1.0, jitter_ell_ms: 8.0}
|
||||
# --- dev calibration candidates (29/10/2026, phase 2 of P6): single-knob and combined settings whose SMC-stage
|
||||
# diagnostics on dev realizations 902–905 (scripts/33 --smc, N = 4, c = 1, R10 and Rm5) choose the L1/L2 levels
|
||||
# above. They are never main cells. Rock physics: per-unit intercept scatter only (the uniform factors are
|
||||
# invariant under the profiled-amplitude likelihood, docs/research/bench-generator.md §2, and stay in rp_C).
|
||||
cand_rp_a: {note: "candidate: unit_dt_intercept_sd 0.05 (in-family model error 0.217, 13.3 dB)", rock_physics: {unit_dt_intercept_sd: 0.05}}
|
||||
cand_rp_b: {note: "candidate: unit_dt_intercept_sd 0.10 (0.391, 8.2 dB)", rock_physics: {unit_dt_intercept_sd: 0.10}}
|
||||
cand_rp_c: {note: "candidate: unit_dt_intercept_sd 0.15 (0.531, 5.5 dB)", rock_physics: {unit_dt_intercept_sd: 0.15}}
|
||||
cand_wv_a: {note: "candidate: minphase_frac 0.5 (0.342, 9.3 dB)", wavelet: {minphase_frac: 0.5}}
|
||||
cand_wv_b: {note: "candidate: Q 160 from 400 ms with dispersion (0.259, 11.7 dB)", wavelet: {Q: 160.0, Q_t_ref_ms: 400.0, Q_dispersion: true}}
|
||||
cand_wv_c: {note: "candidate: minphase_frac 1.0 (0.609, 4.3 dB) = wv_L1 placeholder", wavelet: {minphase_frac: 1.0}}
|
||||
cand_wv_d: {note: "candidate: Q 80 (0.445, 7.0 dB)", wavelet: {Q: 80.0, Q_t_ref_ms: 400.0, Q_dispersion: true}}
|
||||
cand_wv_e: {note: "candidate: minphase_frac 0.5 + Q 160", wavelet: {minphase_frac: 0.5, Q: 160.0, Q_t_ref_ms: 400.0, Q_dispersion: true}}
|
||||
cand_dr_h: {note: "candidate: hyperparameter misspecification only = dr_L1 placeholder", drift: {sigma_b_factor: 3.0, sigma_g_factor: 1.5, ell_factor: 0.5}}
|
||||
cand_dr_s: {note: "candidate: structural components only (step 8 ms, jitter 1 ms) = dr_L2 placeholder", drift: {step_ms: 8.0, step_width_ms: 12.0, step_horizon: Truncation, jitter_sd_ms: 1.0, jitter_ell_ms: 8.0}}
|
||||
cand_dr_hs: {note: "candidate: hyperparameters + structural components", drift: {sigma_b_factor: 3.0, sigma_g_factor: 1.5, ell_factor: 0.5, step_ms: 8.0, step_width_ms: 12.0, step_horizon: Truncation, jitter_sd_ms: 1.0, jitter_ell_ms: 8.0}}
|
||||
cand_dr_s2: {note: "candidate: stronger structural components (step 16 ms, jitter 2 ms)", drift: {step_ms: 16.0, step_width_ms: 12.0, step_horizon: Truncation, jitter_sd_ms: 2.0, jitter_ell_ms: 8.0}}
|
||||
cand_rp_d: {note: "candidate: unit_dt_intercept_sd 0.075 (in-family model error ≈ 0.30, ≈ 0.95 × R10 noise)", rock_physics: {unit_dt_intercept_sd: 0.075}}
|
||||
cand_wv_f: {note: "candidate: minphase_frac 0.25 (0.197, 14.1 dB)", wavelet: {minphase_frac: 0.25}}
|
||||
cand_wv_g: {note: "candidate: Q 40 (0.652, 3.7 dB)", wavelet: {Q: 40.0, Q_t_ref_ms: 400.0, Q_dispersion: true}}
|
||||
cand_wv_h: {note: "candidate: minphase_frac 0.5 + Q 80 (phase and bandwidth)", wavelet: {minphase_frac: 0.5, Q: 80.0, Q_t_ref_ms: 400.0, Q_dispersion: true}}
|
||||
166
configs/protocol_bench.lock.json
Normal file
166
configs/protocol_bench.lock.json
Normal file
@@ -0,0 +1,166 @@
|
||||
{
|
||||
"protocol_sha256": "aa763f0a4f81125ea8441fdfba4361f68246c7a0be1c36d4bf8de2650a91a4c5",
|
||||
"code_sha256": "5ea2eb17681459ed973217c9d61706a269f1913314fec0848bb2d5c99eb6bbb8",
|
||||
"environment": {
|
||||
"python": "3.13.15",
|
||||
"platform": "Linux",
|
||||
"packages": {
|
||||
"torch": "2.14.0+cu130",
|
||||
"numpy": "2.5.4",
|
||||
"scipy": "1.18.1",
|
||||
"pandas": "3.0.6",
|
||||
"matplotlib": "3.11.2",
|
||||
"segyio": "1.9.14",
|
||||
"lasio": "0.32",
|
||||
"pylops": "2.5.0",
|
||||
"numba": "0.67.0",
|
||||
"scikit-learn": "1.9.1",
|
||||
"PyYAML": "6.0.3",
|
||||
"tabulate": "0.10.0",
|
||||
"psutil": "7.2.2"
|
||||
}
|
||||
},
|
||||
"inputs": {
|
||||
"repo:configs/d2_synth_bench.yaml": "2bfd01c94f169116fb92e7c1ac92db8bbe003973a610c32b2740e864b4c761b2",
|
||||
"repo:configs/protocol_p2.yaml": "0733620042c4ec1b7dce447eef3ec64f915db05acbebbe5b6c977ac42e71a470",
|
||||
"repo:configs/protocol_p2r.yaml": "eb887311f26a7c1c3dc69d9623d0086cfb5ccc79eea9e5ef59c723078f49c8aa",
|
||||
"outputs:p2/warp_prior_f3.json": "55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27",
|
||||
"outputs:wavelets.npz": "b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64",
|
||||
"outputs:d2/horizon_grid.npz": "70e3321fa9f8fe2a1301877fb34386a64bf29eaa4f6948007e18874678e92b1e",
|
||||
"outputs:p2/diag/train/budgets.json": "815c6f7abc3d961255feb79bbed57a3e326cbc24cec11bbd97f455f0356e28c5",
|
||||
"repo:tests/data/d2_fingerprints.json": "86cbd6dd49044c1288ec6b649a2d688bf4121280d5cc3dca9b45109523bd6fc1"
|
||||
},
|
||||
"p2r_reference": {
|
||||
"outputs:p2r/summary/sigma_post.csv": "81993c37d434bdb4474df6ee1980234e705157b4564b9db3eea8a4353d93eeaa",
|
||||
"outputs:p2r/train/R10/runs.csv": "68a9b790b0697c7122ced975b210e41d0f1437a15b4f1924e74bc5717ae0f728",
|
||||
"outputs:p2r/train/R0/runs.csv": "0e5545450c25befe71684592b51dcf42d988b049f422542893493e72bd25fbd5",
|
||||
"outputs:p2r/train/Rm5/runs.csv": "3f34805b565effe8430d06ba25db4b8cea53d21df1edc5187b41c6d04dc5d8cc",
|
||||
"outputs:p2r/train/R0h/runs.csv": "2fb21ddae78066c81ba530632dfd21c237d505b317b0da2322242360b85ebc5e",
|
||||
"outputs:p2r/train/R10tb/runs.csv": "155394bacfa60ef7c8adc93f690fd1fcfa7580e6c230add1712bc1cbf4a18d47",
|
||||
"outputs:p2r/posterior/R10/r8_c1_n4_s0_particles.npz": "2221b21a178bef237dcd7fac9134a892dd49c5229e07f61279dff40d9dd35498",
|
||||
"outputs:p2r/posterior/R10/r8_c1_n4_s0_phase.json": "af449f4626f26c27410d953d7ac25b99dfddc6247b58ec756479728779b937ed",
|
||||
"outputs:p2r/posterior/R10/r9_c1_n4_s0_particles.npz": "8319ae0973d6939991f59298373a1021ecde9ff36bae4e0c9e94182be2c49edd",
|
||||
"outputs:p2r/posterior/R10/r9_c1_n4_s0_phase.json": "109a2edf27f883f1ed49b375eb6bb88910f9d688d0acf1d6c8557692fbb494bb",
|
||||
"outputs:p2r/posterior/R10/r10_c1_n4_s0_particles.npz": "f75919b16fecfae9571621205ca46abaefcd89faad41181cfa8dfaf86eee104c",
|
||||
"outputs:p2r/posterior/R10/r10_c1_n4_s0_phase.json": "dd308be9dbbbb0dab231f1568331c95d135fe9ed1cfe791981ae7f27521e1cfa",
|
||||
"outputs:p2r/posterior/R10/r11_c1_n4_s0_particles.npz": "82746d118a3ae765c2f6ca2c598c554427a210098e15bbe6112ab669fac078ea",
|
||||
"outputs:p2r/posterior/R10/r11_c1_n4_s0_phase.json": "589b6a9a0759f78c0deec2570cfcf1d9e999d606496f63d274a299406639a2a1",
|
||||
"outputs:p2r/posterior/R10/r12_c1_n4_s0_particles.npz": "18b5704ef49a6be85718be3afd36adbb1b3b05ac001a4d042825f82e7390b8b3",
|
||||
"outputs:p2r/posterior/R10/r12_c1_n4_s0_phase.json": "edcb9c55168fd4148ca140b8152114c5ed6518de2408a4b5b766d7afe700618a",
|
||||
"outputs:p2r/posterior/R10/r13_c1_n4_s0_particles.npz": "c1ffbe821f0f592362bbd07e8395a1573ba6984c9fb2130a8ddd8fedb0439f38",
|
||||
"outputs:p2r/posterior/R10/r13_c1_n4_s0_phase.json": "9d270dcac190498b135849424e933586789fab5e54f569d1f6c5d60ceca6ccd5",
|
||||
"outputs:p2r/posterior/R10/r14_c1_n4_s0_particles.npz": "566d13c7f2fc5db635012b954adf4c07a2f826b40bbc52de6d237e8cd717870c",
|
||||
"outputs:p2r/posterior/R10/r14_c1_n4_s0_phase.json": "17fa46ad5f285dc058fcb2cec4dc771fc9b808b356ba1778dcee6db92dbf3540",
|
||||
"outputs:p2r/posterior/R10/r15_c1_n4_s0_particles.npz": "16cd72a0541e6a739548cdb2762b4a31c17732785aa976faf36e895b93de5335",
|
||||
"outputs:p2r/posterior/R10/r15_c1_n4_s0_phase.json": "2cb76771811b2b44f1d8a45798bae3d6f15b4e4e0345212147afda5859d41705",
|
||||
"outputs:p2r/posterior/R10/r8_c1_n16_s0_particles.npz": "6d117e2cafe77f1e40250465dfabd28caefef97ef547e648877ef5d4dc0fc621",
|
||||
"outputs:p2r/posterior/R10/r8_c1_n16_s0_phase.json": "473edfa3d0d196a70aef8bd21b30c8781e3200d5e98b6d5f4805446f61e604cf",
|
||||
"outputs:p2r/posterior/R10/r9_c1_n16_s0_particles.npz": "0b124530110ace9bf02c81a94bb1a90a1205ee99817dcbf30689e7bbb98b7fc9",
|
||||
"outputs:p2r/posterior/R10/r9_c1_n16_s0_phase.json": "b3bac0cbf6c7fc360b3bcc4e9594a7896f5fdf2d9deda17df3d799223b7af0fd",
|
||||
"outputs:p2r/posterior/R10/r10_c1_n16_s0_particles.npz": "37352c3c778105c98554d0aba982f91f02876b5b6efa5572745aa71d54194776",
|
||||
"outputs:p2r/posterior/R10/r10_c1_n16_s0_phase.json": "93bcd2dfc6b050f9ef3195ca4747eb7c33b3629916f0629e44b6c93288fbe7c8",
|
||||
"outputs:p2r/posterior/R10/r11_c1_n16_s0_particles.npz": "8cfd481f0d264c4d522e23b3ac1a3583a447167b87418734ea7733cc3c0063c9",
|
||||
"outputs:p2r/posterior/R10/r11_c1_n16_s0_phase.json": "9fd2c2cf41c7c067c28ba66b1a6669069c74d5db179acc4d9714dbc8261c0518",
|
||||
"outputs:p2r/posterior/R10/r12_c1_n16_s0_particles.npz": "4300b1107779f1a88a79fca6c10a845daddd2661575efd74b24ac73bbc8ade9a",
|
||||
"outputs:p2r/posterior/R10/r12_c1_n16_s0_phase.json": "3036584163a098446cc5eb93b1f514248c07a467e0d0b554a39f2b8a98ec778b",
|
||||
"outputs:p2r/posterior/R10/r13_c1_n16_s0_particles.npz": "b537f59b93b49081901cd9eccb623a2ae6f9743ead46bdd87145218f1a33cf80",
|
||||
"outputs:p2r/posterior/R10/r13_c1_n16_s0_phase.json": "d951a6ac2d2a9b35eb157a086c930a2c0f7be9cde179269a61c2641a6078b4d6",
|
||||
"outputs:p2r/posterior/R10/r14_c1_n16_s0_particles.npz": "244cc82ce07bdb01c3f197f62c92c6cc34509aa5d9e477178d678618841eed57",
|
||||
"outputs:p2r/posterior/R10/r14_c1_n16_s0_phase.json": "230a42baf6e4865eac18d4851f3f3ad47c0200a73d6706a3191e6dc2a7491224",
|
||||
"outputs:p2r/posterior/R10/r15_c1_n16_s0_particles.npz": "3bdb8ed21d9c3cbd4b9e05bd9b391c2da8b3c8a27fd4f1dac9e89967b1f3300a",
|
||||
"outputs:p2r/posterior/R10/r15_c1_n16_s0_phase.json": "36b79c5cc8d6f36557cfbfc682f7f87fd94df592594f8e95d71d663098358959",
|
||||
"outputs:p2r/posterior/Rm5/r8_c1_n4_s0_particles.npz": "330f656862017097733b1abb4e774a927f396e9f984bab44c9b53719b125fc93",
|
||||
"outputs:p2r/posterior/Rm5/r8_c1_n4_s0_phase.json": "8f1a5279db5042add8efb12cd5a425b8dc2af195a66f530044232f947ccae63c",
|
||||
"outputs:p2r/posterior/Rm5/r9_c1_n4_s0_particles.npz": "2689b63440065bbf7820f6d3a77d9d6469494cdfc9346b19939c231a264a2d8a",
|
||||
"outputs:p2r/posterior/Rm5/r9_c1_n4_s0_phase.json": "c4ad961246b42c30e1cdb4051bf75808726c40b584a7b83c4c936ece20c6c78b",
|
||||
"outputs:p2r/posterior/Rm5/r10_c1_n4_s0_particles.npz": "226c494a7ac1b236bdd6ecd23940f809087501a42e626be77f7891136f0ba0b8",
|
||||
"outputs:p2r/posterior/Rm5/r10_c1_n4_s0_phase.json": "72e053d1a113f95d417582fba0bd4fca11fafe102f35df46e35a2731cbb5a1c6",
|
||||
"outputs:p2r/posterior/Rm5/r11_c1_n4_s0_particles.npz": "9155fd1537d5b01ffa02baf7d48f5d7d2f36afc739ffe10c08062514d857b470",
|
||||
"outputs:p2r/posterior/Rm5/r11_c1_n4_s0_phase.json": "a171d8f099c31a0ef9ff7c04ba50ce0d8015b3165c5cb3f0b63b678a2c75557b",
|
||||
"outputs:p2r/posterior/Rm5/r12_c1_n4_s0_particles.npz": "46756fc65b51232644bffbe7e990549db9c26b5c995865c394d01ecfa448611c",
|
||||
"outputs:p2r/posterior/Rm5/r12_c1_n4_s0_phase.json": "c67ce4c8dace40a1cb1ebf49c84f8dd7815603397ccb69cd21ea4ac8764fd446",
|
||||
"outputs:p2r/posterior/Rm5/r13_c1_n4_s0_particles.npz": "5bb923440ac215439b360cebc2a004c575db69b36a548037b3be63a8992f1c91",
|
||||
"outputs:p2r/posterior/Rm5/r13_c1_n4_s0_phase.json": "c9715ff84285491c9dfd7b1f698f39571d5b2253584ec68014f83abd971c3f5f",
|
||||
"outputs:p2r/posterior/Rm5/r14_c1_n4_s0_particles.npz": "4016b3c2057790c3e40038c0f08c6e9893c144ba7270c493039046a5bbf4de87",
|
||||
"outputs:p2r/posterior/Rm5/r14_c1_n4_s0_phase.json": "c19eaa7ca8215602a325381b85abdaf715eae693072702f085674858f2457eba",
|
||||
"outputs:p2r/posterior/Rm5/r15_c1_n4_s0_particles.npz": "dfb5a06a345b8ffb4ee9998647c5d53e7e151b894048d4ff0a0dfd553ae36dd0",
|
||||
"outputs:p2r/posterior/Rm5/r15_c1_n4_s0_phase.json": "96401dc3d10f6f187380fdebca6a22e763fe23e742ea0fdc5f53fca1484c798e",
|
||||
"outputs:p2r/posterior/Rm5/r8_c1_n16_s0_particles.npz": "2c0480f2c14111663c5fbbddc6a84f65ba809e818be1247400c054680e6ec509",
|
||||
"outputs:p2r/posterior/Rm5/r8_c1_n16_s0_phase.json": "cc11f96033ba8748fe72eb858bd679e5a067e1a7709843fad9298d9d5efd46f0",
|
||||
"outputs:p2r/posterior/Rm5/r9_c1_n16_s0_particles.npz": "33bfe288e207f0b409885b486df05b182a99ea23c15a134a85515451434f99f8",
|
||||
"outputs:p2r/posterior/Rm5/r9_c1_n16_s0_phase.json": "f7d03ffd0d3d15a021c40e0b643981b304c33d72ca3c608c7e31f41b733c1451",
|
||||
"outputs:p2r/posterior/Rm5/r10_c1_n16_s0_particles.npz": "dd3c1634e2e2c72633e22992c5a993825d501821f1ed8f701178add03e4836fb",
|
||||
"outputs:p2r/posterior/Rm5/r10_c1_n16_s0_phase.json": "81d651de74dfdac67e9942f46bd89dd1473a2aee3d24900ec35c848f5d86bd93",
|
||||
"outputs:p2r/posterior/Rm5/r11_c1_n16_s0_particles.npz": "56c3aeed9e9b3fcf9b67131ec5300a9f75b2fc06578e04a955ba290ed29b5a14",
|
||||
"outputs:p2r/posterior/Rm5/r11_c1_n16_s0_phase.json": "43b421054e5d4e563fcb1237bac5ac57c7487ad4f91499f9cd81a8048ec973a4",
|
||||
"outputs:p2r/posterior/Rm5/r12_c1_n16_s0_particles.npz": "413187f2c4ffa087a494cde19acef2ebdf44b0bf6f3d7b2cfbbfe94dcb948406",
|
||||
"outputs:p2r/posterior/Rm5/r12_c1_n16_s0_phase.json": "7113f91f5d7ecd6e0b03f1fd2be328be4ba3ff9814d9fbd42a7252fb730ce6f7",
|
||||
"outputs:p2r/posterior/Rm5/r13_c1_n16_s0_particles.npz": "c89c55818d71b90b4afa1e92a447a72e333d365675a6c3142f4a63bf07dd20a0",
|
||||
"outputs:p2r/posterior/Rm5/r13_c1_n16_s0_phase.json": "1d5297b1dc819908fb66a4de4fe5d7749a0fbf82ee4b198b8641d3e24ffbb505",
|
||||
"outputs:p2r/posterior/Rm5/r14_c1_n16_s0_particles.npz": "4b2e17b34e0a34aab2d664349f4a942b7729bc59b4ccdcab06b6aadd73677770",
|
||||
"outputs:p2r/posterior/Rm5/r14_c1_n16_s0_phase.json": "6a96189e555b9c86528eb2a89f4b3ef9250540224a6a7f3bff6f7989fe67041a",
|
||||
"outputs:p2r/posterior/Rm5/r15_c1_n16_s0_particles.npz": "acc9499057c1607afd22d16da9ce4d5fb61bc17c84bdb4384e5d7650a566aa9c",
|
||||
"outputs:p2r/posterior/Rm5/r15_c1_n16_s0_phase.json": "58c3370e34f5555f24270eef395499616eb66ae5369d651291120e27111c0cd3",
|
||||
"outputs:p2r/posterior/R0h/r8_c1_n4_s0_particles.npz": "363b747704ed7af158264d20137522e4d8d5a86cfe570cd3563d63d7d509124c",
|
||||
"outputs:p2r/posterior/R0h/r8_c1_n4_s0_phase.json": "3519c7ceeba60bac013c760f78dd96a4638b403d4980b9111f3e226e130147c0",
|
||||
"outputs:p2r/posterior/R0h/r9_c1_n4_s0_particles.npz": "e0411696908e91b56475ee6d28a8314425941f08eab7d318f92a2127d412476f",
|
||||
"outputs:p2r/posterior/R0h/r9_c1_n4_s0_phase.json": "6ce7632e2f4e0e7ef3694704df61bd60f50f2a919c509d180d4a5b364a521d07",
|
||||
"outputs:p2r/posterior/R0h/r10_c1_n4_s0_particles.npz": "ccf6ff42e18e5caf1424cf99a76717b44cf859908205ef91841b819b745f392f",
|
||||
"outputs:p2r/posterior/R0h/r10_c1_n4_s0_phase.json": "9333225fa963bbef09dd39664b2e80a33fbb8170e88a5ce52d1996ba0e37c15f",
|
||||
"outputs:p2r/posterior/R0h/r11_c1_n4_s0_particles.npz": "3b80796b3944413562742bc0843106571298e44aeb5f734eb0f15c5c0cd2da03",
|
||||
"outputs:p2r/posterior/R0h/r11_c1_n4_s0_phase.json": "4fb5a297b5845dfdf5f3fe7a3457865afb7954185bf3b6e3757ee80779c67b99",
|
||||
"outputs:p2r/posterior/R0h/r12_c1_n4_s0_particles.npz": "bc05e164683b73d94dbdd1559f6c0e53a8c2e9847f414088a3570590e703aca6",
|
||||
"outputs:p2r/posterior/R0h/r12_c1_n4_s0_phase.json": "1549857aca3c4d412aa5246fd6e4846e0ae44307ffd96fdb0131c10e9682a339",
|
||||
"outputs:p2r/posterior/R0h/r13_c1_n4_s0_particles.npz": "0600bd71479316eb53e29a940af46726917a555a5489afbcac95939acef76663",
|
||||
"outputs:p2r/posterior/R0h/r13_c1_n4_s0_phase.json": "c671c7bbd0caae492e232dca66854e3ec72c1c4116aef3d6eab337503a142d05",
|
||||
"outputs:p2r/posterior/R0h/r14_c1_n4_s0_particles.npz": "761bdf503cf84d2aee01fd249f9a6cf6f33ecefd3e996e175ff37a7d231527aa",
|
||||
"outputs:p2r/posterior/R0h/r14_c1_n4_s0_phase.json": "e5464d5304b22ada70ae8b69b31afd08cf3c637a8c6d3f01f89ee044e7c9a808",
|
||||
"outputs:p2r/posterior/R0h/r15_c1_n4_s0_particles.npz": "9a998f657239175883556d9acb749eafc885f01fc8b5e301d3945b3daaffdf9a",
|
||||
"outputs:p2r/posterior/R0h/r15_c1_n4_s0_phase.json": "0659850be0f8b937c0f140bb83e8559684f0f8d47f5c23a179d558a1b2068486",
|
||||
"outputs:p2r/posterior/R0h/r8_c1_n16_s0_particles.npz": "dc261c29af42887806406c14ff5a98ee9e0b4438a1002d360688091400649266",
|
||||
"outputs:p2r/posterior/R0h/r8_c1_n16_s0_phase.json": "40979d874d3e20af80c2f26afd0a091f509abdc6100543c3e864b89e969bbb6a",
|
||||
"outputs:p2r/posterior/R0h/r9_c1_n16_s0_particles.npz": "76abcd6d9da0184904473cf51ac62c9bc1c2c7ef768016be0876c3d60e5943f1",
|
||||
"outputs:p2r/posterior/R0h/r9_c1_n16_s0_phase.json": "5999b1fe877cc21c4e712d6dccc221ed558a4a642345311074ea7b905f3e3745",
|
||||
"outputs:p2r/posterior/R0h/r10_c1_n16_s0_particles.npz": "050fd0db044f68389136ce04b1a2c747e6959de28d22d41442b9a0b4668f28df",
|
||||
"outputs:p2r/posterior/R0h/r10_c1_n16_s0_phase.json": "9d66d40af704e2d6170d89b4a8d0ad689a0083c379744eb532cd2504fc8b4686",
|
||||
"outputs:p2r/posterior/R0h/r11_c1_n16_s0_particles.npz": "630d576b74725a0376ca2ddee568ad7372f017ca158071b5360ce3a24b20b656",
|
||||
"outputs:p2r/posterior/R0h/r11_c1_n16_s0_phase.json": "456d8a69ab4b9049510e06b29b12dde9252f7eb3fa97b2e5867634de16b8d7b3",
|
||||
"outputs:p2r/posterior/R0h/r12_c1_n16_s0_particles.npz": "100247cd4db887911212d17e752107ad848b5448481542e2493ca686aa2c3bd4",
|
||||
"outputs:p2r/posterior/R0h/r12_c1_n16_s0_phase.json": "a1953bffa9f0b15d0e8616d1ee26859738a2fac32ebc2d7c678133a7f9f52124",
|
||||
"outputs:p2r/posterior/R0h/r13_c1_n16_s0_particles.npz": "06c6e84cf1d4ac270c677a3ea43143f250a2834c51533e628f23c6634f783169",
|
||||
"outputs:p2r/posterior/R0h/r13_c1_n16_s0_phase.json": "2eada76427f27f3e853674c76394f6e3d97126c9ebb2ca7cfb4110b8e963c31b",
|
||||
"outputs:p2r/posterior/R0h/r14_c1_n16_s0_particles.npz": "ca5521c1aabe3fa9ae86e7db6bc2b0f9bd2b71d7eaa900ef3232e3fa01c293f0",
|
||||
"outputs:p2r/posterior/R0h/r14_c1_n16_s0_phase.json": "00fb832008590ee27c07b72666c2402ca2793e50212dfc4819ac17587daa61db",
|
||||
"outputs:p2r/posterior/R0h/r15_c1_n16_s0_particles.npz": "41cc06637eed575d698f3edccbd8b8b5f265463c061a69d51ccaa7725e901165",
|
||||
"outputs:p2r/posterior/R0h/r15_c1_n16_s0_phase.json": "d0df0a3f9cb55a16d893de229d7880db4dc047aee038b87f4e9430242499b6b5"
|
||||
},
|
||||
"nominal_fingerprints": {
|
||||
"8": {
|
||||
"match": true,
|
||||
"sha256_of_fingerprint": "09ab86e2d27583a42e66f4468c3cd7b67d90d5538e305c34fa406ad8711014a8"
|
||||
},
|
||||
"902": {
|
||||
"match": true,
|
||||
"sha256_of_fingerprint": "a9e084ba63afa05706887dde80a9c5fbef33727fedbbd665bd2d1207cd6f8e8a"
|
||||
}
|
||||
},
|
||||
"locked_utc": "2026-10-29T14:39:20.607386+00:00",
|
||||
"canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and text inputs; binary inputs exact",
|
||||
"studies": [
|
||||
"S1",
|
||||
"S2",
|
||||
"S3",
|
||||
"S4",
|
||||
"S8"
|
||||
],
|
||||
"realizations": [
|
||||
8,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
14,
|
||||
15
|
||||
]
|
||||
}
|
||||
1
configs/protocol_bench.sha256
Normal file
1
configs/protocol_bench.sha256
Normal file
@@ -0,0 +1 @@
|
||||
aa763f0a4f81125ea8441fdfba4361f68246c7a0be1c36d4bf8de2650a91a4c5 configs/protocol_bench.yaml
|
||||
427
configs/protocol_bench.yaml
Normal file
427
configs/protocol_bench.yaml
Normal file
@@ -0,0 +1,427 @@
|
||||
# Protocol bench (phase P6, level B of Pivot 1; plan §12 items 22 and 26; docs/research/pivot-theory-benchmark.md §6).
|
||||
# Registration-aware synthetic benchmark on D2: S1 grid fill, S2 misspecification axes, S3 anchor-free baselines
|
||||
# under the P2r cells, S4 second backbone, S8 controlled cycle-skip regime. Locked by SHA-256 (configs/protocol_bench.sha256)
|
||||
# and configs/protocol_bench.lock.json (code, environment, inputs, P2r reference artifacts, nominal generator
|
||||
# fingerprints) BEFORE the first run on realizations 8–15: `scripts/run_bench.sh lock`. After the lock this file is
|
||||
# never edited; a change needs protocol_bench v2 with a recorded deviation. Dev realizations 902–905 (and 900/901)
|
||||
# are the only realizations used for design; their outputs (outputs/bench/dev) are never results.
|
||||
status: "LOCKED 2026-10-29 — reviewed by the coordinator (7 fixes applied), locked by scripts/run_bench.sh lock after the dev TCN budget selection; no main-grid run before the lock"
|
||||
version: 1
|
||||
date: 2026-10-29
|
||||
designed_after: >
|
||||
Designed on 29/10/2026 after the complete protocol_p2r results (H2a pass at R10/R0/Rm5, H2b pass, σ_a arm fail,
|
||||
H3 descriptive), after the field phases P3 (G-C fail) and P4 (G-D fail), and after the post hoc inspection of
|
||||
29/10/2026 (outputs/p2r/posthoc: Oracle/B3d-Sa and M2-Sa/B3d-Sa ratios, the classical and Berkson bounds (a), (b),
|
||||
b60 and cross-spectral, at σ_post and at the warp error; plan §12 item 24). The T2 mechanism study
|
||||
(docs/research/t2-mechanism.md) was declared and started before this file was written; its results
|
||||
(docs/research/t2-results.md, 29/10/2026, exploratory, on realizations 8–15) arrived while this draft was being
|
||||
written and motivated two DISCLOSED additions (training.equal_budget_arm and the method Ctl-GP); they changed no
|
||||
rule or threshold of the hypotheses below.
|
||||
deviation: >
|
||||
protocol_bench is not a pre-registration in the sense of protocol_p2: every study was designed knowing the P2r
|
||||
outcome, and S1/S3/S4 reuse the P2r realizations 8–15 and, for S4 and the S2 nominal reference, the P2r SMC
|
||||
particles and results. The paper's Methods state this. Hypotheses marked `claim` below are confirmatory ONLY in
|
||||
the sense that their rule and threshold were fixed here before any run on realizations 8–15; everything marked
|
||||
`descriptive` is reported without a pass/fail; `disclosed` marks an analysis whose motivation came from T2, which
|
||||
looked at test realizations 8–15 (T2 test (v): B3d-Sa and M2-Sa gain from 500 iterations in 7/8 wide cells; test
|
||||
(ii): a GP-noise bank with the posterior's first two moments obtains most of the c = 1 gain). Nothing from T2 is
|
||||
used to reselect a budget or a method: the registered P2r budgets remain the budgets of every rule. The S2
|
||||
misspecification levels were chosen on dev realizations 902–905 (calibration block) before the lock; realizations
|
||||
8–15 were not used for that choice.
|
||||
|
||||
inputs: # hash-checked at load and recorded in the lock (text files CRLF-normalised)
|
||||
d2_config: {path: configs/d2_synth_bench.yaml, sha256: 2bfd01c94f169116fb92e7c1ac92db8bbe003973a610c32b2740e864b4c761b2} # generator = d2_synth_p2r + regimes + misspec presets (final 29/10)
|
||||
protocol_p2: {path: configs/protocol_p2.yaml, sha256: 0733620042c4ec1b7dce447eef3ec64f915db05acbebbe5b6c977ac42e71a470}
|
||||
protocol_p2r: {path: configs/protocol_p2r.yaml, sha256: eb887311f26a7c1c3dc69d9623d0086cfb5ccc79eea9e5ef59c723078f49c8aa}
|
||||
warp_prior: {path: outputs/p2/warp_prior_f3.json, sha256: 55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27, fit: matern32}
|
||||
wavelet: {path: outputs/wavelets.npz, key: statistical, sha256: b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64}
|
||||
horizon_cache: {path: outputs/d2/horizon_grid.npz, sha256: 70e3321fa9f8fe2a1301877fb34386a64bf29eaa4f6948007e18874678e92b1e}
|
||||
budgets: {path: outputs/p2/diag/train/budgets.json, sha256: 815c6f7abc3d961255feb79bbed57a3e326cbc24cec11bbd97f455f0356e28c5}
|
||||
fingerprints: {path: tests/data/d2_fingerprints.json, sha256: 86cbd6dd49044c1288ec6b649a2d688bf4121280d5cc3dca9b45109523bd6fc1}
|
||||
|
||||
reference:
|
||||
p2r: # read-only; hashed in the lock (ml_porosity/benchmark/protocol.py p2r_reference_files)
|
||||
root: outputs/p2r
|
||||
regimes: [R10, R0, Rm5, R0h, R10tb]
|
||||
use: >
|
||||
S1: the (c ∈ {0, 1, 2}) × (N ∈ {4, 16}) cells of the phase diagram come from outputs/p2r/train/<regime>/runs.csv
|
||||
and outputs/p2r/summary/sigma_post.csv; they are not recomputed. S2: the nominal cells (R10, Rm5; c = 1; N 4/16)
|
||||
are the P2r cells (descriptive reference only; no S2 rule uses them). S3: the P2r runs of Oracle, B3b, B3c,
|
||||
B3c-R, B3d, B3d-Sa, M2-Sa are joined with the new B4a–d runs cell by cell. S4: the P2r SMC particles and
|
||||
phase_R of the S4 cells are the posterior of the TCN methods (same labels, different backbone).
|
||||
fingerprint_rids: [8, 902] # nominal generator fingerprints recomputed at lock time against inputs.fingerprints
|
||||
reproduction_check: >
|
||||
Before the lock, the cell reproduction: (R10, rid 8, c = 1, N = 4) is rerun through this runner (SMC posterior
|
||||
and training) and compared with outputs/p2r/posterior/R10/r8_c1_n4_s0* and outputs/p2r/train/R10/cells/r8_c1_n4.*
|
||||
(scripts/34_run_bench.py repro). The agreement is recorded in docs/research/bench-protocol.md §2 and in
|
||||
outputs/bench/repro/comparison.json. The P2r guard hashes no code, so this check is the evidence that the
|
||||
default generator path and the training path of this runner are those of protocol_p2r.
|
||||
|
||||
grid:
|
||||
realizations: [8, 9, 10, 11, 12, 13, 14, 15] # the P2r realizations; 0–7 (P2) are never used
|
||||
dev_realizations: [900, 901, 902, 903, 904, 905] # design only; 902–905 new for P6
|
||||
seeds: [0, 1, 2, 3, 4] # network seeds; registration seed and SMC stream below
|
||||
test_wells: 8 # observed at the regime SNR with full anchors (anchors unused)
|
||||
regimes: {R10: {snr_db: 10, anchor_density: full}, R0: {snr_db: 0, anchor_density: full},
|
||||
Rm5: {snr_db: -5, anchor_density: full}, R0h: {snr_db: 0, anchor_density: half},
|
||||
R10tb: {snr_db: 10, anchor_density: topbottom}} # = configs/d2_synth_bench.yaml regimes (= p2r)
|
||||
|
||||
registration: # identical to protocol_p2r (scripts/14 with --wavelets estR, P = 1024, K = 1)
|
||||
base: "protocol_p2 registration block (MAP-II, σ_a 7 ms, σ_b 50 ms, 128 ms statistical wavelet, 15° constant phase)"
|
||||
reg_seed: 0
|
||||
smc:
|
||||
code: ml_porosity/benchmark/registration.py (= scripts/14 run_job, estR arm)
|
||||
particles: 1024
|
||||
smc_seed: 0 # random streams [0, i, 13] anchor samples, [0, 19] phase fit, [0, i, 17] SMC
|
||||
arm: estR # statistical wavelet with the phase re-estimated from the SMC log Z (phase_R)
|
||||
checkpoints: [g_old, g_acf, g_one] # same tempering milestones as P2r (checkpoints change the schedule); g_acf used
|
||||
saved: [estR/g_acf] # particles at γ = 1/κ; P2r also stored g_one (unused by any method)
|
||||
phase_step: 15.0
|
||||
phase_half_width: 3
|
||||
phase_max_extra: 6
|
||||
sigma_a_reg_ms: 7.0 # correct σ_a everywhere (the σ_a arm of P2r is not repeated; its failure stands)
|
||||
note_misspec: >
|
||||
Under the S2 presets the registration still assumes the nominal rock physics (obs["ai_log"]), a stationary
|
||||
wavelet with a constant phase and the F3 Matérn-3/2 prior with σ_b = 50 ms: nothing in the registration is told
|
||||
about the preset. The "true wavelet" arm of scripts/14 is not run (under constant Q no single true wavelet
|
||||
exists). Diagnostics from [b, g] are not used (invalid with jitter); warp errors use obs["t_of_tau_true"].
|
||||
|
||||
training: # identical to protocol_p2r for the CNN-GRU methods
|
||||
backbone: "CNNGRUHetero (protocol_p2 training block: d 64, dropout 0.05, Adam 5e-3, grad clip 5, full batch, 64-sample windows, per-well z-score)"
|
||||
code: ml_porosity/models/bank_train.py train_predict (CNN-GRU, unchanged) | ml_porosity/benchmark/training.py train_predict_tcn (S4)
|
||||
lambda: "λ = 1/τ_c as in protocol_p2 (pooled ACF of the high-passed B3b labels)"
|
||||
bank_S: 64
|
||||
budgets: # iterations; P2r values for the P2r methods, protocol_p2 values for B4a–d
|
||||
Oracle: 500
|
||||
B3b: 125
|
||||
B3c: 250
|
||||
B3c-R: 500
|
||||
B3d: 250
|
||||
B3d-Sa: 250
|
||||
M2-Sa: 250
|
||||
B4a: 125
|
||||
B4b: 125
|
||||
B4c: 500
|
||||
B4d: 250
|
||||
PM2: 250 # S8 point label at the posterior-mean warp: budget of B3d-Sa (same label type)
|
||||
BK2: 250 # S8 two-member bank with RML: budget of M2-Sa
|
||||
HM2: 125 # S8 two-member bank with hard-min: budget of B4a (same loss)
|
||||
Ctl-GP: 250 # control bank with RML: budget of M2-Sa (same loss, same bank size)
|
||||
equal_budget_arm: 500 # DISCLOSED (T2 test v, seen on realizations 8–15): every method's trajectory also records
|
||||
# its prediction at 500 iterations (one trajectory per seed, as bank_train evaluates
|
||||
# every budget in the list). No rule uses this arm; it is reported as a separate
|
||||
# descriptive table (equal budget for all methods). It does not replace the budgets above.
|
||||
budgets_tcn: # S4; filled 29/10/2026 from outputs/bench/dev/budgets_tcn.json (stage dev-budgets, runlog
|
||||
# 20261029-133330_bench_dev_budgets_tcn): protocol_p2 budget_selection rule applied to the TCN
|
||||
# on dev 902–905, R10, c = 1, N ∈ {4, 16}, seeds 0–1, candidates [125, 250, 500, 1000, 2000].
|
||||
# Every method selects 125, the smallest candidate (mean total RMSE rises monotonically with
|
||||
# iterations for the TCN on ≤ 16 wells: e.g. B3d-Sa-TCN 1.406/1.428/1.482/1.537/1.592,
|
||||
# M2-Sa-TCN 1.389/1.429/1.469/1.521/1.616); the minimum lies on the boundary of the candidate
|
||||
# list, which is kept as in protocol_p2 (no smaller candidate is added after seeing dev).
|
||||
Oracle: 125
|
||||
B3b: 125
|
||||
B3c: 125
|
||||
B3c-R: 125
|
||||
B3d-Sa: 125
|
||||
M2-Sa: 125
|
||||
budget_candidates: [125, 250, 500, 1000, 2000]
|
||||
budget_rule_new_methods: >
|
||||
No budget is selected on realizations 8–15. PM2/BK2/HM2 inherit the budget of the P2r/P2 method with the same
|
||||
label type and loss. TCN budgets follow training.budgets_tcn.
|
||||
|
||||
methods:
|
||||
Oracle: {labels: true warp, note: "reference ceiling under the generator of the cell (under S2 presets the seismic changed too)"}
|
||||
B3b: as protocol_p2 (marker-calibrated sonic through the anchors)
|
||||
B3c: as protocol_p2 (B3b + local NCC shifts, protocol_p2 phase)
|
||||
B3c-R: as protocol_p2r (B3c with the wavelet at phase_R)
|
||||
B3d: as protocol_p2 (weighted mean warp of the anchor-conditioned M2 of P2)
|
||||
B3d-Sa: as protocol_p2r (labels at the mean warp of the SMC particles, γ = 1/κ)
|
||||
M2-Sa: as protocol_p2r (RML, soft-min with λ, bank of 64 SMC particles, uniform π)
|
||||
B4a: as protocol_p2 (B3b labels shifted ±8 samples, uniform π, hard-min)
|
||||
B4b: as protocol_p2 (same bank, RML with λ)
|
||||
B4c: as protocol_p2 (soft-DTW γ = 0.1, band ±8, on B3b labels)
|
||||
B4d: as protocol_p2 (DILATE α = 0.5, γ = 0.1, band ±8, on B3b labels)
|
||||
PM2: "S8: point labels at t_true + s·Δ/2 (the posterior-mean warp of the two-mode posterior {t_true, t_true + s·Δ}); s = ±1 per training well from rng [rid, 20261030, 8, i]"
|
||||
BK2: "S8: two-member bank {t_true, t_true + s·Δ}, π = (½, ½), RML with the cell's λ (a calibrated bank: the truth is a member)"
|
||||
HM2: "S8: the BK2 bank with the hard-min loss (λ = ∞)"
|
||||
Ctl-GP: >
|
||||
DISCLOSED (T2 test ii): control bank of 64 warps T̄ + η_s with η_s Gaussian with the empirical mean and covariance
|
||||
of the 1024 SMC particles on the warp grid (rng [reg_seed, i, 2029]; monotone draws, ≤ 1280 attempts, u-space
|
||||
fallback flagged), uniform π, RML with the cell's λ. It carries the posterior's first two moments and no link
|
||||
between a member and the seismic: the natural null for "the information in the SMC bank matters".
|
||||
Implementation ml_porosity/benchmark/training.py control_gp_bank (= scripts/32 control_bank).
|
||||
suffix_TCN: "S4: the same labels trained with TCNHetero (ml_porosity/f3/training.py; 4 dilated Conv1d, k = 5, dilations 1–8, softplus σ); names carry the suffix -TCN"
|
||||
ensembles: "5-seed ensembles (μ = mean μ_s, σ² = mean σ_s² + var μ_s) reported descriptively (coverage, NLL, CRPS); no calibration claim"
|
||||
|
||||
studies:
|
||||
S1: # grid fill of the phase diagram (pivot §2.2 S1, theory gap T5)
|
||||
regimes: [R10, Rm5, R0, R0h, R10tb] # run order = priority; see cut_order
|
||||
drift_factors: [0, 0.5, 1, 1.5, 2]
|
||||
n_train: [2, 4, 8, 16]
|
||||
existing: "P2r cells (c ∈ {0, 1, 2}) × (N ∈ {4, 16}) are read from outputs/p2r; 14 new (c, N) combinations per regime"
|
||||
methods: [Oracle, B3b, B3c, B3c-R, B3d, B3d-Sa, M2-Sa]
|
||||
cells_new: "5 regimes × 14 (c, N) × 8 realizations = 560 SMC jobs and 560 training cells"
|
||||
S2: # misspecification axes (plan §12 item 22 decision 2); MANDATORY for the word "benchmark"
|
||||
regimes: [R10, Rm5]
|
||||
drift_factors: [1]
|
||||
n_train: [4, 16]
|
||||
presets: # names in configs/d2_synth_bench.yaml misspec_presets; levels fixed on dev 902–905 (calibration)
|
||||
rock_physics: [rp_L1, rp_L2] # per-unit φ–DT intercept scatter sd 0.10 / 0.15
|
||||
wavelet: [wv_L1, wv_L2, wv_Q] # phase sub-axis minphase 0.5 / 1.0; bandwidth sub-axis Q 80 (single level, third entry, no L1 role)
|
||||
drift: [dr_L1, dr_L2] # two mechanisms: hyperparameters (σ_b ×3, σ_g ×1.5, ℓ ×0.5) / structural (step 8 ms + jitter 1 ms)
|
||||
controls: # optional, run last and cut first within S2: in-family controls of two axes
|
||||
presets: [rp_C, wv_C]
|
||||
n_train: [4]
|
||||
methods: [Oracle, B3b, B3c, B3c-R, B3d-Sa, M2-Sa, Ctl-GP] # decision 2's set plus the two cheap point ties B3b, B3c so that
|
||||
# the H2a competitor set {B3b, B3c, B3c-R} is the P2r one, plus the
|
||||
# disclosed control bank Ctl-GP (training only)
|
||||
cells: "2 regimes × 7 presets × 2 N × 8 realizations = 224 SMC jobs and 224 training cells (+ 32 control jobs)"
|
||||
nominal_reference: "the P2r cells of the same (regime, c = 1, N): descriptive comparison only"
|
||||
S3: # anchor-free / shift-bank baselines under the P2r cells
|
||||
regimes: [R10, R0, Rm5, R0h, R10tb]
|
||||
drift_factors: [0, 1, 2]
|
||||
n_train: [4, 16]
|
||||
methods: [B4a, B4b, B4c, B4d, Ctl-GP]
|
||||
posterior: p2r # B4 uses the protocol_p2 B3b labels (register(); registration seed 0, as P2r); Ctl-GP reads the
|
||||
# P2r particles of the cell (no new SMC)
|
||||
cells: "5 × 3 × 2 × 8 = 240 training cells; joined with the P2r runs of the same cells"
|
||||
S4: # second backbone on representative cells
|
||||
backbone: tcn
|
||||
posterior: p2r # SMC particles and phase_R of outputs/p2r/posterior/<regime>
|
||||
cells: [{regime: R10, c: 1}, {regime: Rm5, c: 1}, {regime: R0h, c: 1}]
|
||||
n_train: [4, 16]
|
||||
methods: [Oracle, B3b, B3c, B3c-R, B3d-Sa, M2-Sa]
|
||||
cells_count: "3 × 2 × 8 = 48 training cells"
|
||||
S8: # controlled cycle-skip (two-mode) regime; theory Corollary 3 and Proposition 4
|
||||
regimes: [R10, Rm5]
|
||||
drift_factors: [1]
|
||||
n_train: [4, 16]
|
||||
delta_ms: [8, 16, 32] # mode separation; sign-flip band of cos(πfΔ): (62.5, 187), (31.3, 93.8), (15.6, 46.9) Hz
|
||||
methods: [Oracle, PM2, BK2, HM2]
|
||||
posterior: none # the two-mode posterior is constructed from the true warp (no SMC); inputs as the regime
|
||||
cells: "2 × 3 × 2 × 8 = 96 training cells"
|
||||
note: >
|
||||
This is the "set Δ explicitly" reading of pivot §2.2 S8. The run-to-run instability of the real SMC posterior at
|
||||
c = 2 (P2r flag) is not re-measured here; the realistic multimodal cells remain flagged as in P2r.
|
||||
|
||||
rules: # all from protocol_p2 / protocol_p2r; thresholds never change
|
||||
metric: "band RMSE (6 Hz Butterworth high-pass, p.u.) macro over the 8 test wells; band PCC secondary"
|
||||
run: "(realization, c, N, method, seed) at the method's budget; cell statistics average over realization × seed"
|
||||
improves: "band_rmse(cand) ≤ 0.90 · band_rmse(best) OR band_pcc(cand) ≥ band_pcc(best) + 0.05"
|
||||
cell_pass: "improves in ≥ 4/5 seeds (per seed: mean over realizations) AND in > 1/2 of the realizations (per realization: mean over seeds)"
|
||||
better: "cand < ref in ≥ 4/5 seeds AND > 1/2 of realizations (direction rule for ratios without a margin)"
|
||||
no_harm: 1.02
|
||||
wide: "σ_post ≥ 1.5 ms (σ_post = mean 90% width of τ(t) of the SMC particles over the train wells / 3.29; no labels)"
|
||||
ci: "95% bootstrap over realizations (2000 resamples, rng 0) for every ratio; reported regardless of direction"
|
||||
permutation: "10000 permutations, rng 0, one-sided p; a declared test passes at p < 0.05"
|
||||
flags: "c = 2 cells keep the P2r flag 'unstable posterior'; they are reported, never primary evidence"
|
||||
multiplicity: >
|
||||
Every `claim` below is a separate pre-declared test with its own rule and threshold; there is no family-wise
|
||||
correction. Number of claims: 9 (S1-H1, S1-H2, S2-H1, S2-H2, S3-H1, S4-H1, S4-H2, S8-H1, S8-H2), giving 11
|
||||
verdicts because S2-H1 is judged once per axis (rock physics, wavelet, drift). The paper reports every verdict,
|
||||
including failures, and never selects among them.
|
||||
bounds: >
|
||||
No rule here is bound-based. Where a population bound is quoted next to a B3d-Sa ratio at c = 1 it is the Berkson
|
||||
bound 1/B_b (T2 test iv found the Berkson structure for B3d-Sa at c = 1, informed by T2, disclosed); at c = 2 no
|
||||
structure holds and no bound is quoted.
|
||||
|
||||
hypotheses:
|
||||
S1-H1:
|
||||
kind: claim
|
||||
statement: "H2a extends to c = 1.5 in R10: B3d-Sa beats the best point tie {B3b, B3c, B3c-R} (cell_pass) for both N ∈ {4, 16}"
|
||||
prediction: pass
|
||||
S1-H2:
|
||||
kind: claim
|
||||
statement: >
|
||||
The bank gain grows with the number of wells at fixed posterior width (finite-sample heuristic of the paper,
|
||||
Sec. 4.3): in every family (regime, c) whose N = 16 cell is wide, the ratio r(N) = band_rmse(M2-Sa)/band_rmse(B3d-Sa)
|
||||
is lower at N = 16 than at N = 2 in ≥ 2/3 of the families, AND the pooled Spearman ρ(log2 N, r) over all
|
||||
(family, N) points is negative with one-sided permutation p < 0.05 (permutations within family).
|
||||
families: "(regime, c) with σ_post(N = 16) ≥ 1.5 ms, from the P2r and S1 posteriors"
|
||||
prediction: pass
|
||||
S1-D:
|
||||
kind: descriptive
|
||||
items: ["phase diagram c × N of band RMSE per method and of the ratios B3d-Sa/best point tie and M2-Sa/B3d-Sa with CI",
|
||||
"σ_post(c, N) and SMC warp RMSE / coverage90 per regime",
|
||||
"additivity fit per regime: band_rmse²(B3d-Sa; c, N) = band_rmse²(Oracle; c, N) + β σ_post²(c, N), β and R² reported",
|
||||
"H2a cell rule at every new (c, N) with the P2r competitors (no verdict beyond S1-H1)"]
|
||||
S2-H1:
|
||||
kind: claim
|
||||
statement: >
|
||||
Posterior-mean labels survive moderate misspecification: for each axis at level L1, in R10, B3d-Sa beats the best
|
||||
point tie {B3b, B3c, B3c-R} (cell_pass, c = 1) for both N ∈ {4, 16}. One verdict per axis; the claim is scoped to
|
||||
the axes that pass. Rm5, L2 and the bandwidth cell wv_Q are reported with the same rule, without a claim.
|
||||
prediction: >
|
||||
pass for rock physics (dev R10, N = 4: SMC warp RMSE ×1.27 nominal at rp_L1, cov90 0.85) and for the wavelet
|
||||
phase sub-axis at L1 (dev: wv_L1 posterior overconfident, cov90 0.11, yet its warp RMSE 2.14 ms stays below the
|
||||
point tie B3c's 4.30 ms in 4/4 rids); fail expected at wv_L2 (dev: 3.93 ms, cov90 0.03, below B3c 4.57 ms in
|
||||
only 3/4 rids); drift uncertain (dr_L1 1.55 ms / dr_L2 2.27 ms against B3c 3.48 / 4.52 ms, 4/4 rids ahead).
|
||||
expected_null: >
|
||||
At Rm5 (noise RMS 1.78 × signal) every preset's model error (≤ 0.61 × signal) is buried in the noise: on dev
|
||||
(902, 903) all presets left the Rm5 SMC diagnostics within ±10% of nominal, including wv_L2. Pre-declared null:
|
||||
at Rm5 the registration diagnostics (warp RMSE, cov90, σ_post, phase_R) of every preset are expected to equal
|
||||
their nominal values within the CI; S2 at Rm5 therefore tests only the label-side and input-side consequences
|
||||
of misspecification (Oracle and the point ties change with the seismic), not the registration. The sharpest
|
||||
version is the rock-physics axis (model error 0.22–0.30 of the noise).
|
||||
S2-H2:
|
||||
kind: claim
|
||||
statement: >
|
||||
No harm of the posterior bank under misspecification: for every S2 preset (rp_L1, rp_L2, wv_L1, wv_L2, wv_Q,
|
||||
dr_L1, dr_L2) and regime (R10, Rm5), the mean ratio band_rmse(M2-Sa)/band_rmse(B3d-Sa) over its cells
|
||||
(N ∈ {4, 16}) is ≤ 1.02. Passes only if all 14 (preset, regime) pairs satisfy it (summary.py: len(regimes) ×
|
||||
number of presets = 14).
|
||||
prediction: pass
|
||||
S2-D:
|
||||
kind: descriptive
|
||||
items: ["SMC diagnostics per preset, regime, N: warp RMSE, coverage90, σ_post, overconfidence = warp RMSE/σ_post, phase_R, κ_post, r_post",
|
||||
"degradation of every method vs its P2r nominal cell (ratio with CI); Oracle degradation isolates the covariate change",
|
||||
"M2-Sa vs B3d-Sa at wide cells (σ_post ≥ 1.5 ms) with the 'better' rule, and the ratio vs coverage90 (does the gain track coverage rather than σ_post?)",
|
||||
"B3d-Sa no-harm flag: band_rmse(B3d-Sa) ≤ 1.02 · best point tie per (preset, regime, N)",
|
||||
"controls rp_C, wv_C (if run): in-family misspecification should leave every diagnostic at its nominal value",
|
||||
"DISCLOSED (T2 ii): Ctl-GP vs B3d-Sa and M2-Sa vs Ctl-GP ('better' rule) per cell: under misspecification, does the SMC bank's information matter beyond its two moments?",
|
||||
"DISCLOSED (T2 v): the equal-budget table at 500 iterations for every method, next to the registered-budget table"]
|
||||
S3-H1:
|
||||
kind: claim
|
||||
statement: >
|
||||
The H2a verdict is unchanged when the competitor set is extended by the anchor-free / shift-bank baselines:
|
||||
per regime (R10, R0, Rm5), B3d-Sa vs best of {B3b, B3c, B3c-R, B4a, B4b, B4c, B4d} with the P2r regime rule
|
||||
(cell_pass at c = 1 for both N AND the c = 0 guard ≤ 1.02 macro and per N). Passes if R10 passes; scoped to the
|
||||
regimes that pass.
|
||||
prediction: pass
|
||||
S3-D:
|
||||
kind: descriptive
|
||||
items: ["complete benchmark table (all methods × 5 regimes × c × N) with CI", "B4 variants vs B3b (do shift banks help without the posterior?)"]
|
||||
T2-1:
|
||||
kind: disclosed
|
||||
statement: >
|
||||
Control bank across the P2r grid (S3 cells, 5 regimes × c ∈ {0, 1, 2} × N ∈ {4, 16}): per cell, Ctl-GP vs B3d-Sa
|
||||
and M2-Sa vs Ctl-GP with the 'better' rule and CI. Reading fixed before the run: the SMC bank's information
|
||||
matters in a cell if M2-Sa is better than Ctl-GP; T2 (ii) found this at c = 2 (3/4 wide cells) and not at c = 1
|
||||
(3/4 cells consistent with label augmentation). No pass/fail; the N = 16, c ∈ {1, 2} wide cells duplicate T2 (ii).
|
||||
S4-H1:
|
||||
kind: claim
|
||||
statement: "Backbone independence of H2a at R10, c = 1: B3d-Sa-TCN beats the best TCN point tie {B3b-TCN, B3c-TCN, B3c-R-TCN} (cell_pass) for both N"
|
||||
prediction: pass
|
||||
S4-H2:
|
||||
kind: claim
|
||||
statement: "Backbone independence of the wide-cell bank gain: M2-Sa-TCN is better than B3d-Sa-TCN ('better' rule) in both wide cells (Rm5 c = 1 N = 16; R0h c = 1 N = 16)"
|
||||
prediction: "pass; uncertain (the TCN has no recurrent context)"
|
||||
S4-D:
|
||||
kind: descriptive
|
||||
items: ["TCN vs CNN-GRU per method and cell (ratio with CI)", "coverage of TCN ensembles"]
|
||||
S8-H1:
|
||||
kind: claim
|
||||
statement: >
|
||||
Corollary 3 (sign flip): at Δ = 32 ms in R10, for both N, the measured transfer of PM2 relative to Oracle,
|
||||
Ĥ(f) = Σ Re[Y* P_PM2] / Σ Re[Y* P_Oracle] (Hann, NFFT 256, pooled over test wells, realizations and seeds, as
|
||||
H1), averaged over the usable frequencies in (1/(2Δ), 3/(2Δ)) = (15.6, 46.9) Hz, is negative. Usable: f ≥ 6 Hz
|
||||
and Re S_Oracle(f) ≥ 10% of its in-band maximum.
|
||||
prediction: pass
|
||||
S8-H2:
|
||||
kind: claim
|
||||
statement: >
|
||||
The calibrated two-member bank repairs the point label where the modes are resolvable: BK2 is better than PM2
|
||||
('better' rule) at Δ ∈ {16, 32} ms, N = 16, in both regimes (4 cells, all must pass).
|
||||
prediction: pass
|
||||
dev_note: >
|
||||
A first draft also required "no harm at Δ = 8 ms". The dev smoke (rid 902, R10, N = 4, seed 0, 29/10) gave band
|
||||
RMSE PM2 0.96, BK2 1.34, HM2 1.30, Oracle 0.62 at Δ = 8 ms, and PM2 1.45 / BK2 0.62 at 16 ms, PM2 1.76 / BK2 0.56
|
||||
at 32 ms: two members 8 ms apart (half the dominant period) are not separated by the window loss and the bank
|
||||
then behaves like an averaged label. The Δ = 8 ms clause was therefore moved to S8-D before the lock (design on
|
||||
dev, recorded here).
|
||||
S8-D:
|
||||
kind: descriptive
|
||||
items: ["Ĥ(f) of PM2, BK2 and HM2 against cos(πfΔ) for every Δ", "ratios PM2/Oracle, BK2/Oracle, HM2/PM2 with CI per cell",
|
||||
"first zero crossing of Ĥ_PM2 vs 1/(2Δ)",
|
||||
"Δ = 8 ms: BK2/PM2 and HM2/PM2 with CI (resolution limit of the bank; dev showed harm at N = 4, see S8-H2.dev_note)"]
|
||||
|
||||
cells: "cell = (study, regime, preset, c, N); all cell statistics average over realization × seed as in protocol_p2r"
|
||||
|
||||
calibration: # S2 levels: chosen on dev 902–905 before the lock; evidence in docs/research/bench-protocol.md §3
|
||||
status: "CHOSEN 29/10/2026 on rids 902 and 903 (all candidates), confirmed on 904 and 905 (chosen presets): bench-protocol.md §3"
|
||||
procedure: >
|
||||
For each axis, candidate levels (configs/d2_synth_bench.yaml cand_*) were registered as in P2r (SMC, P = 1024,
|
||||
estR, γ = 1/κ) on dev realizations at N = 4, c = 1, R10 and Rm5 (scripts/33 --smc). Targets declared before the
|
||||
results: L1 = the registration's in-family model error comparable to the R10 noise (0.5–1.0 ×) and the SMC
|
||||
posterior still ahead of the point ties (SMC warp RMSE < B3c warp RMSE at R10); L2 = model error 1.5–2 × the R10
|
||||
noise, with a visible loss of posterior calibration (coverage90 < 0.5 at R10 or warp RMSE ≥ 2 × nominal).
|
||||
Rock physics uses the per-unit intercept scatter only (the uniform coefficient error is invariant under the
|
||||
profiled-amplitude likelihood, docs/research/bench-generator.md §2; rp_C stays as a control). The drift axis has
|
||||
no generator-side model-error measure and its two presets are two separate MECHANISMS, not two strengths of one
|
||||
setting: dr_L1 = the truth drawn from misspecified hyperparameters (σ_b ×3, σ_g ×1.5, ℓ ×0.5; inside the GP
|
||||
family, partly absorbed by MAP-II), dr_L2 = components outside the GP family (step 8 ms at Truncation + jitter 1 ms,
|
||||
no hyperparameter change). Each is attributed on its own cell; nothing is attributed by difference. On dev dr_L2
|
||||
degrades the SMC more than dr_L1 (×3.3 vs ×2.2), which is why they carry the labels L2 and L1.
|
||||
levels_vs_declared_band: >
|
||||
Two chosen levels sit outside the declared L1 band of 0.5–1.0 × the R10 noise, by design and stated here:
|
||||
rp_L1 (unit sd 0.10) has a model error of 1.24 × the R10 noise (+24%), wv_L1 (minphase 0.5) 1.08 × (+8%).
|
||||
Reasons. (i) Rock physics: the registration is nearly blind to this axis (sd 0.05 → ×1.3, 0.10 → ×1.27,
|
||||
0.15 → ×1.66 SMC warp RMSE; cov90 0.59–0.85), so the level cannot be set by the SMC criterion; 0.10 keeps L1 and
|
||||
L2 distinguishable in model error (1.24 vs 1.68) and in SMC effect, whereas sd 0.075 (0.95 ×, one dev rid:
|
||||
×1.09, cov90 0.76) would be indistinguishable from nominal; the QC author recommended 0.10/0.15. (ii) Wavelet
|
||||
phase: no in-band setting is moderate for the SMC (minphase 0.25 at 0.62 × already gives cov90 0.25), so the
|
||||
band cannot be met together with the "still ahead of the point ties" criterion; 0.5 is the mildest phase level
|
||||
confirmed on 4 rids that keeps the SMC ahead of B3c (2.14 vs 4.30 ms). The L2 levels (1.68 ×, 1.93 ×) and wv_Q
|
||||
(1.41 ×, bandwidth cell) are inside their declared bands. Option (a) of the review (sd 0.075 with two more dev
|
||||
rids) was considered and rejected for reason (i).
|
||||
evidence: >
|
||||
outputs/bench/dev/smc_qc_rid{902,903,904,905}.json (scripts/33 --smc), tabulated by scripts/35_bench_calibration.py
|
||||
→ outputs/bench/dev/calibration.{csv,md}; docs/research/bench-protocol.md §3. Dev SMC at R10, N = 4, c = 1, means over
|
||||
rids (warp RMSE ratio to nominal 0.69 ms / coverage90; nominal 0.83): unit sd 0.05 ×1.3/0.59 (1 rid), 0.10 ×1.27/0.85
|
||||
(3), 0.15 ×1.66/0.81 (4); minphase 0.25 ×1.9/0.25 (1), 0.5 ×3.2/0.11 (4), 1.0 ×5.9/0.03 (4, ahead of B3c in 3/4),
|
||||
Q 160 ×1.1/0.79 (2), Q 80 ×1.57/0.84 (4), Q 40 ×1.6/0.86 (1); hyperparameter drift ×2.2/0.75 (4), structural drift
|
||||
×3.3/0.61 (4), both ×3.5/0.61 (2), step 16 ms ×5.3/0.60 (2). At Rm5 every preset stays within ×0.97–1.23 of the
|
||||
nominal 3.68 ms. Rock physics is nearly invisible to the registration (chosen by model error);
|
||||
the wavelet phase sub-axis is the one that breaks the constant-phase family (overconfident posterior), while the
|
||||
bandwidth sub-axis widens the posterior without breaking it (kept as a single separate cell wv_Q); the drift levels
|
||||
are two mechanisms rather than two strengths (kept separate for attribution).
|
||||
note_single_checkpoint: >
|
||||
scripts/33 runs the SMC with the single checkpoint γ = 1/κ, whereas P2r and this runner use the milestones
|
||||
(g_old, g_acf, g_one); the dev diagnostics therefore differ slightly from what the main run will produce for the
|
||||
same cell (rid 902, R10 nominal: 0.74 vs 0.70 ms warp RMSE at P00). Levels were chosen on ratios to nominal under
|
||||
the same schedule.
|
||||
chosen: # verbatim misspec dicts (configs/d2_synth_bench.yaml); checked against the file at load
|
||||
rp_L1: {rock_physics: {unit_dt_intercept_sd: 0.10}}
|
||||
rp_L2: {rock_physics: {unit_dt_intercept_sd: 0.15}}
|
||||
wv_L1: {wavelet: {minphase_frac: 0.5}}
|
||||
wv_L2: {wavelet: {minphase_frac: 1.0}}
|
||||
wv_Q: {wavelet: {Q: 80.0, Q_t_ref_ms: 400.0, Q_dispersion: true}}
|
||||
dr_L1: {drift: {sigma_b_factor: 3.0, sigma_g_factor: 1.5, ell_factor: 0.5}}
|
||||
dr_L2: {drift: {step_ms: 8.0, step_width_ms: 12.0, step_horizon: Truncation, jitter_sd_ms: 1.0, jitter_ell_ms: 8.0}}
|
||||
|
||||
reproduction: # see reference.reproduction_check
|
||||
rid: 8
|
||||
regime: R10
|
||||
c: 1
|
||||
n_train: 4
|
||||
methods: [Oracle, B3b, B3c, B3c-R, B3d, B3d-Sa, M2-Sa]
|
||||
tolerance_note: >
|
||||
The SMC on the GPU matches the CPU algorithm up to rounding and bank_train sets no cudnn deterministic flags;
|
||||
bitwise agreement is reported if it occurs, otherwise the maximum deviations of phase_R, particles, warp RMSE
|
||||
and band RMSE are reported as the reproducibility floor of this environment.
|
||||
result: >
|
||||
bitwise exact (29/10/2026, cuda:1, torch 2.14.0+cu130, H200): phase0 and phase_R identical (−0.990696378084408),
|
||||
log Z max |diff| 0, all four g_acf particle sets (1024 × 390) bitwise equal, every warp diagnostic 0, stage counts
|
||||
17/17/17/18 identical; 280 training rows (7 methods × 5 seeds × 8 test wells) max |diff| 0 on band RMSE, RMSE,
|
||||
band PCC, NLL and coverage90, all 35 μ arrays and y_true bitwise equal, _diag.csv 0.
|
||||
Evidence: outputs/bench/repro/comparison.json (runlog 20261029-133329_bench_repro_r8); docs/research/bench-protocol.md §2.
|
||||
|
||||
cut_order: # if late (never cut thresholds); plan §6.1
|
||||
- "S4 (second backbone)"
|
||||
- "S8 (cycle-skip regime)"
|
||||
- "S2 reduced to the rock-physics axis (then the paper says 'controlled synthetic study', not 'benchmark')"
|
||||
- "S1 reduced to c ∈ {0.5, 1.5} × N ∈ {4, 16} on R10, Rm5, R0 (within S1 the regimes R0h, R10tb are cut first)"
|
||||
- "S2 controls rp_C, wv_C are optional at all times; within S2 the bandwidth cell wv_Q is cut before the phase levels"
|
||||
- "the equal-budget arm and Ctl-GP are disclosed extras: dropping them needs no new protocol version only if no cell has been trained yet"
|
||||
|
||||
compute: # estimate; see docs/research/bench-protocol.md §5
|
||||
posterior_jobs: {S1: 560, S2: 224, S2_controls: 32}
|
||||
training_cells: {S1: 560, S2: 224, S3: 240, S4: 48, S8: 96}
|
||||
split: "cuda:0 — S1 R10/Rm5/R0h then S2 R10; cuda:1 — S1 R0/R10tb then S2 Rm5, S3, S4, S8; 4 workers per GPU at 6 GiB each when free"
|
||||
resume: "scripts/run_bench.sh is restartable: completed jobs are skipped by fingerprint and checksum"
|
||||
|
||||
wording:
|
||||
forbidden: ["first", "novel", "the word benchmark if S2 is incomplete", "calibrated uncertainty", "generalizing to the field",
|
||||
"mechanism proven", "tuning on test labels", "claims about λ"]
|
||||
required: ["designed after P2r (deviation above)", "S2 levels chosen on dev 902–905", "P2r guard hashes no code; reproduction check reported",
|
||||
"F3 and Volve are scope-bounding cases"]
|
||||
13
docs/plan.md
13
docs/plan.md
@@ -415,7 +415,8 @@ Chốt ngày 27/10/2026: toàn bộ bài, gồm cả review nội bộ và bản
|
||||
| **P3 F3 field** | T4 28/10 | Nested LOWO đầy đủ; ensemble; calibration; ablation; leave-one-anchor-out; volume kèm bất định. M3 hoãn, không đưa vào bài | Bảng và hình F3 | **G-C (cuối 28/10):** chiều cải thiện nhất quán với synthetic ở ≥ 3/4 giếng; coverage 80/90% nằm trong ±5% so với mức danh nghĩa. Kết quả: không đạt (1/4 giếng; coverage 52,38/60,91%; mục 12, ý 16) |
|
||||
| **P4 Field 2** | T4 28/10 dựng pipeline (song song P3); T5 29/10 chạy (xong 02:21 UTC trên server Linux) | ROI Volve, tie, pipeline; chạy tập con B1, B3 tốt nhất, B4, B5, M2. Đã áp dụng mục cắt phạm vi 5: B3b, B3c, B3c-R (ứng viên B3), B3d-Sa, M2-Sa | Bảng field 2 (`outputs/p4/summary/`; paper mục 6.5) | **G-D (cuối 29/10):** báo cáo kết quả bất kể chiều nào; giới hạn phạm vi claim theo kết quả. Kết quả: M2-Sa tốt hơn B3 chọn ở 2/6 (lowo) và 3/6 (slot) giếng; coverage90 0,48/0,47; không phương pháp nào có kỹ năng ở giếng blind. Không claim cải thiện, hiệu chuẩn hay transfer (mục 12, ý 20–21) |
|
||||
| **P5 Viết** | Khung bài và mục audit, lý thuyết, D2 viết dần từ 27/10; viết chính T5 29/10 – T6 30/10; từ 29/10 theo lịch mức B (mục 6.1) | Bản nháp, hình, phụ lục chứng minh, gói tái lập (code + config + dữ liệu dẫn xuất theo CC BY-SA 3.0) | Draft v1 (cuối 29/10), v2 (cuối 30/10). Ngày 29/10: đã viết các mục Volve; trục bài đặt vào lý thuyết và benchmark synthetic, hai field là kiểm tra giới hạn phạm vi (mục 12, ý 21). **Mức A viết xong sớm ngày 29/10** (mục 6.1, mục 12 ý 24): bản nháp theo khung Pivot 1, 55 trang, biên dịch sạch; còn TODO đỏ cho S1–S8, T2, khai báo của tác giả. Rủi ro độ dài: thân bài khoảng 14.750 từ so với giới hạn khoảng 5.500 từ của C&G (chưa kiểm trên trang chính thức); người dùng bỏ lượt rút gọn (mục 12 ý 25) | Review nội bộ |
|
||||
| **P6 Review + nộp** | T7 31/10 → dời sang T4 11/11 – T7 14/11 (mục 6.1) | GVHD và một người làm địa vật lý đọc; kiểm tra novelty lần cuối (quét SEG/EAGE, tra quartile); preprint (EarthArXiv/ESSOAr) nếu venue cho phép; nộp | Bản nộp | — |
|
||||
| **P6 Benchmark mức B** | CN 1/11 – T3 10/11 (mục 6.1); bắt đầu sớm từ T5 29/10 | T2 cơ chế (exploratory, khai báo trước ở `docs/research/t2-mechanism.md`); sửa generator cho S2 (dev 902–905); khóa `configs/protocol_bench.yaml` trước lần chạy đầu; S1 lấp lưới, S3 B4 dưới SMC, S4 backbone thứ hai, S2 ba trục misspec, S8 cycle-skip có kiểm soát; S7 đóng gói; viết lại các mục kết quả | `configs/protocol_bench.*`, `outputs/t2/`, `outputs/bench/`, gói benchmark | — (không có cổng mới; luật đạt của từng S ghi trong protocol; S2 thiếu thì bài gọi là "controlled synthetic study") |
|
||||
| **P7 Review + nộp** | T7 31/10 → dời sang T4 11/11 – T7 14/11 (mục 6.1) | GVHD và một người làm địa vật lý đọc; kiểm tra novelty lần cuối (quét SEG/EAGE, tra quartile); preprint (EarthArXiv/ESSOAr) nếu venue cho phép; nộp | Bản nộp | — |
|
||||
|
||||
### 6.1 Lịch mức B sau Pivot 1 (chốt 29/10/2026; hạn T7 14/11/2026)
|
||||
|
||||
@@ -426,7 +427,7 @@ Pivot 1 kích hoạt ngày 29/10/2026 (mục 12 ý 22): bài chuyển thành lý
|
||||
| T5 29/10 | Chốt 5 quyết định; cập nhật plan, AGENTS, report; khảo sát dataset field public (`docs/research/field-dataset-survey.md`) | Quyết định ghi ở mục 12 ý 22 |
|
||||
| T6 30/10 – T7 31/10 | Mức A: viết lại abstract, intro, contributions, discussion, conclusion; T1, T4, T8 thành mệnh đề; T4 từ `outputs/p2r/train/*/cells/*.npz`; T3 (giải tích + mô phỏng trên dự đoán P2r); T10 related work. **Xong sớm ngày T5 29/10** (mục 12 ý 24). Việc còn lại của hai ngày này: trích dẫn dataset F3 và Volve; còn lại là dự phòng. Lượt rút gọn độ dài cho venue đã bỏ theo quyết định của người dùng ngày 29/10 (mục 12 ý 25) | Draft khung mới (xong) |
|
||||
| CN 1/11 | T2 exploratory (khai báo trước ở `docs/research/t2-mechanism.md`): responsibility-weighted warp error; bank nhiễu đối chứng; tách ô đa mode; kiểm Berkson hay classical (hiệp phương sai offset); B3d-Sa ở số vòng lặp của Oracle | Phân tích cơ chế: còn lợi ích nào vượt hiệu chỉnh Berkson không |
|
||||
| T2 2/11 – T3 3/11 | Sửa generator cho S2 (misspec rock physics, wavelet, σ_b/drift); dev trên realization 902–905; viết và khóa `protocol_bench.yaml` (S1, S2, S3, S4, S8) kèm `.sha256`, `.lock.json` | Protocol khóa |
|
||||
| T2 2/11 – T3 3/11 | Sửa generator cho S2 (misspec rock physics, wavelet, σ_b/drift); dev trên realization 902–905; viết và khóa `protocol_bench.yaml` (S1, S2, S3, S4, S8) kèm `.sha256`, `.lock.json` | Protocol khóa (**xong sớm 29/10 14:39 UTC**; chạy chính bắt đầu 14:43 UTC, mục 12 ý 26) |
|
||||
| T4 4/11 – T5 5/11 | S1 lấp lưới c ∈ {0.5, 1.5}, N ∈ {2, 8}; S3 B4 dưới SMC; S4 backbone thứ hai (hai GPU) | Lưới đầy |
|
||||
| T6 6/11 – T7 7/11 | S2 ba trục ở R10, Rm5, c = 1, N ∈ {4, 16}; S8/T8 cycle-skip | Bảng misspec |
|
||||
| CN 8/11 – T3 10/11 | S7 đóng gói benchmark (một lệnh sinh, một lệnh chấm, bảng tham chiếu, README, hash, Zenodo); viết lại §4–5 | Gói benchmark; draft v2 |
|
||||
@@ -724,3 +725,11 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
|
||||
25. **Bỏ lượt rút gọn độ dài; commit và push (29/10/2026).**
|
||||
- **Quyết định của người dùng:** bỏ lượt rút gọn độ dài cho venue (trước đó dự kiến 30–31/10: kiểm giới hạn trên Guide for Authors của C&G, chuyển chứng minh, chi tiết Thí nghiệm 1, H1 và phụ lục field sang Supplementary). Rủi ro độ dài vẫn ghi ở R9 (thân bài khoảng 14.750 từ, đếm thô, so với khoảng 5.500 từ theo nguồn thứ cấp), chưa có biện pháp. Ngày 30–31/10 còn: trích dẫn dataset F3 và Volve; còn lại là dự phòng.
|
||||
- **Commit và push lên `main`** (theo yêu cầu người dùng): toàn bộ thay đổi của ý 20–24 (code P4, `configs/protocol_volve.*`, scripts 23–31, `run_p4.sh`/`.ps1`, test, `docs/research/` mới, bản ghi P4x ở `exploratory/` và `docs/research/p4-exploratory.md`, `.gitignore`, bài và tài liệu). Tag `protocol-volve` đặt trên commit này: hash code tính lại từ cây commit khớp `configs/protocol_volve.lock.json` (`c0befaa4…`). Giao thức Volve vì vậy được commit sau lần chạy, đúng như câu ở mục 6 của bài. 190 test pass, 1 skip. `logs/*.out` vẫn không theo dõi, như trước; `data/Teapot/` bị gitignore.
|
||||
|
||||
26. **P6 bắt đầu sớm (29/10/2026; chưa commit).** Theo yêu cầu người dùng, P6 chạy bằng agent con: Fable cho việc cần lập luận (khai báo T2, misspec generator, runner và protocol_bench, diễn giải kết quả, viết lại), Opus cho việc thường (bản đồ code, test, theo dõi chạy, đóng gói). Baseline test: 190 pass, 1 skip.
|
||||
- **p6-gen xong:** `ml_porosity/data/synth_d2.py` nhận `misspec=` với ba trục (rock physics, wavelet, drift prior); `misspec=None` tái lập fingerprint của rid 900, 8, 902 từng bit (`tests/data/d2_fingerprints.json`, ghi trước khi sửa, trên commit 0cfe202). `configs/d2_synth_bench.yaml` chứa các preset, còn đánh dấu PLACEHOLDER; QC ở `scripts/33_bench_generator_qc.py` → `outputs/bench/dev/`; thiết kế ở `docs/research/bench-generator.md`. QC trên rid 902: sai lệch hệ số rock physics đồng đều (rp_C) bị likelihood với α profile hấp thụ hoàn toàn, nên chỉ làm đối chứng, không làm ô chính; preset wavelet L1/L2 hiện quá mạnh (model error khoảng 0.6 so với nhiễu R10 0.32); hai preset drift là hai cơ chế khác nhau, không phải hai mức. QC SMC trên rid 902 (`outputs/bench/dev/smc_qc_rid902.json`; N = 4, c = 1, R10 và Rm5): pha wavelet phụ thuộc tần số (minphase 1.0) là kiểu hỏng mạnh nhất và quá tự tin ở R10 (warp RMSE 4,22 ms, cov90 0,04, kém hơn tie chỉ anchor 3,13 ms); phân tán rock physics theo đơn vị chỉ thấy ở R10 (sd 0,10: RMSE +25 %, vẫn hiệu chỉnh) và vô hình ở Rm5; hai preset drift nhân đôi sai số ở R10, gần hiệu chỉnh. Đề xuất mức: rock physics sd 0,10/0,15; wavelet minphase 0,5/1,0, Q là ô riêng; giữ dr_L1/dr_L2. Mức chính sẽ chốt trên dev 902–905 trước khi khoá.
|
||||
- **T2 xong (12:39–13:27 UTC):** khai báo băm trước mọi tính toán (`docs/research/t2-mechanism.sha256`, f04e6607…), không sai lệch; kết quả ở `docs/research/t2-results.md`, `outputs/t2/summary.md`. Tái lập huấn luyện chính xác (max |dev| = 0 trên 10.560 dòng). (i) tái định vị ngầm có thật: warp trọng số responsibility tốt hơn warp trung bình ở 8/8 ô rộng (giảm 13–40 %). (ii) bank nhiễu GP cùng hiệp phương sai đạt phần lớn lợi ích ở c = 1 (4 'phù hợp (a)', 3 'một phần', 1 'ngược' trên 8 ô rộng); thông tin của bank SMC chỉ cần ở c = 2. (iii) không có bằng chứng cho cơ chế đa mode theo luật chính. (iv) sai số nhãn của B3d-Sa là Berkson ở c = 1 (4/4 ô rộng), nên cận 1/B_b áp dụng; lợi ích H2b không vượt hiệu chỉnh quần thể; không nêu cận ở c = 2. (v) khoảng một phần ba khoảng cách PM–Oracle ở c = 1 là độ dài huấn luyện. Thay đổi code: `bank_train.train_predict` thêm callback `on_budget`, `rml.responsibilities()`; đường mặc định không đổi (24 test pass trước và sau). Exploratory: không đổi H2a/H2b, không dùng để chọn lại budget của P2r.
|
||||
- **protocol_bench (khoá 29/10/2026 14:39 UTC; sha256 `aa763f0a…`, code_sha256 `5ea2eb17…`):** runner `ml_porosity/benchmark/`, `scripts/34_run_bench.py`, `scripts/35_bench_calibration.py`, `scripts/run_bench.sh`; thiết kế ở `docs/research/bench-protocol.md`. Tái lập ô P2r (R10, rid 8, c = 1, N = 4) qua runner: khớp từng bit. Mức S2 chốt trên dev 902–905 (N = 4, c = 1): rock physics sd 0,10/0,15 theo đơn vị; wavelet minphase 0,5/1,0 và ô Q 80 riêng; drift hai cơ chế (siêu tham số; bước 8 ms + jitter 1 ms); ở Rm5 mọi preset để chẩn đoán registration trong khoảng ×0,97–1,23 nên khai báo trước kết quả null. Ô: S1 560 job SMC mới, S2 224 (+32 đối chứng), S3 240 ô huấn luyện, S4 48 (TCN), S8 96 (posterior hai mode dựng từ warp thật, Δ ∈ {8, 16, 32} ms). Thêm có công bố do T2: phương pháp Ctl-GP và nhánh cùng budget 500 vòng; budget đăng ký không đổi. Luật lấy nguyên từ P2/P2r. Rà soát 29/10 đã sửa trước khi khoá: số cặp của S2-H2 (14), số liệu dự đoán S2-H1 lấy từ `outputs/bench/dev/calibration.md`, drift là hai cơ chế riêng, mức L1 vượt dải mục tiêu được công bố (rp_L1 ×1,24; wv_L1 ×1,08) thay vì đổi mức, ghi kết quả tái lập, ghi chú đa so sánh (9 claim, 11 verdict, không hiệu chỉnh family-wise). Budget TCN chọn trên dev 902–905 bằng luật protocol_p2: 125 vòng cho mọi phương pháp TCN (RMSE tăng đơn điệu theo số vòng; điểm chọn nằm ở biên danh sách ứng viên, ghi rõ trong protocol). **Chạy chính khởi động 29/10 14:43 UTC**, tách phiên bằng `setsid nohup` qua `scripts/run_bench.sh`: cuda:0 S1 (R10, Rm5, R0h; 3 worker); cuda:1 S2 (3 worker), S1 (R0, R10tb; 1 worker), S3+S4+S8 train (2 worker). Mỗi worker SMC đo được khoảng 1,56 GB, worker huấn luyện khoảng 0,7 GB; số worker giới hạn để chừa 2–3 GB mỗi card cho project khác. Log `logs/bench_{s1_cuda0,s1_cuda1,s2_cuda1,s348_cuda1}.out`. Chi phí ước tính khoảng 167 worker-giờ (21–26 giờ với 8 worker); với 10 worker hiện tại có thể mất khoảng 40 giờ hoặc hơn. File mới trong `scripts/` và `ml_porosity/` làm hash code của lock F3 và Volve không còn khớp cây làm việc; chấp nhận được vì P3, P4 không chạy lại; không sửa hai lock đó. **15:27 UTC: cả bốn driver bị SIGTERM khi phiên agent kết thúc** (setsid nohup không đủ: Claude Code dọn các process nó đã khởi tạo); lúc đó đã xong 17 posterior S1, 11 posterior S2, 12 job train S3/S4/S8. 15:41 UTC chạy lại trong tmux server của người dùng (session `p6_s2`, `p6_s348`) trên cuda:0: S2 2 worker, S3+S4+S8 2 worker; job đã xong được bỏ qua theo fingerprint (đã kiểm). S1 tạm chờ vì cuda:1 chỉ còn khoảng 1,4 GB trống (project khác giữ khoảng 142 GB) và cuda:0 còn khoảng 2,2 GB sau khi chạy lại. Log `logs/bench_{s2,s348}_cuda0.out`. Từ 15:43 UTC, watcher `operations/p6_s1_watcher.sh` (tmux `p6_s1_watch`, log `logs/p6_s1_watcher.out`) tự khởi động S1 khi một card trống ít nhất 5,7 GB trong hai lần đo cách nhau 1 phút: nhóm A (R10, Rm5, R0) trước, nhóm B (R0h, R10tb) sau, vì hai regime này bị cắt trước theo cut_order; 2–4 worker, chừa 2,5 GB. Hai nhóm không giao nhau vì runner không claim job. **16:07 UTC: project khác trả GPU** (cả hai card trống khoảng 138–143 GB); bỏ watcher trước khi nó khởi động gì, chạy lại với 17 worker trong tmux: `p6_s2` (S2, cuda:1, 6 worker; mất 2 job SMC dở khi chuyển), `p6_s1a` (S1 R10/Rm5/R0, cuda:0, 5 worker), `p6_s1b` (S1 R0h/R10tb, cuda:1, 2 worker), `p6_s348` (S3+S4+S8 train, cuda:0, 4 worker). Số worker giới hạn bởi 40 CPU (2 thread mỗi worker). Log `logs/bench_{s2_cuda1,s1a_cuda0,s1b_cuda1,s348_cuda0}.out`. Từ 16:22 UTC, `operations/p6_supervisor.py` (tmux `p6_supervisor`, log `logs/p6_supervisor.out`) kiểm tra mỗi 5 phút: chạy lại driver chết mà chưa xong trên card trống nhiều nhất (chừa 2,5 GB, tối đa 5 lần mỗi driver), và khi một driver xong thì dồn worker cho driver còn nhiều job nhất (tổng 17 worker, nâng lên 21 lúc 22:26 UTC khi tăng S1 nhóm B từ 2 lên 6 worker vì đây là đường găng; posterior S2 và S1 nhóm A đã xong, hai driver này đang ở bước train); nó chỉ gọi `scripts/run_bench.sh`, nằm ngoài lock và không đổi kết quả vì driver resume theo fingerprint. Job dùng chung GPU là job `vinhnt` của chính người dùng (khoảng 80 GB mỗi card lúc 16:20 UTC).
|
||||
- **GPU:** từ khoảng 13:00 UTC một project khác giữ khoảng 125–128 GB mỗi H200; job P6 giữ ở vài worker nhỏ cho tới khi có chỗ trống.
|
||||
|
||||
27. **Lượt viết theo skill research-paper-writing (30/10/2026; chưa commit).** Skill từ `Master-cai/Research-Paper-Writing-Skills`, cài ở `~/.claude/skills/research-paper-writing`. Sửa có mục tiêu ở Sec. 0–2, 4–8: câu chủ đề, tách đoạn nhiều ý (Sec. 1, 2, 6, 7), lộ trình đầu Sec. 4 (thêm nhãn `sec:theory:blur`, `sec:theory:ident`), Sec. 5 nói rõ RML là họ baseline (C3) và đổi P2/P2r thành Experiment 1/2. Hạ claim: H1 khớp 1% chỉ ở σ = 4–16 ms; phần lớn lợi ích H2a đã có ở c = 0 (thêm vào abstract, Sec. 1, 8); H2b 8/8 chỉ ở N = 16; "bank is cheap" thay bằng lập luận từ định nghĩa loss. Kiểm bằng script: mọi `\todo`/`\todoblock`/`\figplaceholder` giữ nguyên từng byte, không đổi trích dẫn, không mất số nào. Danh sách tự review năm chiều và bản đồ claim–evidence: `paper/self_review.md`.
|
||||
|
||||
118
docs/research/bench-generator.md
Normal file
118
docs/research/bench-generator.md
Normal file
@@ -0,0 +1,118 @@
|
||||
# Bộ sinh D2 với tham số sai mô hình (misspecification) cho S2
|
||||
|
||||
Ngày 29/10/2026. Hạng mục `p6-gen` của phase P6 (plan §12 ý 22, quyết định 2: ba trục sai mô hình "rock physics sai hệ số; wavelet sai pha và băng thông; σ_b / prior drift sai"). Tài liệu này mô tả ngữ nghĩa của từng trục và từng khóa, cái gì **là** và cái gì **không là** sai mô hình so với giả định của registration, bảo đảm common random numbers (CRN), số QC trên realization dev 902, và các quyết định còn mở cho giai đoạn dev (902–905) trước khi khóa `configs/protocol_bench.yaml`.
|
||||
|
||||
Phạm vi: chỉ bộ sinh và test. Runner, protocol và việc chọn mức cuối cùng thuộc bước sau. **Đường mặc định không đổi:** `tests/data/d2_fingerprints.json` ghi SHA-256 của mọi trường `D2Well` và mọi output của `observe()` (rid 900, 8, 902; c ∈ {0, 1, 2}; SNR 10 dB; σ_a 7 ms; 8 giếng test + 4 giếng pool đầu) lấy **trước** khi sửa code; `tests/test_d2_misspec.py` tính lại và so khớp từng bit. Kết quả P2/P2r vì vậy vẫn tái lập.
|
||||
|
||||
## 1. Giao diện
|
||||
|
||||
```python
|
||||
D2Realization(cfg, rid, hg, drift, wavelet, misspec: dict | None = None)
|
||||
```
|
||||
|
||||
`misspec` là `None` (danh nghĩa) hoặc dict với tối đa ba khối con `rock_physics`, `wavelet`, `drift`; khóa và giá trị mặc định ở `synth_d2.MISSPEC_DEFAULTS`. Khóa hoặc khối lạ → `ValueError` (một lỗi chính tả trong protocol đã khóa không được âm thầm có nghĩa "danh nghĩa"). `observe()` giữ nguyên chữ ký và nguyên khóa output. Tiện ích: `preset_misspec(cfg, name)` đọc `cfg["misspec_presets"][name]` (bỏ khóa `note`; `None`/`"nominal"` → `None`); `normalize_misspec`, `active_axes`.
|
||||
|
||||
| Khối | Khóa | Mặc định | Ý nghĩa |
|
||||
|---|---|---|---|
|
||||
| `rock_physics` | `dt_slope_factor` | 1.0 | φ = A + B·DT: B → B·f (B danh nghĩa 0.0011 /(µs/m)) |
|
||||
| | `dt_intercept_factor` | 1.0 | A → A·f (A danh nghĩa −0.2018; DT_matrix = −A/B = 183 µs/m) |
|
||||
| | `rho_slope_factor` | 1.0 | RHOB = ρ0 − ρ1·φ: ρ1 → ρ1·f (1600) |
|
||||
| | `rho_intercept_factor` | 1.0 | ρ0 → ρ0·f (2650) |
|
||||
| | `unit_dt_intercept_sd` | 0.0 | A → A·(1 + sd·ζ_u) theo **từng đơn vị địa tầng** (46 sub-unit của khung S_ref), ζ_u ~ N(0, 1) cấp realization, stream riêng `[rid, 20261029, 1]` |
|
||||
| | `region` | `all` | giếng chịu tác động: `all` \| `test` \| `pool` |
|
||||
| `wavelet` | `phase_deg` | 0.0 | xoay pha hằng (trong họ của registration) |
|
||||
| | `minphase_frac` | 0.0 | s ∈ [0, 1]: phổ pha s·θ_min(f) của phổ biên độ danh nghĩa (cepstral); giữ phổ biên độ; đã bỏ trễ khối bằng cách căn lại tại lag cực đại tương quan chéo với wavelet danh nghĩa |
|
||||
| | `peak_freq_factor` | 1.0 | w(t) → w(p·t): phổ kéo giãn p lần |
|
||||
| | `delay_ms` | 0.0 | trễ khối của wavelet (làm bộ 0,5 ms): sự kiện địa chấn lệch so với anchor |
|
||||
| | `Q` | `null` | suy giảm constant-Q biến thiên theo thời gian so với `Q_t_ref_ms` (áp trong forward, không phải trong wavelet dừng) |
|
||||
| | `Q_t_ref_ms` | 400.0 | thời gian tham chiếu (đỉnh cửa sổ mở rộng); gain exp(−π f Δt/Q), Δt = t′ − t_ref |
|
||||
| | `Q_dispersion` | true | pha Kolsky–Futterman (2 f Δt/Q)·ln(f/f_ref), f_ref = tần số đỉnh của wavelet dừng thật |
|
||||
| `drift` | `sigma_b_factor`, `sigma_g_factor`, `ell_factor` | 1.0 | sự thật rút từ (m_g, σ_g·f, ℓ·f, σ_b·f); cùng z_g, z_b |
|
||||
| | `step_ms` | 0.0 | bước nhảy J của t(τ) ngay dưới `step_horizon`, **không nhân với c** |
|
||||
| | `step_width_ms` | 12.0 | độ rộng (theo τ) của dị thường log-slowness tạo ra bước nhảy |
|
||||
| | `step_horizon` | `Truncation` | tên horizon trong `cfg["horizons"]` |
|
||||
| | `jitter_sd_ms` | 0.0 | jitter Matérn-3/2 của t(τ) trên lưới warp 4 ms, stream riêng `[rid, 20261029, 2, k]` theo giếng |
|
||||
| | `jitter_ell_ms` | 8.0 | độ dài tương quan của jitter |
|
||||
|
||||
Thuộc tính và phương thức mới của realization:
|
||||
|
||||
- `R.misspec` (đã điền mặc định), `R.misspec_active` (chỉ các khóa cường độ khác danh nghĩa; `{}` = danh nghĩa), `R.misspec_info["monotone_repairs"]`.
|
||||
- `R.wavelet`, `R.w_fine`: **wavelet dừng thật** (4 ms / lưới mịn); khi trục wavelet danh nghĩa thì chính là object đầu vào. `R.wavelet_nominal`, `R.w_fine_nominal`: tham chiếu của nhà phân tích. Với Q, `R.w_fine` là wavelet tại t_ref; `R.true_wavelet_at(t_ms)` cho kernel hiệu dụng tại thời gian t. Lưu ý cho runner: scripts/14 dùng `R.w_fine` làm nhánh wavelet "true"; dưới Q không có một wavelet thật duy nhất.
|
||||
- `R.drift_true`, `R.Lg_true`: siêu tham số và Cholesky mà sự thật rút ra (bằng `R.drift`, `R.Lg` khi danh nghĩa).
|
||||
- `R.phi_to_ai_true(phi, unit=None)`: ánh xạ φ → AI thật (bằng `phi_to_ai` khi danh nghĩa); `R.ai_log_true(w, obs)`: AI thật trên trục τ của log (chỉ số đơn vị lấy dọc warp thật); `R.rp_applies(name)`. `obs["ai_log"]` **luôn danh nghĩa**.
|
||||
- `R.true_warp(w, c)` → (b, g) gồm phần GP nhân c và dị thường bước (gộp vào g); `R.true_warp_grid(w, c)` → t(τ) trên lưới gồm cả jitter. `obs["t_of_tau_true"]` luôn là sự thật đầy đủ; `obs["g"]` không chứa jitter (chẩn đoán kiểu `ll_true` từ `[b, g]` sẽ sai khi có jitter).
|
||||
|
||||
## 2. Cái gì là sai mô hình so với giả định của registration
|
||||
|
||||
Registration (`pipeline.register`, SMC ở scripts/14) giả định: (i) `obs["ai_log"]` theo quan hệ F3 danh nghĩa; (ii) wavelet **dừng**, phổ biên độ ước lượng thống kê (128 ms, Hann) từ trace giữa của giếng train, pha **hằng** trên lưới 15° (fit_phase, rồi phase_R qua log Z của SMC), biên độ α ≥ 0 và σ_n profile theo từng mẫu warp; (iii) warp prior Matérn-3/2 với MAP-II cho (m_g, σ_g, ℓ) dưới hyperprior log-normal, σ_a = 7 ms và σ_b = 50 ms cố định, |g| ≤ g_max = 1.
|
||||
|
||||
**Rock physics.** Sai hệ số đồng đều (bốn factor) làm ln AI thay đổi gần **affine** theo φ trên dải φ của D2 (0,20–0,43): với sai 15–20 % hệ số, ln AI đổi 3,9 % mà phần phi affine chỉ 0,56 % của dải ln AI (test `test_rock_physics_uniform_error_is_near_affine`). Vì r ≈ ½ Δln AI và α được profile, synthetic chỉ đổi một hệ số nhân: registration **không thấy** (QC: sai số trong họ 0,072 = danh nghĩa với dt_slope_factor 0,85 hoặc 1,3). SNR cũng không đổi vì nhiễu được chuẩn theo công suất tín hiệu sạch đã sai mô hình. Đây là trục "rock physics sai hệ số" theo nghĩa đen của plan §5.5, và nó là trục rỗng đối với registration; nó được giữ trong preset như một phần của L1/L2 để mô tả đúng plan, còn phần **không** hấp thụ được là `unit_dt_intercept_sd`: matrix slowness khác nhau giữa các đơn vị địa tầng (thạch học) tạo **phản xạ tại biên đơn vị không do φ**, không có trong synthetic danh nghĩa. Với sd = 0,05 (DT_matrix ±9 µs/m, tức vận tốc matrix 5450 → ~5200–5700 m/s) sai số mô hình 0,22; sd = 0,10 → 0,41 (hình (a): bậc thang ln AI_true/AI_nom theo đơn vị). `region: test` chỉ làm sai mô hình ở giếng test: đây là covariate shift cho mạng (câu hỏi của plan §5.5 "φ–DT ở vùng test khác vùng train"), **không** phải câu hỏi của S2 về registration; để sẵn vì rẻ, không khuyến nghị dùng trong S2.
|
||||
|
||||
**Wavelet.** `phase_deg` và `peak_freq_factor` nằm **trong họ**: QC wv_C (45°, ×1,2) cho pha khớp đúng 45° và sai số trong họ 0,050 (26 dB), thậm chí nhỏ hơn danh nghĩa 0,072 vì wavelet ngắn hơn được ước lượng tốt hơn trong 128 ms. Chúng là núm phụ (sanity/kiểm tra họ), không phải trục chính. Ngoài họ: (a) `minphase_frac` — pha phụ thuộc tần số với **cùng** phổ biên độ, nên ước lượng thống kê vẫn đúng biên độ nhưng không pha hằng nào khớp (tương quan tốt nhất 0,82 ở s = 1); (b) `Q` — wavelet biến thiên theo thời gian: một wavelet thống kê là trung bình trên 400–1300 ms nên sai ở cả hai đầu (hình (c): Q = 80 làm tần số đỉnh 59 → 32 Hz từ 600 đến 1100 ms). (c) `delay_ms` — xung đột **hệ thống** giữa địa chấn và anchor (anchor gắn với warp thật; σ_a = 7 ms chỉ mô hình sai số ngẫu nhiên); pha hằng bắt chước một phần (chọn −30°/−75° cho 2/4 ms), phần còn lại 0,24/0,40. Nhiễu `noise_unit` luôn được tạo dạng bằng wavelet danh nghĩa: nhiễu không suy giảm cùng tín hiệu (thực tế) và CRN sạch hơn (chỉ tín hiệu đổi).
|
||||
|
||||
**Drift.** Ba factor rút sự thật từ prior khác: MAP-II hấp thụ một phần (dr_L1: σ_g thật 0,156 → fit 0,133; ℓ thật 36 → fit 91 ms vì hyperprior trung vị 150 ms); σ_b thật 58 ms vượt σ_b = 50 ms cố định của registration ở ×3. Ngoài họ GP: `step_ms` là dị thường log-slowness cục bộ a = ln(1 + J/(Δτ Σ e^{g_i})) trên n_w = round(w/Δτ) nút ngay sau τ_h = t⁻¹(t_h) (bước nhảy **đúng bằng J** dưới dị thường nhờ quy tắc hình thang; ramp trải (n_w + 1) ô lưới bắt đầu từ ô chứa τ_h; t(τ_h) = t_h không đổi; a ≈ 0,50 cho J = 8, w = 12 và 0,85 cho J = 16, đều dưới g_max = 1). Monotone với mọi J > −Δτ Σ e^{g_i} (≈ −12 ms). `jitter` được cộng vào t(τ) chứ không vào g: tích phân của nhiễu ngắn trong g là drift kiểu Brown (tần thấp), không phải jitter; đổi lại jitter không biểu diễn được bằng g. Bảo vệ đơn điệu: nếu Δt giữa hai nút < 0,1·Δτ thì nâng lên (đếm trong `misspec_info`; 0 lần ở mọi mức đã thử). Anchor luôn nhất quán với warp thật: τ_k = t_true⁻¹(t_b), t_k = t_b + σ_a ε_k (kiểm 1e-13 ms trong test).
|
||||
|
||||
## 3. Bảo đảm CRN
|
||||
|
||||
Realization sai mô hình dùng **đúng** stream ngẫu nhiên của realization danh nghĩa, tiêu thụ theo đúng thứ tự: vị trí giếng, φ0, offset đơn vị, GRF từng giếng, nhiễu trắng, z_g, z_b, ε_a — test `_assert_crn` so khớp từng bit `phi_t, noise_unit, z_g, z_b, boundaries_t, eps_a` và tên/vị trí giếng. Hai nguồn ngẫu nhiên **mới** lấy từ stream riêng, gieo bằng rid (và chỉ số giếng cho jitter), chỉ được rút khi núm tương ứng bật, nên không chạm stream danh nghĩa. Hệ quả: trong một ô bench, hiệu số giữa ô sai mô hình và ô danh nghĩa chỉ đến từ phép biến đổi (seismic với rock physics/wavelet; warp với drift), không từ mẫu ngẫu nhiên khác. Sửa test ở `tests/test_d2.py` không cần vì đường danh nghĩa không đổi; test mới ở `tests/test_d2_misspec.py` (15 test, trong đó 3 test fingerprint theo rid, bỏ qua nếu thiếu input hoặc numpy/scipy khác bản ghi 2.5.4/1.18.1).
|
||||
|
||||
## 4. QC trên realization dev 902 (`scripts/33_bench_generator_qc.py`, c = 1, σ_a = 7 ms, địa chấn sạch, 16 giếng pool)
|
||||
|
||||
"Sai số mô hình" = RMS(địa chấn sạch − α·synthetic từ `ai_log` danh nghĩa tại warp thật)/RMS(địa chấn), α profile; "trong họ" = wavelet thống kê từ trace giếng train + pha hằng tốt nhất trên lưới 15°. Quy ra dB tương đương SNR (−20 log10); nhiễu của regime: R10 = 10 dB (tỉ số 0,32), Rm5 = −5 dB (1,78). Mức danh nghĩa: 0,010 với wavelet F3 thật, **0,072 (22,8 dB) trong họ** (sàn của ước lượng thống kê 128 ms).
|
||||
|
||||
| Preset | Khối | Đổi địa chấn (RMS tương đối, cửa sổ chính) | Sai số mô hình, wavelet danh nghĩa | Sai số mô hình **trong họ** (dB) | Ghi chú |
|
||||
|---|---|---|---|---|---|
|
||||
| nominal | — | 0 | 0,010 | 0,072 (22,8) | pha 0° |
|
||||
| rp_C | 4 factor 1,15/1,15/1,2 | 0,037 | 0,012 | 0,073 (22,8) | hấp thụ hoàn toàn; ln AI đổi 0,033 RMS |
|
||||
| rp_L1 | rp_C + unit sd 0,05 | 0,186 | 0,215 | 0,226 (12,9) | ζ_u tới ±1,8 → DT_matrix ±16 µs/m |
|
||||
| rp_L2 | rp_C + unit sd 0,10 | 0,371 | 0,400 | 0,406 (7,8) | |
|
||||
| wv_C | pha 45°, đỉnh ×1,2 | 0,839 | 0,767 | 0,050 (26,0) | pha khớp 45°; trong họ |
|
||||
| wv_L1 | minphase 1,0 | 0,797 | 0,609 | 0,609 (4,3) | tương quan pha hằng tốt nhất 0,82 (13°); SMC chọn 15° |
|
||||
| wv_L2 | wv_L1 + Q 80 | 0,609 | 0,667 | 0,595 (4,5) | đỉnh 59/34/32 Hz tại 600/850/1100 ms; wavelet thống kê đỉnh 36 Hz |
|
||||
| dr_L1 | σ_b ×3, σ_g ×1,5, ℓ ×0,5 | 0 | 0,015 | 0,073 (22,7) | Δwarp RMS 31,9 ms (max 92) chủ yếu do b; Laplace N = 4: RMSE 4,54 ms (danh nghĩa 4,28), z RMS 0,98 |
|
||||
| dr_L2 | bước 8 ms (w 12) + jitter 1 ms (ℓ 8) | 0 | 0,019 | 0,075 (22,5) | bước đạt 8,2 ms trung bình (6,3–10,7 vì đo qua ramp ±σ jitter), τ_h 573–1112 ms, a = 0,50; jitter RMS 0,93; Laplace RMSE 4,57, z RMS 1,26 |
|
||||
|
||||
Quét từng núm (`--sweep`, `outputs/bench/dev/generator_sweep.json`), sai số trong họ: unit sd 0,025/0,05/0,10/0,15 → 0,127/0,217/0,391/0,531 (17,9/13,3/8,2/5,5 dB); dt_slope 0,85 hay 1,3 → 0,072 (= danh nghĩa); minphase 0,25/0,5/0,75/1 → 0,197/0,342/0,486/0,609 (14,1/9,3/6,3/4,3 dB); Q 160/80/40 → 0,259/0,445/0,652 (11,7/7,0/3,7 dB); peak ×0,8/×1,2 → 0,096/0,050; delay 2/4 ms → 0,237/0,399. Drift: bước 4/8/16 ms → Δwarp 3,1/6,1/12,3 ms, Laplace RMSE 4,40/4,62/5,23 ms, z 1,17/1,26/1,47; jitter 0,5/1/2 ms → 0,48/0,97/2,04 ms, RMSE 4,26/4,27/4,46; σ_b ×2/×3/×5 → RMSE 4,08/3,91/3,67 (z 1,06/1,00/0,85); σ_g ×1,5/×2 → 4,65/5,07 (z 0,98/0,83); ℓ ×0,5/×0,25 → 4,03/3,77 (z 1,10/1,13). Kết luận: tie **chỉ anchor** gần như không nhạy với mọi núm drift ở σ_a = 7 ms (sai số anchor che bước nhảy ≤ 16 ms); sai mô hình drift chỉ bộc lộ ở posterior có địa chấn (σ_post ≈ 0,85 ms ở R10, 3 ms ở Rm5), nơi prior trơn (ℓ fit 90–120 ms) không biểu diễn được bước 8 ms trong 12 ms hay jitter ℓ = 8 ms. QC này không chạy SMC; mức drift phải chọn bằng chẩn đoán SMC trên dev (bước tiếp theo).
|
||||
|
||||
Hình `outputs/bench/dev/generator_qc.png`: (a) ln(AI_true/AI_nom) dọc log P00, (b)–(c) wavelet và phổ, (d) đổi warp dọc τ, (e) sai số trong họ theo preset so với mức nhiễu R10/Rm5, (f) tie chỉ anchor.
|
||||
|
||||
### 4b. Registration + SMC trên các preset (`--smc`, cuda:1, một worker; `outputs/bench/dev/smc_qc_rid902.json`)
|
||||
|
||||
Chạy đúng cấu hình P2r cho từng preset và nominal: `pipeline.register` (MAP-II, wavelet thống kê, pha anchor-based phase0, tie B3c/B3d) rồi SMC tie posterior với wavelet phase_R, γ = 1/κ, 1024 hạt, 4 giếng train đầu, c = 1, rid 902 (log `logs/runs/20261029-130144_bench_gen_smc_rid902/`, 18 ô, 32,5 phút; ô R10 khoảng 3 phút vì bước khớp phase_R, ô Rm5 khoảng 45 s). Giá trị là trung bình 4 giếng; warp RMSE/cov90/width90 của trung bình posterior SMC trên cửa sổ chính; r_post = tương quan synthetic tại trung bình posterior với địa chấn.
|
||||
|
||||
| Preset | R10: phase_R | SMC RMSE (ms) | cov90 | width90 (ms) | r_post | B3c / B3d (ms) | Rm5: phase_R | SMC RMSE | cov90 | width90 | r_post | B3c / B3d |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| nominal | −1° | 0,99 | 0,74 | 2,0 | 0,93 | 4,49 / 3,65 | 6° | 2,95 | 0,79 | 8,1 | 0,46 | 6,49 / 3,59 |
|
||||
| rp_C | 4° | 1,02 | 0,69 | 2,1 | 0,92 | 4,49 / 3,65 | −1° | 2,87 | 0,79 | 7,6 | 0,47 | 6,49 / 3,59 |
|
||||
| rp_L1 | 2° | 1,01 | 0,75 | 2,2 | 0,91 | 4,17 / 3,19 | 4° | 3,00 | 0,78 | 7,6 | 0,45 | 6,96 / 3,77 |
|
||||
| rp_L2 | 6° | 1,24 | 0,76 | 3,0 | 0,85 | 5,60 / 3,26 | 1° | 3,07 | 0,81 | 8,2 | 0,41 | 8,26 / 3,60 |
|
||||
| wv_C (thật 45°) | 54° | 0,92 | 0,70 | 1,8 | 0,89 | 3,84 / 3,28 | 48° | 3,62 | 0,85 | 8,6 | 0,38 | 6,81 / 3,47 |
|
||||
| wv_L1 | 78° | **4,22** | **0,04** | 3,0 | 0,81 | 4,18 / 3,13 | 49° | 3,61 | 0,79 | 9,7 | 0,33 | 7,65 / 3,37 |
|
||||
| wv_L2 | 56° | 3,06 | 0,26 | 3,5 | 0,85 | 3,68 / 3,11 | 27° | 3,04 | 0,91 | 10,1 | 0,32 | 7,49 / 3,31 |
|
||||
| dr_L1 | 3° | 2,09 | 0,69 | 4,2 | 0,76 | 4,17 / 3,97 | 2° | 3,07 | 0,90 | 12,5 | 0,23 | 7,88 / 4,28 |
|
||||
| dr_L2 | 0° | 2,22 | 0,64 | 3,7 | 0,79 | 4,15 / 3,81 | −2° | 3,25 | 0,68 | 7,2 | 0,49 | 8,21 / 3,66 |
|
||||
|
||||
Đọc kết quả:
|
||||
|
||||
- **Đối chứng đúng như dự đoán.** rp_C trùng nominal ở cả hai regime (trục "sai hệ số đồng đều" rỗng với registration). wv_C khôi phục pha thật trong một bước lưới (54°/48° so với 45°) và tie tốt như nominal.
|
||||
- **Rock physics có bậc ở R10, không thấy ở Rm5.** sd 0,05 không đổi gì; sd 0,10 tăng RMSE 25 % và width 50 % mà vẫn hiệu chuẩn (cov90 0,76). Ở Rm5 nhiễu che hoàn toàn sai số mô hình (chỉ B3c xấu đi 6,5 → 8,3 ms). Trục này chỉ có lực ở SNR cao.
|
||||
- **Pha phụ thuộc tần số là chế độ thất bại mạnh nhất, và là thất bại kiểu quá tự tin.** wv_L1 ở R10: RMSE 4,22 ms với width90 chỉ 3,0 ms → cov90 0,04, tệ hơn cả tie chỉ anchor B3d (3,13 ms); phase_R trôi tới 78°. Thêm Q (wv_L2) làm giảm thiệt hại (3,06 ms, cov90 0,26) vì suy giảm tần cao bớt phần tán sắc. Ở Rm5 posterior đủ rộng nên vẫn hiệu chuẩn (0,79–0,91) và RMSE chỉ tăng nhẹ (2,95 → 3,6). Hệ quả cho T4/Mệnh đề 5: đây là cơ chế tạo posterior lệch nhưng hẹp, khác hẳn trục drift.
|
||||
- **Drift làm tăng sai số và độ rộng mà vẫn hiệu chuẩn.** dr_L1 và dr_L2 ở R10: RMSE gấp đôi (2,1–2,2 ms), width gấp đôi, cov90 0,64–0,69. Ở Rm5 dr_L1 làm posterior quá rộng (width 12,5 ms, cov90 0,90), dr_L2 hơi quá hẹp (0,68). Khác với tie chỉ anchor (mục 4), SMC thấy rõ hai mức này.
|
||||
- phase0 (pha từ anchor) dao động −45°…75° dù pha thật 0°, nhắc lại vì sao P2 thất bại; chỉ phase_R có nghĩa.
|
||||
|
||||
## 5. Quyết định còn mở cho giai đoạn dev (902–905), trước khi khóa protocol
|
||||
|
||||
1. **Mức (sau 4b).** Rock physics: rp_L1 hiện tại (sd 0,05) là ô rỗng với SMC ở cả hai regime; đề nghị L1 = sd 0,10 (mức đầu tiên SMC thấy ở R10), L2 = sd 0,15 (sai số mô hình 0,53), và ghi trước rằng trục này được kỳ vọng rỗng ở Rm5. Wavelet: minphase 1,0 là mức "gãy" (posterior lệch 4 ms, cov90 0,04 ở R10); đề nghị L1 = minphase 0,5 (sai số mô hình 0,34 ≈ nhiễu R10) để có đáp ứng có bậc, L2 = minphase 1,0; Q nên là một ô riêng (cơ chế biến thiên theo thời gian) thay vì gộp vào L2, vì gộp làm giảm thiệt hại của tán sắc. Drift: dr_L1 và dr_L2 đã có bậc vừa phải (RMSE ×2, vẫn hiệu chuẩn) và có thể giữ; nếu cần một mức mạnh hơn thì bước 16 ms (a = 0,85). Mọi mức chốt trên 902–905 (lặp `--smc` trên 903–905, mỗi rid khoảng 30 phút một worker) rồi ghi vào protocol_bench cùng luật đạt; sau khi khóa không đổi.
|
||||
2. **Trục rock physics.** Không dùng ô "chỉ sai hệ số đồng đều" làm ô chính (trục rỗng với registration; giữ rp_C làm bằng chứng trong bài). Giữ các factor đồng đều bên trong L1/L2 để bám câu chữ của plan hay bỏ hẳn cho sạch: cần một quyết định ghi vào protocol.
|
||||
3. **Trục drift.** Hai mức hiện là hai cơ chế (siêu tham số sai; thành phần ngoài GP). Cần chọn: giữ như vậy (dễ quy kết) hay làm hai cường độ của cùng tổ hợp. Bước nhảy không nhân với c, nên ở c = 0 ô drift sẽ không còn là "không drift"; S2 chỉ chạy c = 1 nên không ảnh hưởng, nhưng protocol phải nói rõ.
|
||||
4. **Núm phụ.** `phase_deg`, `peak_freq_factor` (trong họ) và `delay_ms`, `region` để làm kiểm tra bổ sung hoặc bỏ; nếu dùng `delay_ms` thì phải nói rõ đó là xung đột anchor–địa chấn, không phải "sai pha". `Q_dispersion` ảnh hưởng ít (Q 80: 0,517 có tán sắc so với 0,487 không, với wavelet danh nghĩa).
|
||||
5. **Runner.** Nhánh wavelet "true" phải dùng `R.w_fine` (wavelet dừng thật) và ghi chú rằng dưới Q không có wavelet thật duy nhất; chẩn đoán từ `[b, g]` không hợp lệ khi có jitter; protocol phải ghi nguyên văn dict preset đã chuẩn hóa, SHA-256 của `configs/d2_synth_bench.yaml`, và đối chiếu fingerprint danh nghĩa.
|
||||
6. **Dev.** Mọi thiết kế chỉ trên 902–905; QC từ chối rid ngoài tập này; realization 8–15 không được chạy trước khi khóa.
|
||||
7. **Bài.** Khi viết, nói rõ trục rock physics của plan §5.5 theo nghĩa đen là bất biến với likelihood có α profile (một kết quả nhỏ nhưng đáng ghi), và rằng các mức được chọn sau khi xem dev 902–905 (thiết kế sau P2r, không phải confirmatory trừ khi luật đạt được ghi trước trong protocol_bench).
|
||||
|
||||
## 6. Tệp
|
||||
|
||||
- `ml_porosity/data/synth_d2.py`: `MISSPEC_DEFAULTS`, `normalize_misspec`, `active_axes`, `preset_misspec`, `phi_to_ai_coef`, `fractional_minimum_phase`, `true_stationary_wavelet`, `q_kernel`, `forward_fine_q`, các phương thức mới của `D2Realization`.
|
||||
- `configs/d2_synth_bench.yaml`: bộ sinh = p2r + `regimes` (sao chép) + `misspec_presets` (placeholder).
|
||||
- `tests/data/d2_fingerprints.json`, `tests/test_d2_misspec.py`.
|
||||
- `scripts/33_bench_generator_qc.py` → `outputs/bench/dev/{generator_qc.json, generator_qc.png, generator_sweep.json, smc_qc_rid902.json}` (không theo dõi trong git); `--smc` chạy registration + SMC trên GPU (`--device cuda:1`, một worker, cap 2 GiB) hoặc `--device cpu` khi GPU đầy; nối tiếp theo ô đã xong.
|
||||
247
docs/research/bench-protocol.md
Normal file
247
docs/research/bench-protocol.md
Normal file
@@ -0,0 +1,247 @@
|
||||
# protocol_bench: runner, hiệu chuẩn mức sai mô hình, tái lập P2r và bản nháp giao thức
|
||||
|
||||
Ngày viết: **29/10/2026** (phase P6, mức B; plan §12 ý 22 và 26; lịch §6.1 dự kiến 2–3/11, làm sớm). Trạng thái: **ĐÃ KHOÁ 14:39:20 UTC 29/10/2026** sau khi điều phối duyệt bản nháp và yêu cầu 7 sửa đổi (mục 1.4); `configs/protocol_bench.sha256` = `aa763f0a4f81125ea8441fdfba4361f68246c7a0be1c36d4bf8de2650a91a4c5`, `configs/protocol_bench.lock.json` (code `5ea2eb17…`, torch 2.14.0+cu130, 8 input, 102 artifact P2r, fingerprint rid 8/902 khớp). Chưa chạy ô chính nào; chưa commit. Tài liệu này ghi (1) thiết kế runner `ml_porosity/benchmark/` và CLI, (2) kết quả kiểm tra tái lập P2r qua runner mới, (3) hiệu chuẩn mức L1/L2 của ba trục sai mô hình trên realization dev, (4) tóm tắt giao thức `configs/protocol_bench.yaml` (ô, giả thuyết, luật), (5) ước tính chi phí và phân bổ GPU, (6) tác dụng phụ lên hash code của lock F3/Volve, (7) rủi ro còn mở. Mục 2 và 3 được điền khi có số; mọi số dev đều ghi rõ rid, N, regime.
|
||||
|
||||
Liên quan: `docs/research/pivot-theory-benchmark.md` §2.2 (S1–S8) và §6; `docs/research/bench-generator.md` (bộ sinh misspec, QC rid 902); `configs/protocol_p2r.yaml` (khoá; nguồn của regime, phương pháp, ngân sách, luật); `configs/protocol_p2.yaml` (khoá; registration, training, metric); bản đồ code của phase 1 (scratchpad `bench-code-map.md`, không theo dõi trong git).
|
||||
|
||||
---
|
||||
|
||||
## 1. Runner `ml_porosity/benchmark/` và CLI
|
||||
|
||||
### 1.1 Mô-đun
|
||||
|
||||
| Mô-đun | Vai trò | Mẫu theo |
|
||||
| --- | --- | --- |
|
||||
| `protocol.py` | `load_protocol` (kiểm hash input), `current_stamp` (protocol, code `ml_porosity/**/*.py` + `scripts/34_run_bench.py` + `scripts/run_bench.sh` + `pyproject.toml`, môi trường, input, artifact P2r tham chiếu, fingerprint bộ sinh danh nghĩa của rid 8 và 902), `freeze(check)` (khoá `.lock.json` + `.sha256`; từ chối khoá lần đầu nếu `outputs/bench/{s1,s2,s3,s4,s8,summary}` đã tồn tại, nếu còn `sha256: TBD` hoặc `status: DRAFT`), `check_rids` (rid 8–15 chỉ khi lock khớp; 900–905 chỉ với `--dev`; 0–7 luôn từ chối; không trộn), `dev_stamp` (khoá resume dev: chỉ protocol + bộ sinh), `fingerprint` | `ml_porosity/volve/protocol.py`, `scripts/11 check_rids` |
|
||||
| `data.py` | `Inputs` (cfg bộ sinh, horizon grid, prior warp, wavelet, khối registration/training/metric của protocol_p2 qua `scripts/11 reg_settings`), `Inputs.realization(rid, preset)` (`D2Realization(..., misspec=preset_misspec(cfg, preset))`), `Inputs.observe` (giếng train = `pool[:N]` với anchor theo regime, 8 giếng test cùng SNR), `fingerprint_realization` (đúng hàm của `tests/test_d2_misspec.py`) | scripts 14/15 |
|
||||
| `cells.py` | `Cell(study, regime, preset, c, N, rid, methods, backbone, posterior, delta_ms)`; liệt kê ô của S1/S2/S3/S4/S8 từ khối `studies:`; đường dẫn phẳng: posterior dùng chung theo setting `outputs/bench/posterior/<regime[__preset]>/r{rid}_c{c}_n{N}_s0{.csv,_particles.npz,_phase.json,.json}` (cùng layout P2r), train `outputs/bench/<study>/train/<setting>/cells/r{rid}_c{c}_n{N}[_d{Δ}][__tcn]{.csv,.npz,_diag.csv,.json}`; `--dev` → gốc `outputs/bench/dev/`, `repro` → `outputs/bench/repro/` | `volve/runner.py` reg_path/job_path |
|
||||
| `registration.py` | `posterior_cell`: đúng `scripts/14 run_job` thu hẹp về nhánh estR mà P2r dùng; cùng stream ngẫu nhiên (`[k, i, 13]` mẫu anchor, `[k, 19]` fit pha, `[k, i, 17]` SMC), cùng ba mốc γ (g_old, g_acf, g_one; mốc đổi lịch tôi luyện nên giữ nguyên), chỉ lưu hạt g_acf (P2r còn lưu g_one, không phương pháp nào dùng) | scripts/14 |
|
||||
| `training.py` | `train_cell`: đúng `scripts/15 run_cell` biến thể "a" (B3c-R, B3d-Sa, M2-Sa từ hạt; `run_d2.method_specs` cho Oracle/B3*/B4*/M*); thêm bank hai mode S8 (`two_mode_banks`), backbone TCN (`train_predict_tcn`, vòng lặp của `bank_train.train_predict` với `TCNHetero` và cờ cudnn deterministic như `f3.make_model`); nhánh CNN-GRU uỷ quyền nguyên vẹn cho `bank_train.train_predict` (không sửa `bank_train.py`/`rml.py` của T2) | scripts/15, `f3/training.py` |
|
||||
| `runner.py` | job theo ô, pool `spawn`, `wait(FIRST_COMPLETED)` với ETA, fail-fast; sidecar `.json` mang fingerprint + SHA-256 artifact; `reusable` bỏ qua job khớp, **raise** nếu lệch (gốc output mới); `progress.json`; sắp xếp N lớn trước | `volve/runner.py` |
|
||||
| `summary.py` | mọi phân tích đã khai báo (mục 4) dùng `scripts/13 gate_gb/boot` và luật cặp của `scripts/18`; đọc P2r cho ô có sẵn | scripts 13/18 |
|
||||
| `repro.py` | so sánh ô tái lập với `outputs/p2r` (pha, hạt, chẩn đoán warp, metric train, dự đoán) → `outputs/bench/repro/comparison.json` | — |
|
||||
| `devbudgets.py` | ngân sách TCN trên dev theo đúng luật `budget_selection` của protocol_p2 | scripts/11 `select_budgets` |
|
||||
|
||||
### 1.2 CLI và driver
|
||||
|
||||
```
|
||||
scripts/34_run_bench.py <stage…> [--studies S1 S2 S3 S4 S8] [--device cuda:0] [--workers 4] [--gpu-mem-gb 6] [--threads 2]
|
||||
[--regimes …] [--presets …] [--controls] [--rids …] [--dev] [--drift …] [--n-train …] [--seeds …]
|
||||
stages: status | lock | posterior | train | summarize | repro | dev-budgets | all
|
||||
scripts/run_bench.sh <stage…> # bọc runlog; env DEVICE WORKERS THREADS MEM_GB STUDIES REGIMES PRESETS RIDS DEV CONTROLS EXTRA
|
||||
```
|
||||
|
||||
- `--dev`, `--drift`, `--n-train`, `--seeds` chỉ dành cho dev (900–905); với `--drift/--n-train` S1 bỏ loại trừ ô P2r (để chạy posterior danh nghĩa c = 1, N = 4/16 trên dev).
|
||||
- `repro` chạy đúng một ô (`reproduction:` của protocol) trước khi khoá, ghi vào `outputs/bench/repro/`, không phải kết quả.
|
||||
- Mọi lần chạy dài: `setsid nohup scripts/run_bench.sh … > logs/bench_<x>.out 2>&1 &`.
|
||||
- Luồng: `OMP/MKL/OPENBLAS/NUMEXPR/NUMBA_NUM_THREADS` đặt tường minh (mặc định 2/worker), `PYTHONHASHSEED=0`, `CUBLAS_WORKSPACE_CONFIG=:4096:8` như `scripts/24`.
|
||||
- Test: `tests/test_bench.py` (11 test: nhất quán protocol, đếm ô, đường dẫn, guard, fingerprint, TCN trên CPU, bank hai mode S8, bank đối chứng Ctl-GP, danh sách ngân sách với nhánh 500, fingerprint danh nghĩa, luật tổng hợp trên dữ liệu giả). Toàn bộ `tests/`: 216 pass, 1 skip (CUDA ẩn) sau khi sửa `tests/test_d2_misspec.py` cho tên preset `cand_*`.
|
||||
- `scripts/35_bench_calibration.py`: bảng hiệu chuẩn từ `outputs/bench/dev/smc_qc_rid*.json` → `outputs/bench/dev/calibration.{csv,md}`.
|
||||
|
||||
### 1.3 Lệnh khoá (đã chạy 14:39 UTC, runlog `20261029-143914_bench_lock`) và lệnh chạy chính (điều phối khởi động 14:43 UTC bằng setsid nohup với ít worker hơn; bị SIGTERM 15:27 khi phiên agent kết thúc; chạy lại 15:41 UTC trong tmux, xem plan §12 ý 26. Lệnh dưới đây là mẫu: hãy bọc bằng `tmux new-session -d` thay cho `setsid nohup`)
|
||||
|
||||
```bash
|
||||
# 0. (sau khi duyệt) trong configs/protocol_bench.yaml: (a) đổi status thành "LOCKED 2026-11-0x"; (b) điền training.budgets_tcn
|
||||
# từ outputs/bench/dev/budgets_tcn.json (stage dev-budgets, đang chạy lúc bàn giao) hoặc để null = budget-matched (phải nói trong bài);
|
||||
# (c) nếu có sửa configs/d2_synth_bench.yaml sau bàn giao thì cập nhật inputs.d2_config.sha256:
|
||||
.venv/bin/python -c "from ml_porosity.f3.protocol import digest; from pathlib import Path; print(digest(Path('configs/d2_synth_bench.yaml'), True))"
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python -m pytest -q -p no:cacheprovider tests/test_bench.py tests/test_d2_misspec.py tests/test_protocol.py
|
||||
# 1. khoá (từ chối nếu còn DRAFT/TBD, nếu outputs/bench/{s1,s2,s3,s4,s8,summary} đã tồn tại, nếu fingerprint danh nghĩa rid 8/902 lệch)
|
||||
scripts/run_bench.sh lock # = .venv/bin/python -m ml_porosity.runlog -n bench_lock -- .venv/bin/python scripts/34_run_bench.py lock
|
||||
# 2. chạy chính (hai GPU, tách phiên); bộ nhớ đo được: worker SMC 1 556 MiB ở N = 16 (cap không chạm), worker train ≈ 710 MiB
|
||||
setsid nohup env STUDIES="S1" REGIMES="R10 Rm5 R0h" DEVICE=cuda:0 WORKERS=4 MEM_GB=6 scripts/run_bench.sh posterior train > logs/bench_s1_cuda0.out 2>&1 &
|
||||
setsid nohup env STUDIES="S1" REGIMES="R0 R10tb" DEVICE=cuda:1 WORKERS=4 MEM_GB=6 scripts/run_bench.sh posterior train > logs/bench_s1_cuda1.out 2>&1 &
|
||||
setsid nohup env STUDIES="S2" REGIMES="R10" DEVICE=cuda:0 WORKERS=4 MEM_GB=6 scripts/run_bench.sh posterior train > logs/bench_s2_cuda0.out 2>&1 &
|
||||
setsid nohup env STUDIES="S2" REGIMES="Rm5" DEVICE=cuda:1 WORKERS=4 MEM_GB=6 scripts/run_bench.sh posterior train > logs/bench_s2_cuda1.out 2>&1 &
|
||||
setsid nohup env STUDIES="S3 S4 S8" DEVICE=cuda:1 WORKERS=4 scripts/run_bench.sh train > logs/bench_s348_cuda1.out 2>&1 &
|
||||
scripts/run_bench.sh summarize
|
||||
```
|
||||
|
||||
### 1.4 Sửa theo review của điều phối trước khi khoá (29/10, 14:15–14:39 UTC)
|
||||
|
||||
1. S2-H2: "12 cặp" → **14 cặp** (7 preset × 2 regime; `summary.py` đếm `len(regimes) × Σ preset` = 14).
|
||||
2. S2-H1 `prediction`: số lấy đúng từ `calibration.md` (wv_L1: ×3.2 = 2.14 ms, cov90 0.11, B3c 4.30 ms, 4/4 rid; wv_L2: 3.93 ms, cov90 0.03, 3/4 rid; dr_L1/L2 1.55/2.27 ms so với B3c 3.48/4.52).
|
||||
3. `calibration.procedure`: trục drift viết lại thành **hai cơ chế riêng** (dr_L1 siêu tham số trong họ GP; dr_L2 thành phần ngoài họ GP), bỏ câu "quy kết bằng hiệu".
|
||||
4. `calibration.levels_vs_declared_band`: nêu rõ rp_L1 vượt dải L1 (0.5–1.0 × nhiễu R10) **+24 %** (1.24 ×) và wv_L1 **+8 %** (1.08 ×), lý do (registration mù với trục rock physics nên 0.075 ≈ danh nghĩa; không có mức pha "ôn hoà"); chọn phương án (b) giữ 0.10 và 0.5; phương án (a) đã cân nhắc và bác.
|
||||
5. `reproduction.result`: ghi "bitwise exact" kèm con trỏ `outputs/bench/repro/comparison.json`.
|
||||
6. `rules.multiplicity`: 9 claim, 11 verdict (S2-H1 theo trục), không hiệu chỉnh family-wise, báo mọi verdict kể cả trượt.
|
||||
7. `training.budgets_tcn` điền từ `outputs/bench/dev/budgets_tcn.json` (stage `dev-budgets`, wall 1:03:53, 4 rid × 2 N × 2 seed): luật budget_selection của protocol_p2 chọn **125 cho mọi phương pháp TCN** — RMSE tổng tăng đơn điệu theo số vòng lặp (B3d-Sa-TCN 1.406/1.428/1.482/1.537/1.592; M2-Sa-TCN 1.389/1.429/1.469/1.521/1.616; Oracle-TCN 1.393/…/1.604); cực tiểu nằm ở biên danh sách ứng viên, danh sách giữ nguyên như protocol_p2 (không thêm ứng viên nhỏ hơn sau khi xem dev); ghi rõ trong protocol.
|
||||
|
||||
Sau sửa: `pytest tests/test_bench.py tests/test_d2_misspec.py tests/test_protocol.py` 31 pass; toàn bộ `tests/` 216 pass, 1 skip; `scripts/run_bench.sh lock` thành công; `freeze(check=True)` khớp lock; `check_rids([8..15])` chấp nhận realization chính, vẫn từ chối rid dev không có `--dev`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Kiểm tra tái lập P2r qua runner mới
|
||||
|
||||
Ô `reproduction:` của protocol: R10, rid 8, c = 1, N = 4 — chạy **lại từ đầu** qua `scripts/34_run_bench.py repro` (posterior SMC với P = 1024, mốc γ (g_old, g_acf, g_one), rồi huấn luyện 7 phương pháp × 5 seed ở ngân sách P2r) trên cuda:1 (1 worker, `--gpu-mem-gb 3`; runlog `20261029-133329_bench_repro_r8`, wall 3:48: posterior 142 s, train 73 s), so với `outputs/p2r/posterior/R10/r8_c1_n4_s0*` và `outputs/p2r/train/R10/cells/r8_c1_n4.*`. Kết quả (`outputs/bench/repro/comparison.json`):
|
||||
|
||||
| Đại lượng | Sai lệch tuyệt đối lớn nhất | Ghi chú |
|
||||
| --- | --- | --- |
|
||||
| phase0 (đăng ký anchor) | 0 (0.0° = 0.0°) | `register()` CPU |
|
||||
| phase_R (fit pha qua log Z của SMC) | 0 (-0.990696378084 = P2r) | lưới 7 nút, GPU |
|
||||
| log Z theo pha × giếng | 0.0 | |
|
||||
| hạt SMC tại γ = 1/κ, 4 giếng × (1024 × 390) | 0 — **trùng từng bit** | `particles_bitwise = true` |
|
||||
| warp RMSE / cov90 / width90 / κ_post / r_post của mọi dòng CSV | 0 | số stage 17/17/17/18 trùng |
|
||||
| metric train theo (phương pháp, seed, giếng test), 280 dòng: band RMSE, RMSE, band PCC, NLL, coverage90 | 0 | |
|
||||
| dự đoán μ (35 mảng 8 × 126) và y_true | trùng từng bit | `pred_bitwise = true` |
|
||||
| `_diag.csv`: B3c-R / B3d-Sa warp RMSE, λ, phase_R, M2-Sa n_valid | 0 | |
|
||||
|
||||
Band RMSE trung bình ô (mới = P2r): B3b 0.9667, B3c 0.5755, B3c-R 0.6022, B3d 0.7475, B3d-Sa 0.5380, M2-Sa 0.5289, Oracle 0.5577 p.u.
|
||||
|
||||
**Kết luận.** Đường mặc định của runner (bộ sinh với `misspec=None`, `register`, SMC GPU, bank nhãn, huấn luyện CNN-GRU qua `bank_train.train_predict`) tái lập P2r **chính xác từng bit** trên H200 với torch 2.14.0+cu130 (khớp self-check của T2: 10.560 dòng, sai lệch 0). Vì guard của P2r không băm code, đây là bằng chứng rằng các sửa code của P6 (misspec trong `synth_d2.py`, `on_budget`/`responsibilities` của T2, gói `benchmark/`) không đổi đường chạy đã đăng ký. Giới hạn: một ô, một GPU, một môi trường; bit-equality của SMC trên GPU không được bảo đảm nói chung (smc_torch khớp CPU đến sai số làm tròn; chọn/loại ở ties có thể lệch) — ở đây không xảy ra.
|
||||
|
||||
Kiểm tra phụ (dev rid 902, R10, c = 1, N = 4): runner và `scripts/33 --smc` cho **cùng** phase_R (−0.5323048335…) nhưng hạt khác nhau (warp RMSE P00 0.704 so với 0.744 ms; 17 so với 12 stage) vì scripts/33 chạy SMC với một mốc γ duy nhất (g_acf) còn runner/P2r dùng ba mốc; mốc đổi lịch tôi luyện. Các số hiệu chuẩn ở mục 3 vì vậy ở "lịch một mốc"; mức được chọn theo tỉ số so với danh nghĩa dưới cùng lịch.
|
||||
|
||||
---
|
||||
|
||||
## 3. Hiệu chuẩn mức L1/L2 của S2 trên dev
|
||||
|
||||
**Cách làm.** Với mỗi ứng viên (khối `misspec_presets` của `configs/d2_synth_bench.yaml`, kể cả `cand_*`), chạy đúng registration của P2r trên dev: `pipeline.register` (MAP-II, wavelet thống kê, pha hằng) rồi SMC GPU (P = 1024, nhánh estR, γ = 1/κ; `scripts/33_bench_generator_qc.py --smc`, lịch **một mốc** γ — xem lưu ý ở mục 2) ở N = 4, c = 1, hai regime R10 và Rm5, trên realization dev 902 (mọi preset), 903 (các ứng viên), 904 và 905 (xác nhận 7 preset đã chọn). Bảng gộp: `scripts/35_bench_calibration.py` → `outputs/bench/dev/calibration.{csv,md}` (hàng nhận diện theo núm đang bật, vì tên preset đã được định nghĩa lại trong ngày). "Sai số mô hình trong họ" = RMS(địa chấn sạch − α·synthetic danh nghĩa tại warp thật)/RMS(địa chấn) với thành viên tốt nhất của họ wavelet thống kê + pha hằng (QC rid 902, `bench-generator.md` §4); nhiễu regime: R10 0.316, Rm5 1.778. Các log: `logs/bench_cal_smc_rid90{2,2b,3,4,5}.out`, runlog `bench_cal_smc_rid*`.
|
||||
|
||||
**Mục tiêu khai báo trước khi xem số** (`calibration.procedure` của protocol): L1 — sai số mô hình trong họ ≈ 0.5–1.0 × nhiễu R10 và SMC vẫn trước point tie ở R10; L2 — ≈ 1.5–2 × nhiễu R10, kèm mất hiệu chỉnh thấy được (cov90 < 0.5 ở R10 hoặc warp RMSE ≥ 2 × danh nghĩa). Trục rock physics chỉ dùng độ phân tán intercept theo đơn vị (các hệ số đồng đều bất biến với likelihood có α profile; `rp_C` giữ làm control). Thầy QC bộ sinh (chuyển qua điều phối) đề nghị: rp 0.10/0.15, wv minphase 0.5/1.0 với Q thành ô riêng, dr giữ hai preset; quyết định cuối ở dưới.
|
||||
|
||||
### 3.1 Bảy preset đã chọn — R10 (N = 4, c = 1; trung bình trên rid × 4 giếng train)
|
||||
|
||||
| Preset | Núm | n_rid | Sai số mô hình trong họ (÷ nhiễu regime) | SMC warp RMSE (ms) | ÷ danh nghĩa | cov90 | σ_post (ms) | overconf. | B3c warp RMSE | SMC < B3c (tỉ lệ rid) | r_post |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| nominal | `{}` | 4 | 0.072 (0.23) | 0.69 | 1.00 | 0.83 | 0.56 | 1.25 | 3.97 | 1.00 | 0.89 |
|
||||
| rp_L1 | `{"rock_physics": {"unit_dt_intercept_sd": 0.1}}` | 3 | 0.391 (1.24) | 0.76 | 1.27 | 0.85 | 0.69 | 1.14 | 4.34 | 1.00 | 0.84 |
|
||||
| rp_L2 | `{"rock_physics": {"unit_dt_intercept_sd": 0.15}}` | 4 | 0.531 (1.68) | 1.17 | 1.66 | 0.81 | 0.91 | 1.31 | 4.83 | 1.00 | 0.79 |
|
||||
| wv_L1 | `{"wavelet": {"minphase_frac": 0.5}}` | 4 | 0.342 (1.08) | 2.14 | 3.24 | 0.11 | 0.63 | 3.49 | 4.30 | 1.00 | 0.85 |
|
||||
| wv_L2 | `{"wavelet": {"minphase_frac": 1.0}}` | 4 | 0.609 (1.93) | 3.93 | 5.92 | 0.03 | 0.82 | 4.94 | 4.57 | 0.75 | 0.76 |
|
||||
| wv_Q | `{"wavelet": {"Q": 80.0}}` | 4 | 0.445 (1.41) | 1.06 | 1.57 | 0.84 | 0.98 | 1.08 | 3.42 | 1.00 | 0.86 |
|
||||
| dr_L1 | `{"drift": {"ell_factor": 0.5, "sigma_b_factor": 3.0, "sigma_g_factor": 1.5}}` | 4 | 0.073 (0.23) | 1.55 | 2.22 | 0.75 | 1.08 | 1.43 | 3.48 | 1.00 | 0.66 |
|
||||
| dr_L2 | `{"drift": {"jitter_sd_ms": 1.0, "step_ms": 8.0}}` | 4 | 0.075 (0.24) | 2.27 | 3.29 | 0.61 | 0.85 | 2.74 | 4.52 | 1.00 | 0.80 |
|
||||
|
||||
### 3.2 Bảy preset đã chọn — Rm5
|
||||
|
||||
| Preset | Núm | n_rid | Sai số mô hình trong họ (÷ nhiễu regime) | SMC warp RMSE (ms) | ÷ danh nghĩa | cov90 | σ_post (ms) | overconf. | B3c warp RMSE | SMC < B3c (tỉ lệ rid) | r_post |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| nominal | `{}` | 4 | 0.072 (0.04) | 3.68 | 1.00 | 0.76 | 2.43 | 1.54 | 6.77 | 1.00 | 0.42 |
|
||||
| rp_L1 | `{"rock_physics": {"unit_dt_intercept_sd": 0.1}}` | 3 | 0.391 (0.22) | 4.03 | 1.04 | 0.73 | 2.44 | 1.70 | 6.52 | 1.00 | 0.39 |
|
||||
| rp_L2 | `{"rock_physics": {"unit_dt_intercept_sd": 0.15}}` | 4 | 0.531 (0.30) | 3.91 | 1.08 | 0.75 | 2.58 | 1.57 | 7.09 | 1.00 | 0.37 |
|
||||
| wv_L1 | `{"wavelet": {"minphase_frac": 0.5}}` | 4 | 0.342 (0.19) | 3.87 | 1.06 | 0.76 | 2.59 | 1.50 | 7.27 | 1.00 | 0.36 |
|
||||
| wv_L2 | `{"wavelet": {"minphase_frac": 1.0}}` | 4 | 0.609 (0.34) | 4.30 | 1.23 | 0.71 | 2.85 | 1.51 | 7.28 | 1.00 | 0.30 |
|
||||
| wv_Q | `{"wavelet": {"Q": 80.0}}` | 4 | 0.445 (0.25) | 4.08 | 1.12 | 0.71 | 2.43 | 1.68 | 6.05 | 1.00 | 0.41 |
|
||||
| dr_L1 | `{"drift": {"ell_factor": 0.5, "sigma_b_factor": 3.0, "sigma_g_factor": 1.5}}` | 4 | 0.073 (0.04) | 3.90 | 1.10 | 0.83 | 3.27 | 1.24 | 7.16 | 1.00 | 0.15 |
|
||||
| dr_L2 | `{"drift": {"jitter_sd_ms": 1.0, "step_ms": 8.0}}` | 4 | 0.075 (0.04) | 4.21 | 1.18 | 0.66 | 2.37 | 1.79 | 7.29 | 1.00 | 0.41 |
|
||||
|
||||
### 3.3 Ứng viên đã xét và không chọn (R10)
|
||||
|
||||
| Ứng viên | Núm | n_rid | Sai số trong họ (÷ nhiễu) | SMC warp RMSE | ÷ danh nghĩa | cov90 | σ_post | overconf. |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| cand_dr_hs | `{"drift": {"ell_factor": 0.5, "jitter_sd_ms": 1.0, "sigma_b_factor": 3.0, "sigma_g_factor": 1.5, "step_ms": 8.0}}` | 2 | — | 2.86 | 3.52 | 0.61 | 1.33 | 2.16 |
|
||||
| cand_dr_s2 | `{"drift": {"jitter_sd_ms": 2.0, "step_ms": 16.0}}` | 2 | — | 4.25 | 5.26 | 0.60 | 2.07 | 2.09 |
|
||||
| cand_rp_a | `{"rock_physics": {"unit_dt_intercept_sd": 0.05}}` | 1 | 0.217 (0.69) | 0.93 | 1.34 | 0.59 | 0.50 | 1.84 |
|
||||
| cand_rp_d | `{"rock_physics": {"unit_dt_intercept_sd": 0.075}}` | 1 | — | 1.08 | 1.09 | 0.76 | 0.76 | 1.41 |
|
||||
| cand_wv_b | `{"wavelet": {"Q": 160.0}}` | 2 | 0.259 (0.82) | 0.92 | 1.08 | 0.79 | 0.64 | 1.41 |
|
||||
| cand_wv_e | `{"wavelet": {"Q": 160.0, "minphase_frac": 0.5}}` | 2 | — | 1.72 | 2.06 | 0.32 | 0.67 | 2.58 |
|
||||
| cand_wv_f | `{"wavelet": {"minphase_frac": 0.25}}` | 1 | 0.197 (0.62) | 1.92 | 1.95 | 0.25 | 0.64 | 3.01 |
|
||||
| cand_wv_g | `{"wavelet": {"Q": 40.0}}` | 1 | 0.652 (2.06) | 1.60 | 1.63 | 0.86 | 1.59 | 1.01 |
|
||||
| cand_wv_h | `{"wavelet": {"Q": 80.0, "minphase_frac": 0.5}}` | 1 | — | 1.67 | 1.69 | 0.63 | 0.98 | 1.71 |
|
||||
| rp_C | `{"rock_physics": {"dt_intercept_factor": 1.15, "dt_slope_factor": 1.15, "rho_slope_factor": 1.2}}` | 1 | 0.073 (0.23) | 1.02 | 1.04 | 0.69 | 0.63 | 1.62 |
|
||||
| rp_L1 (old definition) | `{"rock_physics": {"dt_intercept_factor": 1.15, "dt_slope_factor": 1.15, "rho_slope_factor": 1.2, "unit_dt_intercept_sd": 0.05}}` | 1 | 0.226 (0.71) | 1.01 | 1.02 | 0.75 | 0.67 | 1.49 |
|
||||
| rp_L2 (old definition) | `{"rock_physics": {"dt_intercept_factor": 1.15, "dt_slope_factor": 1.15, "rho_slope_factor": 1.2, "unit_dt_intercept_sd": 0.1}}` | 1 | 0.406 (1.28) | 1.24 | 1.26 | 0.76 | 0.91 | 1.37 |
|
||||
| wv_C | `{"wavelet": {"peak_freq_factor": 1.2, "phase_deg": 45.0}}` | 1 | 0.050 (0.16) | 0.92 | 0.93 | 0.70 | 0.53 | 1.72 |
|
||||
| wv_L2 (old definition) | `{"wavelet": {"Q": 80.0, "minphase_frac": 1.0}}` | 1 | 0.595 (1.88) | 3.06 | 3.11 | 0.26 | 1.08 | 2.84 |
|
||||
|
||||
(Ở Rm5 mọi ứng viên nằm trong 0.97–1.33 × danh nghĩa; bảng đầy đủ trong `calibration.md`.)
|
||||
|
||||
### 3.4 Quyết định và lý do
|
||||
|
||||
1. **Rock physics: rp_L1 = unit sd 0.10, rp_L2 = 0.15.** Sai số mô hình 1.24× và 1.68× nhiễu R10. Trục này **gần như vô hình với registration**: SMC warp RMSE chỉ ×1.27 / ×1.66 danh nghĩa, cov90 giữ 0.85 / 0.81 (4 rid), nên mục tiêu "mất hiệu chỉnh" của L2 không đạt được trong dải vật lý hợp lý (sd 0.15 = DT_matrix ±27 µs/m, tức matrix 4 500–6 400 m/s); các mức 0.05/0.075 không khác biệt đủ. Mức được chọn theo sai số mô hình (như đề nghị); phát hiện "registration bền với rock physics sai hệ số ở R10" tự nó là một kết quả của S2. **Null khai báo trước ở Rm5** (sai số 0.22–0.30 × nhiễu).
|
||||
2. **Wavelet: wv_L1 = minphase 0.5, wv_L2 = minphase 1.0, cộng ô băng thông wv_Q = Q 80.** Hai cơ chế rất khác nhau: pha phụ thuộc tần số phá họ pha-hằng → posterior **tự tin quá mức** (minphase 0.5: warp ×3.2, cov90 0.11, overconfidence 3.5; minphase 1.0: ×5.9, cov90 0.03, SMC không còn chắc hơn B3c: 3/4 rid), trong khi suy giảm Q làm posterior **nới rộng chứ không gãy** (Q 80: ×1.57, cov90 0.84, σ_post ×1.8; Q 160 ≈ danh nghĩa; Q 40: ×1.6, cov90 0.86). Minphase 0.25 (0.62× nhiễu, ứng viên L1 theo dải sai số) đã cho cov90 0.25 trên rid 903 — không có mức "ôn hoà" cho pha. Vì vậy L1/L2 là hai cường độ của **pha** (1.08× và 1.93× nhiễu, khớp dải khai báo), và băng thông thành ô riêng một mức (1.41× nhiễu) để trục wavelet phủ đúng câu chữ "sai pha và băng thông"; tổ hợp minphase 0.5 + Q 80 (`cand_wv_h`, 1 rid: ×1.7, cov 0.63) không chọn vì trộn hai cơ chế. Dự đoán ghi trong S2-H1: wv_L1 còn thắng point tie ở R10 (2.1 so với 4.3 ms) nhưng **wv_L2 trượt**.
|
||||
3. **Drift: dr_L1 = siêu tham số (σ_b ×3, σ_g ×1.5, ℓ ×0.5), dr_L2 = cấu trúc (bước 8 ms tại Truncation + jitter 1 ms, ℓ 8 ms).** Hai **cơ chế** chứ không phải hai cường độ; giữ tách để quy kết được. Trên 4 rid: ×2.2 (cov90 0.75) và ×3.3 (cov90 0.61), tức L2 nặng hơn L1 về SMC; biến thiên giữa rid lớn (dr_L2: 1.3–4.1 ms vì vị trí bước so với cửa sổ). Tổ hợp (`cand_dr_hs`: ×3.5 nhưng SMC thua B3c ở 1/2 rid) và bước 16 ms (`cand_dr_s2`: ×5.3, σ_post 2.1) không chọn. Bước không nhân với c (S2 chỉ chạy c = 1).
|
||||
4. **Rm5:** mọi preset cho chẩn đoán SMC trong ±23 % danh nghĩa (3.7 ms, cov 0.76) — nhiễu 1.78 × tín hiệu nuốt sai số mô hình ≤ 0.61. Protocol khai báo null này cho **mọi** trục ở Rm5 (S2-H1 `expected_null`): S2 ở Rm5 kiểm tra hệ quả phía nhãn/đầu vào (Oracle và point tie đổi theo địa chấn), không kiểm tra registration.
|
||||
5. **Chi phí:** N = 4 một ô 50–240 s tuỳ tải GPU (Rm5 nhanh hơn R10 vì ít stage); không thấy ô nào vượt số stage bất thường dưới misspec ở N = 4.
|
||||
|
||||
**Giới hạn.** Hiệu chuẩn ở N = 4 (chưa ở N = 16), lịch SMC một mốc (khác lịch ba mốc của bench ≈ 5 %), 1–4 rid mỗi ứng viên, không có huấn luyện (mức chọn theo chẩn đoán registration + sai số mô hình, không theo band RMSE).
|
||||
|
||||
---
|
||||
|
||||
## 4. Tóm tắt giao thức (bản nháp `configs/protocol_bench.yaml`, chưa khoá)
|
||||
|
||||
**Chung.** Realization chính 8–15 (của P2r); dev 900–905; seed mạng 0–4; registration seed 0, SMC stream 0, P = 1024, nhánh estR, mốc γ (g_old, g_acf, g_one) như P2r; σ_a đúng (7 ms) ở mọi ô (nhánh σ_a của P2r không lặp lại, kết quả trượt của nó giữ nguyên). Ngân sách = P2r (Oracle 500, B3b 125, B3c 250, B3c-R 500, B3d 250, B3d-Sa 250, M2-Sa 250) + P2 cho B4a–d (125/125/500/250) + kế thừa cho phương pháp mới (PM2 250, BK2 250, HM2 125, Ctl-GP 250); TCN: `budgets_tcn` từ stage `dev-budgets` (luật budget_selection của protocol_p2 trên dev 902–905) hoặc null = bằng CNN-GRU. **Nhánh 500 vòng lặp cho mọi phương pháp** (`equal_budget_arm`, công bố là do T2 (v) gợi ý sau khi đã xem realization test): ghi trên cùng quỹ đạo, chỉ báo cáo, không luật nào dùng.
|
||||
|
||||
**Ô.**
|
||||
|
||||
| Study | Ô | SMC mới | Train | Phương pháp |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| S1 lấp lưới | 5 regime × 14 (c, N) mới của lưới c ∈ {0, 0.5, 1, 1.5, 2} × N ∈ {2, 4, 8, 16} × 8 rid | 560 | 560 | Oracle, B3b, B3c, B3c-R, B3d, B3d-Sa, M2-Sa |
|
||||
| S2 misspec | 2 regime (R10, Rm5) × 7 preset (rp_L1/L2, wv_L1/L2, wv_Q, dr_L1/L2) × c = 1 × N ∈ {4, 16} × 8 rid (+ 32 ô control rp_C, wv_C ở N = 4, tuỳ chọn) | 224 (+32) | 224 | Oracle, B3b, B3c, B3c-R, B3d-Sa, M2-Sa, Ctl-GP |
|
||||
| S3 B4 dưới ô P2r | 5 regime × c ∈ {0, 1, 2} × N ∈ {4, 16} × 8 rid; hạt P2r | 0 | 240 | B4a–d, Ctl-GP (ghép với run P2r của ô) |
|
||||
| S4 backbone TCN | (R10, Rm5, R0h) × c = 1 × N ∈ {4, 16} × 8 rid; hạt P2r | 0 | 48 | Oracle, B3b, B3c, B3c-R, B3d-Sa, M2-Sa (-TCN) |
|
||||
| S8 cycle-skip có kiểm soát | (R10, Rm5) × c = 1 × N ∈ {4, 16} × Δ ∈ {8, 16, 32} ms × 8 rid; posterior hai mode dựng từ warp thật | 0 | 96 | Oracle, PM2, BK2, HM2 |
|
||||
|
||||
**Luật** (P2/P2r, không đổi): metric band RMSE (6 Hz) macro 8 giếng test; improves = tỉ số ≤ 0.90 hoặc ΔPCC ≥ 0.05; cell_pass = ≥ 4/5 seed và > 1/2 realization; "better" = cùng luật hướng không lề; no-harm 1.02; wide = σ_post ≥ 1.5 ms; CI bootstrap 2000 trên realization; hoán vị 10 000, p một phía < 0.05. Ô c = 2 giữ cờ "unstable posterior".
|
||||
|
||||
**Giả thuyết** (`claim` = có pass/fail với luật cố định; `descriptive` = bảng; `disclosed` = động cơ từ T2 đã xem realization test):
|
||||
|
||||
| Mã | Loại | Nội dung | Dự đoán |
|
||||
| --- | --- | --- | --- |
|
||||
| S1-H1 | claim | H2a mở rộng sang c = 1.5 ở R10 (B3d-Sa thắng point tie tốt nhất, cell_pass, cả hai N) | pass |
|
||||
| S1-H2 | claim | Lợi ích bank tăng theo N ở σ_post cố định: trong các family (regime, c) rộng ở N = 16, r(16) < r(2) ở ≥ 2/3 family VÀ Spearman ρ(log₂N, r) < 0, p hoán vị trong family < 0.05 | pass |
|
||||
| S1-D | descriptive | phase diagram c × N; σ_post; fit cộng tính band_rmse²(B3d-Sa) = band_rmse²(Oracle) + β σ_post² | — |
|
||||
| S2-H1 | claim | Mỗi trục ở L1, R10: B3d-Sa thắng point tie tốt nhất (cell_pass) cả hai N; một verdict/trục; Rm5, L2, wv_Q chỉ báo cáo; null khai báo trước ở Rm5 cho rp | pass rp và wv_L1; wv_L2 trượt; dr không chắc |
|
||||
| S2-H2 | claim | No-harm của bank: mean ratio M2-Sa/B3d-Sa ≤ 1.02 ở mọi 14 cặp (preset × regime) | pass |
|
||||
| S2-D | descriptive | chẩn đoán SMC theo preset (warp RMSE, cov90, σ_post, overconfidence, phase_R); suy giảm so với ô danh nghĩa P2r; M2-Sa ở ô rộng; Ctl-GP (disclosed); bảng 500 vòng lặp (disclosed) | — |
|
||||
| S3-H1 | claim | H2a với tập đối thủ mở rộng {B3b, B3c, B3c-R, B4a–d} theo luật regime của P2r (R10 quyết định; phạm vi theo regime đạt) | pass |
|
||||
| S3-D / T2-1 | descriptive / disclosed | bảng benchmark đầy đủ; Ctl-GP so với B3d-Sa và M2-Sa trên 30 ô P2r | T2: M2-Sa > Ctl-GP ở c = 2, không ở c = 1 |
|
||||
| S4-H1 | claim | H2a độc lập backbone ở R10 c = 1 (TCN, cả hai N) | pass |
|
||||
| S4-H2 | claim | Lợi ích bank ở ô rộng độc lập backbone (M2-Sa-TCN better B3d-Sa-TCN ở Rm5 và R0h c = 1 N = 16) | pass, không chắc |
|
||||
| S8-H1 | claim | Hệ quả 3: Ĥ_PM2(f) trung bình trên (1/(2Δ), 3/(2Δ)) âm ở Δ = 32 ms, R10, cả hai N | pass (dev rid 902 N = 4 seed 0: −0.14; zero crossing 17.6 Hz so với 15.6 lý thuyết) |
|
||||
| S8-H2 | claim | BK2 better PM2 ở Δ ∈ {16, 32}, N = 16, cả hai regime (4 ô) | pass (dev: BK2/PM2 0.43 và 0.32); Δ = 8 chuyển sang mô tả (dev: 1.4, bank không tách được hai mode cách nửa chu kỳ) |
|
||||
|
||||
**Deviation ghi trong protocol:** thiết kế sau P2r và sau post hoc 29/10; S1/S3/S4 tái dùng realization và hạt P2r; nhánh 500 và Ctl-GP là bổ sung disclosed do T2; mức S2 chọn trên dev; nhãn test không chọn gì. **Thứ tự cắt:** S4 → S8 → S2 còn trục rock physics (bài gọi là "controlled synthetic study") → S1 còn c ∈ {0.5, 1.5} × N ∈ {4, 16} trên R10, Rm5, R0 (trong S1: R0h, R10tb cắt trước; trong S2: wv_Q cắt trước hai mức pha; control luôn tuỳ chọn).
|
||||
|
||||
---
|
||||
|
||||
## 5. Chi phí và phân bổ GPU
|
||||
|
||||
**Đo được ngày 29/10 (H200 dùng chung; project khác giữ 125–135 GB mỗi card, util 0–93 %):**
|
||||
|
||||
| Việc | Đo | Nguồn |
|
||||
| --- | --- | --- |
|
||||
| SMC N = 4, c = 1, P = 1024, một worker, lịch ba mốc | 142 s (rid 8 R10, cuda:1) ; 156 s (rid 902, cuda:1, trong đó fit pha 96 s) | runlog `bench_repro_r8`, `bench_dev_smoke_r902` |
|
||||
| SMC N = 4, lịch một mốc (scripts/33) | 62–153 s/ô (trung vị ≈ 100 s) khi GPU ít tải; 211 s khi tải nặng | `bench_cal_smc_rid90{2,3,4,5}` |
|
||||
| SMC N = 16, c = 1, P = 1024, một worker, lịch ba mốc | 695 s (rid 902 R10, cuda:0, GPU có job khác ở 0–93 % util) ; P2r: 600–1150 s/job khi 3–5 worker chen nhau | runlog `bench_dev_budgets_tcn` |
|
||||
| Train N = 4, 7 phương pháp × 5 seed, ngân sách P2r | 73 s | repro |
|
||||
| Train N = 4, 7 phương pháp × 1 seed | 19 s | smoke |
|
||||
| Train S8, 4 phương pháp × 1 seed, hai ngân sách (250/125 + 500) | 16–17 s/ô | smoke S8 |
|
||||
|
||||
**Ước tính giai đoạn chính** (4 worker/GPU, `MEM_GB=6`, hai GPU; "sạch" = một pipeline mỗi GPU như lần chạy đầu của P2r; "chen" = hệ số 1.37 của P2r):
|
||||
|
||||
| Giai đoạn | Job | Thời gian job (s) | Worker-giờ | Wall trên 8 worker (sạch → chen) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| S1 posterior (560: c ∈ {0.5, 1.5} × N ∈ {2, 4, 8, 16} và c ∈ {0, 1, 2} × N ∈ {2, 8}; 5 regime) | 560 | N = 2 ≈ 235, N = 4 ≈ 270, N = 8 ≈ 550, N = 16 ≈ 830 (c = 1; c = 0 rẻ hơn 30 %, c = 2 đắt hơn 15 %) | ≈ 70 | **≈ 8.8 h → 12 h** |
|
||||
| S2 posterior (224: 7 preset × 2 regime × N 4/16 × 8 rid) | 224 | (270 + 830)/2 ≈ 550 (misspec có thể đổi số stage; chưa đo ở N = 16) | ≈ 34 | **≈ 4.3 h → 5.9 h** |
|
||||
| S2 controls (32, N = 4) | 32 | 270 | 2.4 | 0.3 h |
|
||||
| S1 train (560 ô; 7 phương pháp × 5 seed; nhánh 500 cho mọi phương pháp → 3 500 bước/seed) | 560 | ≈ 120 (N ≤ 8) – 250 (N = 16) | ≈ 25 | **≈ 3 h** |
|
||||
| S2 train (224 ô; 7 phương pháp kể cả Ctl-GP; 4 000 bước/seed) | 224 | ≈ 150–280 | ≈ 13 | **≈ 1.6 h** |
|
||||
| S3 train (240 ô; B4a–d + Ctl-GP; soft-DTW/DILATE chậm) | 240 | ≈ 200–350 | ≈ 18 | **≈ 2.3 h** |
|
||||
| S4 train (48 ô TCN; 6 phương pháp, quỹ đạo tới 500 do nhánh 500) | 48 | ≈ 150 | 2 | 0.25 h |
|
||||
| S8 train (96 ô; 4 phương pháp × 5 seed) | 96 | ≈ 80 | 2 | 0.3 h |
|
||||
| summarize | — | — | — | < 10 phút |
|
||||
| **Tổng** | | | **≈ 167 worker-giờ** | **≈ 21 h sạch → 26 h chen** trên 8 worker; ≈ 42 h nếu chỉ có 4 worker |
|
||||
|
||||
Đĩa: hạt g_acf 3.2 MB/giếng: S1 ≈ 560 × 7.5 giếng TB × 3.2 MB ≈ 13 GB, S2 ≈ 224 × 10 × 3.2 ≈ 7 GB; npz dự đoán nhỏ (< 1 GB). `/home` còn 274 GB.
|
||||
|
||||
**Phân bổ đề xuất** (`compute.split` của protocol): cuda:0 — S1 R10, Rm5, R0h rồi S2 R10; cuda:1 — S1 R0, R10tb rồi S2 Rm5, rồi S3, S4, S8 (chỉ train). Với lịch 4–7/11 (4 ngày) đủ chỗ ngay cả ở kịch bản chen, **với điều kiện** mỗi GPU có ≥ 25 GB trống (4 worker × 6 GB); hiện chỉ còn 8–12 GB mỗi card nên nếu project kia không trả bộ nhớ, chạy 1–2 worker/GPU (N = 16 cần ≈ 4–6 GB) và S1 kéo dài 2–3 ngày: khi đó áp thứ tự cắt (R0h, R10tb của S1 trước).
|
||||
|
||||
---
|
||||
|
||||
## 6. Tác dụng phụ lên hash code của lock F3 và Volve
|
||||
|
||||
`ml_porosity/f3/protocol.source_hash` băm **mọi** `scripts/*.py`, còn `ml_porosity/volve/protocol.code_files` băm **mọi** `ml_porosity/**/*.py`. Các tệp mới của P6 (`scripts/32_t2_mechanism.py`, `33_bench_generator_qc.py`, `34_run_bench.py`, gói `ml_porosity/benchmark/`, và các sửa bổ sung của T2 trong `bank_train.py`/`rml.py`, của p6-gen trong `synth_d2.py`) làm `code_sha256` của cây làm việc khác với `configs/protocol_f3.lock.json` và `configs/protocol_volve.lock.json`. Hệ quả: `freeze(check=True)` của P3/P4 sẽ raise "lock mismatch" nếu chạy lại một stage đã đóng băng. Điều này **chấp nhận được** vì P3 và P4 đã hoàn tất và không bao giờ chạy lại (AGENTS.md); hai lock đó **không được sửa**. Kết quả P3/P4 vẫn tái lập được từ cây commit mang tag `protocol-volve` (hash code tính lại từ cây đó khớp lock, plan §12 ý 25). Lock của protocol_bench vì vậy chỉ băm code sau khi code đã chốt, và phải khoá **sau** mọi sửa code của P6 (kể cả T2) — nếu T2 còn sửa `bank_train.py`/`rml.py` sau khi khoá bench thì bench cũng rơi vào tình huống tương tự; thứ tự cần giữ: T2 xong việc sửa code → khoá bench → chạy chính.
|
||||
|
||||
---
|
||||
|
||||
## 7. Rủi ro còn mở
|
||||
|
||||
1. **GPU.** Project khác giữ 125–135 GB mỗi H200 từ 13:00 UTC 29/10; chỉ còn 8–12 GB trống mỗi card. Lịch chính (≈ 21–26 h trên 8 worker) chỉ kịp 4–7/11 nếu mỗi card có ≥ 25 GB; nếu không, 1–2 worker/GPU và S1 kéo dài 2–3 ngày → áp thứ tự cắt. Ô N = 16 cần ≈ 4–6 GB/worker (cap `--gpu-mem-gb`), N ≤ 8 ≈ 2–3 GB.
|
||||
2. **Khoá sau mọi sửa code.** `code_sha256` của lock bench băm `ml_porosity/**/*.py`; mọi sửa sau khoá (kể cả của agent khác) làm `freeze(check=True)` từ chối chạy tiếp → phải khoá khi code đã chốt (T2 xong), và không ai sửa `ml_porosity/` trong lúc bench chạy.
|
||||
3. **Chi phí SMC dưới misspec chưa đo ở N = 16** (số stage có thể tăng khi likelihood xung đột với anchor); ước tính S2 dùng số danh nghĩa.
|
||||
4. **S1-H2 là dự đoán mới** (heuristic mẫu hữu hạn): có thể trượt; ghi là claim với dự đoán pass. **S8-H2** đã chỉnh trên dev (bỏ vế Δ = 8). **S2-H1 trục drift** không có dự đoán rõ.
|
||||
5. **Ô P2r-grid trong S1 không chạy lại** (đọc từ `outputs/p2r`): hợp lệ vì tái lập từng bit (mục 2), nhưng nếu môi trường đổi (torch/cuDNN) trước 4/11 thì S1 trộn hai môi trường; khi đó chạy lại ô repro để kiểm.
|
||||
6. **Dev-budgets TCN**: đã xong trước khi khoá; mọi phương pháp TCN chọn 125 vòng lặp (biên dưới của danh sách ứng viên) — S4 so sánh TCN ở 125 với CNN-GRU ở ngân sách P2r (125–500); nhánh 500 cho cả hai cho phép so sánh cùng ngân sách (disclosed).
|
||||
7. **Số dev 904/905**: chạy xác nhận mức đã chọn; nếu trái ngược rõ (ví dụ wv_L1 không còn thắng point tie ở R10 trên 3/4 rid), mức được cân nhắc lại trước khi khoá và ghi ở mục 3.
|
||||
205
docs/research/t2-mechanism.md
Normal file
205
docs/research/t2-mechanism.md
Normal file
@@ -0,0 +1,205 @@
|
||||
# T2 — Cơ chế của lợi ích bank (exploratory): khai báo trước
|
||||
|
||||
Ngày viết: **29/10/2026** (lịch gốc ở `docs/plan.md` §6.1 là 1/11/2026; làm sớm). Trạng thái: **exploratory, khai báo trước** (pre-declaration). Tài liệu này được viết và băm SHA-256 (`t2-mechanism.sha256`) **trước** khi tính bất kỳ đại lượng mới nào trên `outputs/p2r/` cho T2. Không sửa sau khi băm; thay đổi phải ghi thành mục "Deviation" có ngày ở cuối tài liệu kèm một dòng hash mới.
|
||||
|
||||
Liên quan: `docs/plan.md` §12 ý 22 (quyết định 3: T2 exploratory) và ý 24 (câu hỏi đổi ngày 29/10), `docs/research/pivot-theory-benchmark.md` §2.1 hàng T2 và §6, `docs/theory.md` §6 (Mệnh đề 3–6, Nhận xét 1, Hệ quả 3), `paper/sections/06_experiments.tex` mục 6.3–6.4 (todoblock T2), `configs/protocol_p2r.yaml` (khóa; không đụng).
|
||||
|
||||
---
|
||||
|
||||
## 0. Trạng thái, phạm vi và công bố những gì đã xem
|
||||
|
||||
### 0.1 Tính chất
|
||||
|
||||
1. **Exploratory.** T2 được thiết kế **sau khi** đã thấy toàn bộ kết quả P2r (H2a, H2b, nhánh σ_a, H3 mô tả) và phân tích post hoc ngày 29/10/2026 (mục 0.2). Vì vậy không kết quả nào của T2 là confirmatory; không kết quả nào thay đổi H2a, H2b, σ_a arm hay bất kỳ số đã đăng ký nào của `protocol_p2r`; không giao thức khóa nào bị đụng. Trong bài, T2 là "mechanism analysis (exploratory)" ở mục 6.4.
|
||||
2. **Dữ liệu.** Chỉ dùng realization 8–15 của P2r, với bank SMC đã có (`outputs/p2r/posterior/<regime>/r<rid>_c<c>_n<N>_s0_particles.npz`, key `<well>/estR/g_acf`, mảng (1024, 390): hạt u = [b, g(389 nút lưới warp)], t(τ) = `R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)` như `scripts/15_diag_train.py` `run_cell`), dự đoán đã lưu (`outputs/p2r/train/<regime>/cells/*.npz`, `*.csv`, `*_diag.csv`) và tổng hợp đã đăng ký (`outputs/p2r/summary/`). Không sinh realization mới. `outputs/p2r/` là **chỉ đọc**; mọi đầu ra của T2 ghi vào `outputs/t2/`.
|
||||
3. **Nhãn test** chỉ dùng để chấm điểm theo đúng metric đã đăng ký (`run_d2.evaluate`, band RMSE với f_c = 6 Hz). Mọi ô, đại lượng, ước lượng và luật quyết định được cố định trong tài liệu này trước khi tính; không chọn gì theo kết quả.
|
||||
|
||||
### 0.2 Công bố (disclosure): những gì đã được xem ngày 29/10/2026, trước khai báo này
|
||||
|
||||
Các số dưới đây được **chép lại** từ file đã có (`outputs/p2r/posthoc/bound.csv`, `meta.json`; `outputs/p2r/summary/h2b.csv`, `sigma_post.csv`), không tính lại. Chúng là lý do T2 đổi câu hỏi (plan §12 ý 24), nên người đọc phải biết chúng đã được xem trước khi năm phép kiểm được viết ra.
|
||||
|
||||
**Bảng A. N = 16, tất cả ô (regime, c). rml_pm = tỉ số band RMSE M2-Sa/B3d-Sa đã đăng ký (H2b) với CI 95%; o_pm = Oracle/B3d-Sa; rml_o = M2-Sa/Oracle; gap_closed = (pm − rml)/(pm − oracle).**
|
||||
|
||||
| Ô | wide | σ_post (ms) | warp RMSE B3d-Sa (ms) | rml_pm [CI] | o_pm | rml_o | gap_closed |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| R10 c=0 | không | 0.283 | 0.211 | 0.994 [0.975, 1.014] | 0.984 | 1.010 | 0.382 |
|
||||
| R10tb c=0 | không | 0.310 | 0.231 | 0.990 [0.968, 1.012] | 0.986 | 1.004 | 0.740 |
|
||||
| R0 c=0 | không | 0.616 | 0.442 | 0.993 [0.978, 1.008] | 0.969 | 1.024 | 0.239 |
|
||||
| R0h c=0 | không | 0.689 | 0.498 | 0.999 [0.983, 1.012] | 0.972 | 1.027 | 0.045 |
|
||||
| Rm5 c=0 | không | 0.914 | 0.681 | 1.003 [0.988, 1.017] | 0.986 | 1.017 | −0.210 |
|
||||
| R10 c=1 | không | 0.588 | 0.629 | 1.004 [0.994, 1.017] | 0.996 | 1.008 | −1.069 |
|
||||
| R0 c=1 | **có** | 1.527 | 1.862 | 0.967 [0.956, 0.979] | 0.927 | 1.043 | 0.447 |
|
||||
| R0h c=1 | **có** | 1.717 | 2.364 | 0.970 [0.953, 0.989] | 0.919 | 1.056 | 0.370 |
|
||||
| R10tb c=1 | **có** | 1.916 | 4.784 | 0.890 [0.866, 0.915] | 0.758 | 1.174 | 0.455 |
|
||||
| Rm5 c=1 | **có** | 2.559 | 2.911 | 0.982 [0.966, 0.995] | 0.933 | 1.052 | 0.275 |
|
||||
| R10 c=2 | không | 1.181 | 0.997 | 0.987 [0.972, 1.002] | 0.974 | 1.013 | 0.513 |
|
||||
| R0 c=2 | **có** | 2.792 | 2.719 | 0.952 [0.940, 0.962] | 0.899 | 1.059 | 0.477 |
|
||||
| Rm5 c=2 | **có** | 3.955 | 3.924 | 0.964 [0.953, 0.977] | 0.909 | 1.061 | 0.395 |
|
||||
| R0h c=2 | **có** | 4.176 | 4.102 | 0.904 [0.889, 0.925] | 0.853 | 1.060 | 0.652 |
|
||||
| R10tb c=2 | **có** | 11.489 | 19.081 | 0.667 [0.615, 0.713] | 0.408 | 1.634 | 0.563 |
|
||||
|
||||
Tóm tắt đã ghi ở plan §12 ý 24: Oracle tốt hơn B3d-Sa 7–8% ở R0, R0h, Rm5 (c = 1, N = 16; o_pm 0.927, 0.919, 0.933) và 24% ở R10tb; ở c = 0 Oracle vẫn tốt hơn 1–3% dù sai số warp SMC chỉ 0.2–0.7 ms; M2-Sa đóng 27–46% khoảng cách B3d-Sa–Oracle ở c = 1 (39–65% ở c = 2) và không ô rộng nào đạt mức Oracle.
|
||||
|
||||
**Bảng B. Mọi cận đã xem (N = 16), tại σ_post. bound_post = 1/B_a đã đăng ký (nội suy trên lưới blur; tại R10tb c=2 kẹp ở 6 ms); a_exact = 1/B_a tính đúng tại σ_post; b = 1/B_b (Berkson, plug-in); b60 = b giữ hệ số ở 60 Hz; a_spec, b_spec = ρ* từ phổ chéo với nhãn thật.**
|
||||
|
||||
| Ô | 1/B_a đăng ký | a_exact | b | b60 | a_spec | b_spec |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| R10 c=0 | 1.001 | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 |
|
||||
| R10tb c=0 | 1.001 | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 |
|
||||
| R0 c=0 | 1.001 | 1.001 | 0.999 | 0.999 | 1.000 | 1.000 |
|
||||
| R0h c=0 | 1.001 | 1.001 | 0.998 | 0.999 | 1.000 | 1.000 |
|
||||
| Rm5 c=0 | 1.002 | 1.002 | 0.997 | 0.998 | 1.000 | 1.000 |
|
||||
| R10 c=1 | 1.000 | 1.001 | 0.998 | 0.999 | 1.000 | 0.999 |
|
||||
| R0 c=1 | 0.999 | 0.999 | 0.982 | 0.991 | 0.994 | 0.990 |
|
||||
| R0h c=1 | 0.996 | 0.996 | 0.972 | 0.986 | 0.991 | 0.984 |
|
||||
| R10tb c=1 | 0.964 | 0.966 | 0.893 | 0.953 | 0.960 | 0.921 |
|
||||
| Rm5 c=1 | 1.000 | 1.000 | 0.904 | 0.958 | 0.985 | 0.952 |
|
||||
| R10 c=2 | 0.994 | 0.996 | 0.984 | 0.993 | 0.993 | 0.990 |
|
||||
| R0 c=2 | 0.968 | 0.968 | 0.768 | 0.911 | 0.957 | 0.833 |
|
||||
| Rm5 c=2 | 0.980 | 0.980 | 0.285 | 0.776 | 0.955 | 0.447 |
|
||||
| R0h c=2 | 0.910 | 0.910 | 0.132 | 0.604 | 0.893 | 0.191 |
|
||||
| R10tb c=2 | 0.634 | 0.481 | 0.000 | 0.000 | 0.476 | 0.000 |
|
||||
|
||||
**Bảng C. Cùng các cận, tại sai số warp RMS của B3d-Sa trên giếng train (bound_warp = 1/B_a; b, b60, a_spec, b_spec như trên).**
|
||||
|
||||
| Ô | 1/B_a | b | b60 | a_spec | b_spec |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| R10 c=0 | 1.001 | 1.000 | 1.000 | 1.000 | 1.000 |
|
||||
| R10tb c=0 | 1.001 | 1.000 | 1.000 | 1.000 | 1.000 |
|
||||
| R0 c=0 | 1.001 | 0.999 | 1.000 | 1.000 | 1.000 |
|
||||
| R0h c=0 | 1.001 | 0.999 | 1.000 | 1.000 | 1.000 |
|
||||
| Rm5 c=0 | 1.001 | 0.998 | 0.999 | 1.000 | 1.000 |
|
||||
| R10 c=1 | 1.000 | 0.998 | 0.999 | 0.999 | 0.999 |
|
||||
| R0 c=1 | 0.994 | 0.961 | 0.981 | 0.988 | 0.976 |
|
||||
| R0h c=1 | 0.982 | 0.894 | 0.955 | 0.974 | 0.927 |
|
||||
| R10tb c=1 | 0.710 | 0.017 | 0.258 | 0.703 | 0.025 |
|
||||
| Rm5 c=1 | 0.996 | 0.820 | 0.933 | 0.979 | 0.902 |
|
||||
| R10 c=2 | 0.999 | 0.991 | 0.996 | 0.996 | 0.995 |
|
||||
| R0 c=2 | 0.971 | 0.794 | 0.920 | 0.960 | 0.853 |
|
||||
| Rm5 c=2 | 0.980 | 0.301 | 0.783 | 0.956 | 0.466 |
|
||||
| R0h c=2 | 0.913 | 0.154 | 0.626 | 0.897 | 0.221 |
|
||||
| R10tb c=2 | 0.634 | 0.000 | 0.000 | 0.396 | 0.000 |
|
||||
|
||||
**Số đếm đã ghi** (`meta.json`, 8 ô rộng ở N = 16; "vượt" = rml_pm thấp hơn cận; trong ngoặc: cả mép trên CI thấp hơn cận): classical tại σ_post 7/8 (6), tại sai số warp 6/8 (4); a_exact tại σ_post 7/8 (6); Berkson b tại σ_post 3/8 (1; R0, R0h, R10tb, đều c = 1), tại sai số warp 0/8; b60 tại σ_post 3/8 (2), tại sai số warp 1/8 (1; R0 c=1); a_spec tại σ_post 5/8 (3), tại sai số warp 3/8 (1); b_spec tại σ_post 3/8 (2), tại sai số warp 1/8 (0). Tỉ số (b)/(a) của tích phân méo: 1.5–1.7 tại σ = 1.5 ms, 2.1–2.6 tại 2 ms, 3.3–4.6 tại 2.5 ms; tần số trung vị có trọng số f⁴ 67–72 Hz.
|
||||
|
||||
**Cũng đã tính từ cùng các dự đoán này:** T4 (`scripts/30_t4_coverage.py` → `outputs/t4/`: ξ, coverage, phân tách theo ngân sách; plan §12 ý 24) và T3 (`scripts/27_t3_power.py` → `outputs/t3/`: N*, power, tỉ số trung vị theo σ_ref; `applicability-results.md`). Cả hai không dùng responsibilities, bank đối chứng, thống kê đa mode hay hiệp phương sai offset; các đại lượng của năm phép kiểm dưới đây **chưa được tính** ở bất kỳ đâu trước tài liệu này. Những gì đã tính trên dev P2 (900/901) về λ ∈ {1, 3, ∞} (`outputs/p2/diag/train/`, M2@k và M2-Sa@k, dùng để chọn λ = 1/τ_c giữ nguyên) cũng đã được xem; T2 không chọn lại λ.
|
||||
|
||||
---
|
||||
|
||||
## 1. Câu hỏi và ba cơ chế
|
||||
|
||||
**Câu hỏi (đổi ngày 29/10/2026):** sau khi trừ hiệu chỉnh quần thể của cấu trúc Berkson (cận 1/B_b), lợi ích của bank (M2-Sa so với B3d-Sa) còn phần nào không, và nếu còn thì cơ chế gì tạo ra nó? Ba ứng viên, mỗi ứng viên kèm hệ quả quan sát được mà nó dự đoán:
|
||||
|
||||
- **(a) Tăng cường nhãn / regularization.** Bank làm mạng không nhớ được một nhãn lệch duy nhất; phương sai học được hấp thụ độ trải của bank. Hệ quả: một bank **không mang thông tin** về warp nào khớp với seismic, chỉ có cùng độ rộng và cùng cấu trúc tương quan (phép kiểm ii), phải cho lợi ích gần bằng M2-Sa.
|
||||
- **(b) Lệch của warp trung bình khi posterior đa mode.** Khi posterior có hai mode (cycle skip), warp trung bình nằm giữa hai mode và nhãn của nó sai ở mọi mode (Hệ quả 3); bank giữ cả hai mode. Hệ quả: lợi ích tập trung ở các đơn vị (regime, c, rid) có giếng đa mode (phép kiểm iii).
|
||||
- **(c) Tái đăng ký ngầm qua responsibilities.** Với λ > 0, gradient của RML là NLL có trọng số r_{w,j,s} = softmax_s(log π_s + λ ℓ_{w,j,s}) (Bổ đề 3; Nhận xét 1): mạng dùng chung giữa các giếng dồn trọng số về các hạt mà nhãn khớp với dự đoán nhất quán liên giếng. Hệ quả: warp có trọng số r gần warp thật hơn warp trung bình (phép kiểm i), ở λ của giao thức.
|
||||
|
||||
Hai phép kiểm còn lại không phân biệt (a)/(b)/(c) mà định vị câu hỏi: **(iv)** quyết định cấu trúc sai số của tie trung bình posterior (Berkson hay classical), tức cận nào (1/B_b hay 1/B_a) áp dụng cho B3d-Sa; **(v)** tách phần của khoảng cách B3d-Sa–Oracle do số vòng lặp (250 so với 500) khỏi phần do sai số nhãn.
|
||||
|
||||
Ba cơ chế không loại trừ nhau. Một kết quả "không cơ chế nào" cũng là kết quả và sẽ được báo cáo như vậy.
|
||||
|
||||
---
|
||||
|
||||
## 2. Thiết lập chung (tái dựng đúng `scripts/15 run_cell`)
|
||||
|
||||
- **Giao thức và kiểm tra hash.** `P = run_d2.load_protocol(check=True)` (protocol_p2, nguồn của backbone, optimizer, cửa sổ, chuẩn hóa nhãn, f_c); `run_d2.check_rids([8..15], P)` phải trả về protocol_p2r khớp SHA-256 (như scripts 14/15). Regime (snr_db, anchor_density) đọc từ `configs/d2_synth_p2r.yaml` như `scripts/run_p2r_main.sh`.
|
||||
- **Realization và giếng.** `R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)`; train = `R.pool[:N]`, test = `R.test` (8 giếng); `obs = R.observe(w, c, snr, σ_a = 7, density)`; test quan sát ở cùng SNR với anchor đầy đủ (không dùng anchor test). Input `X = zscore_patch(seis, R.main)`; nhãn test `yt = 100·y_true`.
|
||||
- **Đăng ký.** `out = register(R, obs, reg_settings(P), reg_seed = 0)`; kiểm `out["phase"] == phase0` của `r<rid>_c<c>_n<N>_s0_phase.json`; wavelet pha R: `phase_wavelet(phase_basis(statistical_wavelet(...), fac), phase_R)`; `t_b3b = tie_b3b`, `t3c = tie_b3c` (B3c-R) như run_cell.
|
||||
- **Bank SMC.** `U = smc["<well>/estR/g_acf"]`; `Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)` (1024, 3101); warp trung bình B3d-Sa `tm = warp_mean(Tf, 0)` (đều trên 1024 hạt); tập con 64 thành viên `sub = np.random.default_rng([0, i, 29]).choice(1024, 64, replace=False)` (i = chỉ số giếng train); nhãn `labels_for_warps(R.tau_fine, antialias(phi_log, 0.5, 4), T, R.t_main)`; thành viên không hợp lệ (nhãn không hữu hạn) thay bằng thành viên hợp lệ đầu tiên và log π = −∞; π đều trên thành viên hợp lệ. Nhãn chuẩn hóa `(Y − m0)/s0` với `out["norm"]`.
|
||||
- **Huấn luyện.** `train_predict(X, Xte, spec, tcfg, seed, budgets, device)` với `tcfg = P.training.model | P.training.optimizer` (CNNGRUHetero d = 64, dropout 0.05, Adam 5e-3, grad clip 5, full batch, cửa sổ 64 mẫu bắt đầu 0, 2, …, 62: 32 cửa sổ/giếng); λ = `out["lam"]` = 1/τ_c của ô; seed 0–4; ngân sách khóa: Oracle 500, B3d-Sa 250, M2-Sa 250. Dự đoán về p.u.: μ = 100(μ̂ s0 + m0), σ = 100 σ̂ s0; chấm bằng `run_d2.evaluate(yt, μ, σ, f_c = 6)` → `band_rmse` theo giếng test.
|
||||
- **Thống kê.** Trung bình ô = trung bình trên realization × seed × giếng test. Tỉ số = tỉ số hai trung bình ô. CI 95% = bootstrap trên realization (2000 lần, `np.random.default_rng(0)`, như `scripts/13 boot`): lấy mẫu lại 8 realization có hoàn lại, trung bình theo realization rồi tỉ số/hiệu. Hiệu ghép cặp = trung bình trên realization của (hiệu theo realization). "Majority" = tỉ lệ > 0.5.
|
||||
- **Sai số warp.** `warp_errors(t_of_tau[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]`: RMSE trên 126 mẫu của t_main của τ(t) − τ_true(t), với τ(t) = nghịch đảo của t(τ) (`invert_warps`). Đây là đại lượng ở cột `B3d-Sa_warp_rmse_ms` của `_diag.csv` (sẽ đối chiếu).
|
||||
- **Tập nút cửa sổ theo τ** (cho iii, iv): K_w = {k : t_b3b(τ_k) ∈ [600, 1100] ms} trên lưới warp τ_k (bước 4 ms), xác định từ tie anchor B3b (chỉ dữ liệu), dùng chung cho mọi phương pháp và hạt của giếng đó.
|
||||
- **Ô.** WIDE16 = 8 ô có `wide = True` ở N = 16 trong `h2b.csv`: R0 c=1, R0h c=1, R10tb c=1, Rm5 c=1, R0 c=2, Rm5 c=2, R0h c=2, R10tb c=2. NARROW16 = R10 c=0, R0 c=0, Rm5 c=0 (N = 16). Phép kiểm (i), (ii), (v): WIDE16 ∪ NARROW16 (11 ô × 8 realization = 88 cell-realization). Phép kiểm (iii), (iv): cả 30 ô (5 regime × c ∈ {0, 1, 2} × N ∈ {4, 16}); luật quyết định chỉ dùng các ô nêu trong từng phép kiểm. Ô c = 2 mang cờ "unstable posterior" như P2r.
|
||||
- **Thay đổi code.** Thêm **bổ sung** vào `ml_porosity/models/bank_train.py`: tham số `on_budget=None` của `train_predict`, gọi `on_budget(step, model)` ngay sau khi lấy dự đoán tại mỗi ngân sách; mặc định `None` giữ đường chạy cũ nguyên vẹn. Thêm helper thuần `responsibilities(mu, sigma, Y, logpi, starts, win, lam)` vào `ml_porosity/losses/rml.py` (không đổi ngữ nghĩa hàm nào). `pytest tests/test_losses.py tests/test_models.py` chạy trước và sau (trước: 24 pass, 29/10 12:3x UTC).
|
||||
- **Tái lập (self-check).** Ô R0, rid 8, c = 1, N = 16, seed 0: band RMSE theo giếng test của M2-Sa(250), B3d-Sa(250), Oracle(500) huấn luyện lại so với `outputs/p2r/train/R0/cells/r8_c1_n16.csv`; báo sai lệch tuyệt đối lớn nhất (mục tiêu ~1e-4; GPU/GRU không tất định và torch đã đổi phiên bản, nên sai lệch thực đo được sẽ được ghi nguyên). Thêm: `B3d-Sa_warp_rmse_ms` và `M2-Sa_n_valid` theo giếng của `_diag.csv` phải khớp giá trị tính lại tới 1e-9 (CPU). Trên cả 88 cell-realization, sai lệch band RMSE giữa bản huấn luyện lại và bản đã đăng ký (Oracle 500, B3d-Sa 250, M2-Sa 250) được ghi (trung bình, lớn nhất) làm thước đo bất định tính; mọi tỉ số của T2 được báo cả hai cách: mẫu số đã đăng ký và mẫu số huấn luyện lại trong cùng phiên.
|
||||
|
||||
Các ngân sách [250, 500] trong một quỹ đạo: `train_predict` lấy dự đoán tại từng bước của `budgets` trên một quỹ đạo (tương đương huấn luyện riêng từng ngân sách; docstring của module). Callback tại bước 250 lấy responsibilities trước khi quỹ đạo tiếp tục.
|
||||
|
||||
Mỗi cell-realization, mỗi seed, huấn luyện 6 mạng: M2-Sa (λ giao thức) [250, 500] (callback tại 250), M2-Sa@1 [250] (callback), M2-Sa@3 [250] (callback), B3d-Sa [250, 500], Oracle [250, 500], Control [250]. Tổng 88 × 5 × 6 = 2.640 mạng.
|
||||
|
||||
---
|
||||
|
||||
## 3. Năm phép kiểm
|
||||
|
||||
### (i) Sai số warp có trọng số responsibility so với warp trung bình
|
||||
|
||||
**Ô:** WIDE16 ∪ NARROW16. **Mạng:** M2-Sa cuối huấn luyện (bước 250) với λ giao thức; chẩn đoán đã khai báo tại λ ∈ {1, 3} (M2-Sa@1, M2-Sa@3 của `scripts/15`: cùng bank, cùng π, cùng ngân sách 250). Seed 0–4.
|
||||
|
||||
**Đại lượng (theo giếng train w, trên input train X, mạng ở chế độ eval):**
|
||||
- ℓ_{w,j,s} = `window_loglik(μ, σ, Y_norm, starts, 64)` trên 32 cửa sổ cố định; r_{w,j,s} = softmax_s(log π_{w,s} + λ ℓ_{w,j,s}).
|
||||
- Trọng số theo thành viên r̄_{w,s} = mean_j r_{w,j,s}; trọng số theo mẫu r_{w,i,s} = trung bình của r_{w,j,s} trên các cửa sổ j chứa mẫu i.
|
||||
- E_r: sai số warp của T_r(τ) = Σ_s r̄_{w,s} T_s(τ) (`warp_mean(Tf[sub], log r̄)`).
|
||||
- E_r,win: RMSE trên t_main của Σ_s r_{w,i,s} τ_s(t_i) − τ_true(t_i), với τ_s(t) = `invert_warps(Tf[sub], tau_fine, t_main)`.
|
||||
- E_64: sai số warp của warp trung bình đều trên cùng 64 thành viên (`warp_mean(Tf[sub], 0)`). **So sánh chính** (cùng bank; chỉ khác trọng số).
|
||||
- E_1024: sai số warp của `warp_mean(Tf, 0)` (warp của B3d-Sa). So sánh phụ.
|
||||
- ē_r = Σ_s r̄_s e_s và ē_u = Σ_{s hợp lệ} e_s / S_ok, với e_s = RMSE trên t_main của τ_s(t) − τ_true(t) (sai số từng thành viên).
|
||||
- S_eff = 1/Σ_s r̄_s², H = −Σ_s r̄_s log r̄_s (nat; tối đa log 64 = 4.159); S_eff theo cửa sổ (trung bình trên j) và max_s r_{w,j,s} trung bình.
|
||||
|
||||
**Tổng hợp:** Δ_r = E_r − E_64 (chính), Δ_r,1024 = E_r − E_1024, Δ_win = E_r,win − E_64, Δ_e = ē_r − ē_u; theo ô: trung bình trên (rid, seed, giếng) với CI bootstrap trên realization; tỉ lệ (rid, seed, giếng) có Δ < 0.
|
||||
|
||||
**Luật quyết định (tại λ giao thức):** một ô "có (c)" nếu tỉ lệ (rid, seed, giếng) có Δ_r < 0 vượt 0.5 **và** CI 95% của Δ_r nằm hoàn toàn dưới 0. **Bằng chứng cho (c)** nếu ≥ 5/8 ô rộng "có (c)". Nếu điều đó chỉ xảy ra tại λ ∈ {1, 3}: ghi "(c) khả dụng nhưng không phải điều phương pháp của giao thức làm" (không claim về λ; `protocol_p2r` wording.forbidden). Nếu không ô rộng nào đạt: không bằng chứng cho (c). Ô hẹp được báo cáo để đối chiếu (kỳ vọng Δ ≈ 0 vì các thành viên gần trùng nhau). Δ_e và S_eff là mô tả: S_eff gần 64 nghĩa là responsibilities gần đều (RML gần trung bình theo π, Mệnh đề 4), S_eff nhỏ nghĩa là gần hard-min.
|
||||
|
||||
**Ý nghĩa:** E_r < E_64 cho thấy responsibilities mang thông tin về warp thật vượt ngoài posterior, tức có tái đăng ký. Đây là điều kiện cần cho (c) là nguồn của lợi ích, không phải điều kiện đủ.
|
||||
|
||||
### (ii) Bank nhiễu GP ngẫu nhiên (đối chứng cho (a))
|
||||
|
||||
**Ô:** WIDE16 ∪ NARROW16. **Xây bank đối chứng theo giếng train:** T_grid = `R.grid.t_of_tau(U[:, 0], U[:, 1:])` (1024 × 389, trên lưới warp); T̄ = trung bình theo hạt; C = hiệp phương sai thực nghiệm (ddof 0, 389 × 389) của T_grid quanh T̄. Phân rã C = V diag(λ) Vᵀ, cắt λ⁺ = max(λ, 0). Nhiễu η_s = V diag(√λ⁺) z_s, z_s ~ N(0, I_389), `rng = np.random.default_rng([0, i, 2029])`, rút tuần tự. SD biên của η tại mỗi nút bằng SD của hạt tại nút đó (đúng tới phần cắt), và tương quan theo τ là tương quan của tập hạt; đó là nghĩa của "cùng độ rộng, cùng cấu trúc tương quan, không mang thông tin về warp nào khớp seismic" (phân phối Gauss cùng hai mômen đầu, mất mọi cấu trúc cao hơn như đa mode và mất liên hệ giữa hạt với seismic). Chấp nhận một lần rút nếu diff(T̄ + η_s) > 0.05 ms tại mọi nút (t(τ) tăng ngặt); nếu không thì rút lại, tối đa 1.280 lần cho 64 thành viên; số lần loại được ghi. Nếu không đủ 64 thành viên, giếng dùng **phương án dự phòng** rút Gauss trong không gian u = [b, g] (ū, C_u từ hạt; đơn điệu theo cấu trúc) và được gắn cờ. t_s trên tau_fine = `np.interp(tau_fine, grid.tau, T̄ + η_s)` (như `D2Realization.observe` làm với warp thật). Nhãn và thành viên không hợp lệ xử lý như bank SMC (mục 2). Báo thêm: SD biên của bank đối chứng so với SD của hạt tại các nút K_w (tỉ số), sai số warp trung bình thành viên ē_ctl so với ē_u của 64 thành viên SMC.
|
||||
|
||||
**Huấn luyện:** RML, λ = `out["lam"]`, π đều, ngân sách 250, seed 0–4, chấm trên 8 giếng test như M2-Sa.
|
||||
|
||||
**Tỉ số theo ô (CI bootstrap trên realization):** ρ_ctl = Control/B3d-Sa (mẫu số đã đăng ký), ρ_rml = M2-Sa/B3d-Sa (đã đăng ký; bằng tỉ số H2b), ρ_ctl,rml = Control/M2-Sa (đã đăng ký); phiên bản mẫu số huấn luyện lại trong phiên cho cả ba (độ nhạy với bất định tính); hiệu ghép cặp D_ctl = band RMSE(Control) − band RMSE(M2-Sa) theo realization (trung bình trên seed, giếng) với CI.
|
||||
|
||||
**Luật quyết định theo ô rộng:** (A) "nhất quán với (a)" nếu CI(ρ_ctl) nằm dưới 1 **và** CI(D_ctl) chứa 0; (B) "chống (a)" nếu CI(ρ_ctl) chứa 1 trong khi CI(ρ_rml) nằm dưới 1; (C) "(a) một phần" nếu CI(ρ_ctl) nằm dưới 1 và CI(D_ctl) nằm trên 0 (đối chứng có lợi nhưng kém M2-Sa); (D) còn lại: không xác định. Kết luận chung = loại chiếm đa số trong 8 ô rộng, báo kèm số đếm từng loại. Ô hẹp: kỳ vọng ρ_ctl ≈ 1; nếu CI(ρ_ctl) nằm trên 1.02 ở ô hẹp thì ghi "bank nhiễu có hại khi posterior hẹp" (mô tả).
|
||||
|
||||
### (iii) Tách theo đa mode (cho (b))
|
||||
|
||||
**Thống kê đa mode (theo giếng train, cố định trước):** offset trung bình cửa sổ của từng hạt a_s = mean_{k ∈ K_w} (t_s(τ_k) − τ_k), s = 1..1024 (ms). Khớp Gaussian mixture 1 và 2 thành phần (`sklearn.mixture.GaussianMixture`, sklearn 1.9.1, `covariance_type="full"`, `n_init=5`, `random_state=0`, `reg_covar=1e-6`) trên a_s; ΔBIC = BIC₁ − BIC₂. Giếng **đa mode** nếu ΔBIC > 10 **và** |μ₁ − μ₂| > 4 ms (một mẫu) **và** min(w₁, w₂) ≥ 0.1. Lý do chọn a_s thay cho b = U[:, 0] (gợi ý trong todoblock): b là offset tại τ = 100 ms, đầu trên của miền log, ngoài cửa sổ chấm điểm 600–1100 ms; nhãn trong cửa sổ phụ thuộc t(τ) trong cửa sổ, và a_s cũng là đại lượng của phép kiểm (iv). Thống kê trên b được tính và báo cáo như **phụ**, không dùng trong luật.
|
||||
|
||||
**Đơn vị và nhóm:** đơn vị = (regime, c, rid) ở N = 16; m_u = tỉ lệ giếng đa mode trong 16 giếng train. Nhóm "đa mode" nếu m_u ≥ 0.25 (≥ 4 giếng); độ nhạy: m_u > 0 (≥ 1 giếng). Tỉ lệ m_u cũng được báo theo ô cho cả 30 ô (mô tả; kỳ vọng cao nhất ở R10tb c = 2, ô có cờ đa mode trong `protocol_p2r`).
|
||||
|
||||
**Đại lượng:** ρ_u = trung bình trên seed × giếng test của band RMSE(M2-Sa) chia cho cùng đại lượng của B3d-Sa, từ dự đoán đã lưu (không huấn luyện lại); dùng log ρ_u.
|
||||
|
||||
**So sánh (64 đơn vị của 8 ô rộng):** D = mean log ρ_u (đa mode) − mean log ρ_u (đơn mode): (1) không hiệu chỉnh; (2) **hiệu chỉnh theo ô** (chính): hiệu trong ô, trung bình trên các ô có cả hai nhóm với trọng số n₁n₂/(n₁ + n₂). CI: bootstrap đơn vị trong từng ô (2000, rng 0). Thêm: Spearman giữa m_u và log ρ_u trên 64 đơn vị và trong từng ô.
|
||||
|
||||
**Luật quyết định:** bằng chứng cho (b) nếu D hiệu chỉnh < 0 với CI không chứa 0 (lợi ích lớn hơn ở nhóm đa mode). Nếu không ô rộng nào có cả hai nhóm (nhóm trùng với ô), phép tách bị trộn với ô: không rút kết luận, chỉ báo m_u theo ô và D không hiệu chỉnh kèm cảnh báo. Nếu không đơn vị nào đa mode: "(b) không kiểm được trên P2r; không bằng chứng".
|
||||
|
||||
### (iv) Kiểm hiệp phương sai Berkson so với classical (quyết định cận nào áp dụng)
|
||||
|
||||
**Đại lượng theo giếng train (trên K_w):** offset thật a*_w = mean_k (t_true(τ_k) − τ_k); offset gán â^m_w = mean_k (t_m(τ_k) − τ_k) với m ∈ {B3d-Sa: `warp_mean(Tf, 0)`; B3c-R: t3c; B3b: t_b3b}; sai số e^m_w = â^m_w − a*_w. (Tương đương định nghĩa theo t trong `docs/theory.md` §6.1 tới dấu và tới hiệu ứng biên; hệ số tương quan không đổi dấu khi đổi dấu cả hai đại lượng.)
|
||||
|
||||
**Thống kê thô (như bài mục 4.3):** r_C = corr(e, a*) (classical dự đoán 0), r_B = corr(e, â) (Berkson dự đoán 0), V = Var(â)/Var(a*) (classical > 1, Berkson < 1); gộp 8 realization × N giếng cho mỗi ô. Ghi chú về lực: a* biến thiên giữa giếng với SD = c · σ_b = c · 19.4 ms (prior F3 của generator; `outputs/p2/warp_prior_f3.json`), trong khi σ_e ≈ 1–5 ms, nên |r| ≤ σ_e/σ_a* ≈ 0.05–0.25 với SE ≈ 0.09 tại n = 128: thống kê thô có lực thấp ở c = 1 và **suy biến ở c = 0** (a* ≡ 0; Cov(e, a*) = 0 tầm thường). Vì vậy c = 0 được báo nhưng không dùng trong luật.
|
||||
|
||||
**Thống kê neo theo anchor (chính):** a*'_w = a*_w − â^{B3b}_w, â'_w = â^m_w − â^{B3b}_w (cùng e). r'_C = corr(e, a*'), r'_B = corr(e, â'), V' = Var(â')/Var(a*'). Lý do: â^{B3b} là hàm của dữ liệu (chỉ anchor); trừ nó giữ nguyên e và đưa biến thiên của "giá trị thật" về thang sai số anchor (σ_a/√n_k ≈ 2–3 ms), cùng bậc với σ_e, nên tương quan có thể phát hiện được. Dưới Berkson (a* − â độc lập với dữ liệu): r'_B = 0 **chính xác** và Cov(e, a*') = −Var(e) < 0. Dưới classical (e độc lập với a*): Cov(e, a*') = −Cov(e, n_B) với n_B = â^{B3b} − a* (nhiễu anchor), bằng 0 chỉ khi thêm e ⊥ n_B; điều này hợp lý cho tie chỉ dùng seismic, **không bảo đảm** cho B3d-Sa (dùng anchor) và B3c-R (khởi từ B3b). Hệ quả cho cách đọc: với B3d-Sa, thống kê quyết định là r'_B (0 ⇔ trọng số tương đối anchor/seismic của posterior đúng ⇔ Berkson; r'_B > 0 ⇔ seismic được tin quá; r'_B < 0 ⇔ tin chưa đủ); r'_C < 0 không phân biệt được hai cấu trúc cho B3d-Sa và chỉ được báo.
|
||||
|
||||
**CI:** bootstrap cụm trên realization (lấy mẫu lại 8 realization có hoàn lại, giữ nguyên mọi giếng của realization; 2000 lần, rng 0); CI phân vị 95%.
|
||||
|
||||
**Độ nhạy theo mẫu:** cùng các tương quan với đại lượng theo nút (t_m(τ_k) − τ_k, t_true(τ_k) − τ_k, hiệu, và phiên bản neo theo anchor theo nút) gộp trên k ∈ K_w, giếng, realization; cùng bootstrap cụm.
|
||||
|
||||
**Luật quyết định theo ô (c ≥ 1) và phương pháp, trên thống kê neo:** "Berkson" nếu CI(r'_B) chứa 0 và CI(r'_C) không chứa 0; "classical" nếu CI(r'_C) chứa 0 và CI(r'_B) không chứa 0; còn lại "neither" (ghi rõ "không lực" nếu cả hai chứa 0, "không cấu trúc nào" nếu cả hai không chứa 0). Ô dùng cho kết luận: bốn ô rộng c = 1, N = 16 (R0, R0h, R10tb, Rm5) và bản gộp mọi ô c = 1 (5 regime × 2 N; bootstrap cụm trên realization). Kết quả thô được báo với cùng luật, làm đối chiếu. **Hệ quả:** ở ô kết luận "Berkson" cho B3d-Sa, cận 1/B_b (cột `bound_post_b`, Bảng B) là cận áp dụng; "classical" → 1/B_a; "neither" → không cận nào được claim cho ô đó. Điều này chỉ làm rõ cách đọc Bảng `tab:h2b`, không đổi số nào.
|
||||
|
||||
### (v) B3d-Sa và M2-Sa ở ngân sách của Oracle (500 vòng lặp)
|
||||
|
||||
**Ô:** WIDE16 ∪ NARROW16. **Huấn luyện lại** B3d-Sa, M2-Sa (λ giao thức) và Oracle với ngân sách [250, 500] trên một quỹ đạo, seed 0–4, spec y hệt bản đã đăng ký (mục 2).
|
||||
|
||||
**Tỉ số theo ô (trung bình ô; CI bootstrap trên realization):** Oracle(500)/B3d-Sa(500); B3d-Sa(500)/B3d-Sa(250) (cả hai huấn luyện lại; và so với B3d-Sa(250) đã đăng ký); M2-Sa(500)/B3d-Sa(500); Oracle(250)/B3d-Sa(250); M2-Sa(250)/B3d-Sa(250) (tái lập tỉ số H2b trong phiên); Oracle(500)/B3d-Sa(250) (tái lập o_pm, Bảng A). Thêm band PCC cho cùng các cặp.
|
||||
|
||||
**Cách đọc (không phải gate):** phần của khoảng cách B3d-Sa–Oracle do số vòng lặp = 1 − [1 − Oracle(500)/B3d-Sa(500)]/[1 − Oracle(500)/B3d-Sa(250)] khi cả hai tỉ số dưới 1; phần còn lại ở cùng ngân sách được quy cho sai số nhãn (và bất định tính, theo thước đo ở mục 2). Nếu B3d-Sa(500) kém B3d-Sa(250) (tỉ số > 1 với CI trên 1), ngân sách 250 đã chọn trên dev là phù hợp và khoảng cách không do thiếu vòng lặp. M2-Sa(500)/B3d-Sa(500) so với tỉ số H2b: lợi ích bank còn hay mất ở ngân sách dài hơn, chỉ báo cáo. Các so sánh đã đăng ký ở 250 vẫn là số được báo trong bài; (v) là bổ sung mô tả.
|
||||
|
||||
---
|
||||
|
||||
## 4. Báo cáo, claim cấm, ngân sách, đầu ra
|
||||
|
||||
**Báo cáo bất kể chiều kết quả:** mọi bảng của mục 3 với ước lượng và CI theo ô, tỉ lệ (rid, seed, giếng) cho (i), số đếm loại (A)–(D) cho (ii), m_u theo ô và D cho (iii), verdict theo ô và phương pháp cho (iv), các tỉ số của (v); sai lệch tái lập; số lần loại/cờ dự phòng của bank đối chứng; thời gian chạy và lệnh. Kết quả âm hoặc null được báo như kết quả dương.
|
||||
|
||||
**Claim cấm** (plan §10; `protocol_p2r` wording.forbidden; thêm cho T2): không câu nào confirmatory; không đổi H2a/H2b/σ_a arm hay bất kỳ số đã đăng ký; không "mechanism proven" / "cơ chế đã được chứng minh" (chỉ "consistent with" / "against", exploratory); không claim λ khác tốt hơn λ giao thức (M2-Sa@1, @3 chỉ là chẩn đoán responsibilities); không claim calibration; không ngoại suy sang field; không gọi lợi ích "vượt cận" nếu (iv) không cho Berkson và tỉ số không dưới 1/B_b; ô c = 2 giữ cờ unstable.
|
||||
|
||||
**Tài nguyên:** GPU cuda:0 (trống lúc 12:28 UTC 29/10; chọn lại nếu tình trạng đổi), 4 worker, `OMP/MKL/OPENBLAS/NUMEXPR_NUM_THREADS = 2`; ước tính: giai đoạn huấn luyện 88 cell-realization × (đăng ký ≈ 1–2 phút + 30 mạng ≈ 2–3 phút) ≈ 1.5–2 h với 4 worker; (iii), (iv) chỉ CPU, 240 cell-realization, ≈ 15–30 phút. Mọi lần chạy qua `scripts/runlog.sh -n t2_<stage>`; lần chạy dài tách bằng `setsid nohup`, log `logs/t2_<stage>.out`.
|
||||
|
||||
**Đầu ra:** `scripts/32_t2_mechanism.py` (`--tests i ii iii iv v`, `--device`, `--workers`, `--out-dir` mặc định `outputs/t2`, resume theo (giai đoạn, cell-realization)); `outputs/t2/cells/<regime>_r<rid>_c<c>_n16.csv` (metric test của mọi mạng huấn luyện lại), `_resp.csv` (i), `_ctl.csv` (ii); `outputs/t2/iii/`, `outputs/t2/iv/` theo cell-realization; tổng hợp `test_i.csv`, `test_ii.csv`, `test_iii.csv`, `test_iv.csv`, `test_v.csv`, `selfcheck.json`, `meta.json`, `summary.md`, `figures/*.pdf` (nhãn tiếng Anh, `ml_porosity.eval.figstyle`); tài liệu kết quả `docs/research/t2-results.md` (tiếng Việt). Không ghi vào `outputs/p2r/`, không sửa `configs/*`, `scripts/14`, `15`, `18`, `synth_d2.py`, bài, `docs/plan.md`, `AGENTS.md`, `report.html` (orchestrator đồng bộ).
|
||||
|
||||
---
|
||||
|
||||
## Deviation
|
||||
|
||||
(Trống lúc băm. Mọi thay đổi sau khi băm ghi ở đây, có ngày, kèm một dòng hash mới trong `t2-mechanism.sha256`.)
|
||||
1
docs/research/t2-mechanism.sha256
Normal file
1
docs/research/t2-mechanism.sha256
Normal file
@@ -0,0 +1 @@
|
||||
f04e660792faf301c9f433347a5d1258bded098bb9a7ec05f808823f4efb2b87 t2-mechanism.md # hashed 2026-10-29T12:39:35Z before any T2 computation
|
||||
225
docs/research/t2-results.md
Normal file
225
docs/research/t2-results.md
Normal file
@@ -0,0 +1,225 @@
|
||||
# Kết quả T2 — cơ chế của lợi ích bank (exploratory) — 29/10/2026
|
||||
|
||||
Khai báo trước: `t2-mechanism.md` (SHA-256 `f04e6607…` trong `t2-mechanism.sha256`, băm 12:39:35 UTC 29/10/2026 trước mọi phép tính; bản sao byte `outputs/t2/declaration_v1.md`). **Exploratory, không confirmatory**: không số nào ở đây thay đổi H2a, H2b, nhánh σ_a hay bất kỳ số đã đăng ký nào của `protocol_p2r`; `outputs/p2r/` chỉ đọc. Script: `scripts/32_t2_mechanism.py` → `outputs/t2/` (`test_i.csv` … `test_v.csv`, `test_iv_persample.csv`, `test_iii_*.csv`, `selfcheck.json`, `meta.json`, `summary.md`, `figures/t2_{i,ii,iii,iv,v}_*.pdf`). Mọi CI là bootstrap 95% trên realization (2000 lần, `rng(0)`), như khai báo §2.
|
||||
|
||||
**Tóm tắt một đoạn.** (iv) Sai số của tie trung bình posterior (B3d-Sa) ở c = 1 có cấu trúc **Berkson** trong cả bốn ô rộng N = 16 và trong hai tập gộp c = 1, nên cận quần thể áp dụng cho B3d-Sa là 1/B_b; so với cận đó, tỉ số H2b chỉ thấp hơn ở tối đa 3/8 ô tại σ_post với lề ≤ 0.015 (hai ô ≤ 0.003) và ở 0/8 ô tại sai số warp đo được, tức **không xác lập được lợi ích vượt hiệu chỉnh quần thể của cấu trúc Berkson**. (v) Ở cùng ngân sách 500 vòng lặp, Oracle chỉ còn hơn B3d-Sa 4.3–5.6% ở R0, R0h, Rm5 (c = 1): khoảng 30–35% khoảng cách đã đăng ký (7–8%) là do số vòng lặp; lợi ích bank còn ở ngân sách 500 nhưng nhỏ hơn (R0, R0h: 2%). Về cơ chế: (i) responsibilities của RML tái đăng ký nhãn train (warp có trọng số r gần warp thật hơn warp trung bình ở 8/8 ô rộng, giảm 13–40% sai số warp) — (c) có thật như một hiện tượng; nhưng (ii) một bank nhiễu GP **không mang thông tin ngoài hai mômen đầu của posterior** thu được phần lớn lợi ích ở c = 1 (3/4 ô loại A), nên lợi ích ở c = 1 chủ yếu là tăng cường nhãn (a); ở c = 2 (posterior không ổn định) bank SMC hơn bank đối chứng (3/4 ô loại C), nơi thông tin của posterior có đóng góp; (iii) không có bằng chứng cho (b) theo luật chính. Tất cả là exploratory.
|
||||
|
||||
## 0. Lệnh, tài nguyên và thời gian chạy
|
||||
|
||||
| Giai đoạn | Lệnh (qua `scripts/runlog.sh`) | Thiết bị | Wall | Ghi chú |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| particles (iii, iv) | `scripts/32_t2_mechanism.py --tests iii iv --workers 4` (`CUDA_VISIBLE_DEVICES=`) | CPU | 0:06:46 | 240/240 cell-realization |
|
||||
| train (i, ii, v), lần 1 | `--tests i ii v --device cuda:0 --workers 4` | cuda:0 | 0:09:11 (dừng) | 13/88 xong; dừng chủ động (SIGTERM cả nhóm tiến trình) để chia sang hai GPU theo yêu cầu điều phối; 13 file đã xong được kiểm (360 dòng mỗi file) và giữ lại |
|
||||
| train, lần 2a | `--tests i ii v --device cuda:0 --workers 4 --rids 8 9 10 11` | cuda:0 | 0:17:52 | 36 job, ~120 s/job |
|
||||
| train, lần 2b | `--tests i ii v --device cuda:1 --workers 3 --rids 12 13 14 15` | cuda:1 | 0:25:28 | 39 job, ~125 s/job; 3 worker vì cuda:1 chỉ còn 4.5 GB trống |
|
||||
| summary | `--tests summary` (`CUDA_VISIBLE_DEVICES=`) | CPU | 0:02:27 | bảng, hình, self-check |
|
||||
|
||||
Tổng thời gian từ lần khởi chạy đầu đến hết summary: 12:48–13:27 UTC (≈ 38 phút); thời gian worker huấn luyện ≈ 2.9 worker-giờ (2.640 mạng); mỗi worker giữ 710 MiB GPU. Trong lúc chạy, một job của người dùng khác (`gpu_hold.py` + hai tiến trình SFT) chiếm ≈ 135 GB trên mỗi GPU; **không có OOM**, không job nào thất bại, không đụng tiến trình của người khác. Biến môi trường `OMP/MKL/OPENBLAS/NUMEXPR/NUMBA_NUM_THREADS = 2`. Log: `logs/t2_particles.out`, `logs/t2_train.out`, `logs/t2_train_a.out`, `logs/t2_train_b.out`; `logs/runs/20261029-12*_t2_*`, `20261029-132408_t2_summary`.
|
||||
|
||||
Thay đổi code (bổ sung, không đổi đường chạy mặc định): `ml_porosity/models/bank_train.py` thêm tham số `on_budget=None` cho `train_predict` (callback `on_budget(step, model)` sau dự đoán tại mỗi ngân sách); `ml_porosity/losses/rml.py` thêm helper thuần `responsibilities(...)`. `pytest tests/test_losses.py tests/test_models.py`: 24 pass trước và sau.
|
||||
|
||||
## 1. Tái lập (self-check; `outputs/t2/selfcheck.json`)
|
||||
|
||||
Band RMSE theo (ô, realization, seed, giếng test) của Oracle(500), B3d-Sa(250), M2-Sa(250) huấn luyện lại so với `outputs/p2r/train/<regime>/cells/*.csv`: **10.560 dòng, sai lệch tuyệt đối lớn nhất 0.0** (trung bình 0.0; sai lệch tương đối của trung bình ô 0.0). Ô R0 r8 c1 n16 seed 0: 0.0 cho cả ba phương pháp (B3d-Sa 0.7274, M2-Sa 0.7154, Oracle 0.7246 p.u., trùng số đã đăng ký). `B3d-Sa_warp_rmse_ms`, `M2-Sa_n_valid` và λ theo giếng khớp `_diag.csv` tới 0.0. Huấn luyện trên H200 với torch 2.14.0+cu130 vì vậy tất định ở đây; mọi tỉ số "mẫu số huấn luyện lại" trùng "mẫu số đã đăng ký".
|
||||
|
||||
## 2. Phép kiểm (i): warp có trọng số responsibility so với warp trung bình
|
||||
|
||||
E (ms) = sai số warp RMS trên cửa sổ chính (giếng train), trung bình trên realization × seed × giếng. E_64: warp trung bình đều của 64 thành viên bank; E_1024: warp của B3d-Sa; E_r: Σ_s r̄_s T_s; E_r,win: trọng số theo mẫu; Δ_r = E_r − E_64 (chính); Δ_e = ē_r − ē_u (sai số thành viên có trọng số r trừ trung bình đều); S_eff = 1/Σ r̄²; H = entropy (nat, tối đa 4.16). Ngân sách 250 (cuối huấn luyện).
|
||||
|
||||
| Ô | wide | E_64 | E_1024 | E_r | E_r,win | Δ_r [CI] | tỉ lệ Δ_r<0 | Δ_e [CI] | S_eff | H | (c) | Δ_r λ=1 | S_eff λ=1 | Δ_r λ=3 | S_eff λ=3 |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| R0 c=1 | có | 1.86 | 1.86 | 1.38 | 1.24 | -0.480 [-0.670, -0.316] | 0.83 | -0.74 [-0.89, -0.63] | 15.2 | 2.84 | có | -0.535 [-0.765, -0.324] | 4.5 | -0.536 [-0.770, -0.303] | 2.7 |
|
||||
| R0h c=1 | có | 2.39 | 2.36 | 1.84 | 1.70 | -0.547 [-0.796, -0.350] | 0.82 | -0.87 [-1.16, -0.62] | 14.3 | 2.70 | có | -0.573 [-0.793, -0.384] | 4.5 | -0.600 [-0.816, -0.387] | 2.7 |
|
||||
| R10tb c=1 | có | 4.86 | 4.79 | 3.05 | 2.87 | -1.808 [-2.222, -1.439] | 0.89 | -2.01 [-2.37, -1.66] | 27.8 | 3.13 | có | -1.934 [-2.331, -1.567] | 11.6 | -1.967 [-2.331, -1.601] | 4.3 |
|
||||
| Rm5 c=1 | có | 2.92 | 2.91 | 2.35 | 2.20 | -0.572 [-0.752, -0.369] | 0.80 | -1.13 [-1.37, -0.86] | 9.7 | 2.25 | có | -0.628 [-0.788, -0.432] | 3.1 | -0.520 [-0.671, -0.353] | 2.1 |
|
||||
| R0 c=2 | có | 2.74 | 2.71 | 2.04 | 1.78 | -0.702 [-0.890, -0.524] | 0.80 | -1.43 [-1.64, -1.20] | 6.5 | 1.89 | có | -0.662 [-0.883, -0.457] | 2.4 | -0.579 [-0.796, -0.364] | 2.1 |
|
||||
| Rm5 c=2 | có | 3.94 | 3.91 | 3.44 | 3.27 | -0.494 [-0.645, -0.301] | 0.67 | -1.69 [-1.89, -1.48] | 3.5 | 1.20 | có | -0.398 [-0.566, -0.185] | 1.9 | -0.275 [-0.433, -0.086] | 1.7 |
|
||||
| R0h c=2 | có | 4.15 | 4.09 | 2.67 | 2.27 | -1.485 [-1.743, -1.229] | 0.84 | -2.62 [-2.88, -2.36] | 4.8 | 1.56 | có | -1.298 [-1.611, -0.955] | 2.8 | -1.388 [-1.673, -1.068] | 1.9 |
|
||||
| R10tb c=2 | có | 19.33 | 19.08 | 11.71 | 11.24 | -7.620 [-9.204, -6.226] | 0.81 | -9.75 [-11.66, -7.73] | 9.4 | 1.67 | có | -8.087 [-9.538, -6.768] | 3.9 | -8.113 [-9.335, -6.843] | 2.2 |
|
||||
| R10 c=0 | không | 0.21 | 0.21 | 0.21 | 0.21 | -0.005 [-0.007, -0.002] | 0.60 | -0.02 [-0.02, -0.02] | 52.6 | 4.03 | có | -0.007 [-0.011, -0.001] | 33.7 | 0.001 [-0.004, 0.007] | 13.1 |
|
||||
| R0 c=0 | không | 0.45 | 0.44 | 0.41 | 0.40 | -0.035 [-0.044, -0.027] | 0.66 | -0.12 [-0.13, -0.11] | 38.1 | 3.76 | có | -0.039 [-0.055, -0.019] | 17.4 | 0.018 [-0.018, 0.060] | 6.4 |
|
||||
| Rm5 c=0 | không | 0.69 | 0.68 | 0.63 | 0.62 | -0.055 [-0.089, -0.026] | 0.59 | -0.22 [-0.25, -0.19] | 31.6 | 3.59 | có | 0.023 [-0.044, 0.095] | 13.8 | 0.251 [0.168, 0.333] | 5.7 |
|
||||
|
||||
**Luật đã khai báo:** ô "có (c)" nếu tỉ lệ (rid, seed, giếng) có Δ_r < 0 vượt 0.5 và CI của Δ_r dưới 0; bằng chứng cho (c) nếu ≥ 5/8 ô rộng. **Kết quả: 8/8 ô rộng tại λ giao thức → bằng chứng cho (c)** (cũng 8/8 tại λ = 1 và λ = 3). Độ lớn: warp có trọng số r giảm sai số warp 13–40% so với warp trung bình (R0 c=1: 1.86 → 1.38 ms; R10tb c=1: 4.86 → 3.05; R0h c=2: 4.15 → 2.67; R10tb c=2: 19.3 → 11.7; Rm5 c=2: 3.94 → 3.44). Phiên bản theo mẫu E_r,win còn thấp hơn. Δ_e âm ở mọi ô: responsibilities dồn về các thành viên gần warp thật hơn. S_eff tại λ giao thức là 3.5–28 trên 64 (R10tb c=1 cao nhất, Rm5 c=2 thấp nhất): RML ở λ = 1/τ_c **không** ở gần giới hạn λ → 0 (trung bình theo π, Mệnh đề 4) mà có responsibilities tập trung. Tại λ = 1 và 3, Δ_r trong ô rộng tương đương, S_eff 1.7–12; ở ô hẹp λ = 3 làm xấu warp (Rm5 c=0: +0.25 ms [0.17, 0.33]; R0 c=0: +0.02) nên không có cơ sở nói λ lớn hơn tốt hơn; không claim về λ. Ô hẹp tại λ giao thức: |Δ_r| ≤ 0.06 ms (luật cơ học cho "có" nhưng độ lớn không đáng kể so với sai số warp 0.2–0.7 ms). Ở bước 500 (mô tả, không khai báo trước) Δ_r gần như không đổi còn S_eff giảm (R0 c=1: 15.2 → 5.8): responsibilities sắc dần theo huấn luyện.
|
||||
|
||||
**Cách đọc.** E_r < E_64 là tính chất in-sample của responsibilities trên giếng train: thành viên gần dự đoán của mạng (dùng chung 16 giếng) thì gần warp thật hơn, tức mạng mang thông tin về warp và tái đăng ký nhãn trong lúc huấn luyện (Nhận xét 1). Đây là điều kiện cần để (c) là nguồn của lợi ích trên giếng test, không phải điều kiện đủ, và không đo được phần lợi ích test do (c).
|
||||
|
||||
## 3. Phép kiểm (ii): bank nhiễu GP đối chứng
|
||||
|
||||
Bank đối chứng: 64 warp T̄ + η_s, η_s ~ GP với hiệp phương sai thực nghiệm của 1024 hạt trên lưới warp (§3 ii của khai báo). Trên 1.408 giếng × 64 thành viên: 7 lần rút bị loại vì không đơn điệu, **0 giếng dùng phương án dự phòng**; SD biên của bank đối chứng bằng 0.98–0.99 SD của hạt; sai số warp của từng thành viên đối chứng bằng 1.00–1.03 lần của thành viên SMC (bank đối chứng "xa sự thật" ngang bank SMC). Huấn luyện RML, λ = 1/τ_c, π đều, 250 vòng lặp, seed 0–4; D_ctl = band RMSE(Control) − band RMSE(M2-Sa) theo realization.
|
||||
|
||||
| Ô | wide | Control/B3d-Sa [CI] | M2-Sa/B3d-Sa (H2b) [CI] | Control/M2-Sa [CI] | D_ctl (p.u.) [CI] | SD ctl/hạt | sai số thành viên ctl / SMC (ms) | loại |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| R0 c=1 | có | 0.987 [0.972, 1.003] | 0.967 [0.955, 0.979] | 1.021 [1.014, 1.027] | 0.016 [0.011, 0.022] | 0.978 | 2.47 / 2.43 | B: against (a) |
|
||||
| R0h c=1 | có | 0.970 [0.955, 0.985] | 0.970 [0.952, 0.989] | 1.000 [0.990, 1.011] | 0.000 [-0.008, 0.009] | 0.984 | 3.08 / 3.01 | A: consistent with (a) |
|
||||
| R10tb c=1 | có | 0.904 [0.879, 0.930] | 0.890 [0.867, 0.915] | 1.016 [0.996, 1.037] | 0.009 [-0.002, 0.022] | 0.992 | 5.21 / 5.16 | A: consistent with (a) |
|
||||
| Rm5 c=1 | có | 0.984 [0.975, 0.994] | 0.982 [0.967, 0.994] | 1.003 [0.992, 1.018] | 0.003 [-0.009, 0.018] | 0.982 | 3.87 / 3.85 | A: consistent with (a) |
|
||||
| R0 c=2 | có | 0.969 [0.959, 0.978] | 0.952 [0.941, 0.963] | 1.018 [1.009, 1.028] | 0.014 [0.007, 0.022] | 0.980 | 4.05 / 3.97 | C: partial (a) |
|
||||
| Rm5 c=2 | có | 0.973 [0.961, 0.985] | 0.964 [0.953, 0.976] | 1.010 [0.999, 1.021] | 0.011 [-0.001, 0.024] | 0.978 | 5.60 / 5.57 | A: consistent with (a) |
|
||||
| R0h c=2 | có | 0.944 [0.933, 0.956] | 0.904 [0.889, 0.924] | 1.044 [1.023, 1.060] | 0.036 [0.019, 0.046] | 0.981 | 6.03 / 5.89 | C: partial (a) |
|
||||
| R10tb c=2 | có | 0.753 [0.709, 0.791] | 0.667 [0.614, 0.713] | 1.129 [1.085, 1.188] | 0.097 [0.068, 0.130] | 0.999 | 22.28 / 21.81 | C: partial (a) |
|
||||
| R10 c=0 | không | 0.994 [0.976, 1.012] | 0.994 [0.974, 1.014] | 1.000 [0.990, 1.013] | 0.000 [-0.005, 0.006] | 0.987 | 0.35 / 0.35 | D: undetermined |
|
||||
| R0 c=0 | không | 0.994 [0.982, 1.006] | 0.993 [0.980, 1.009] | 1.002 [0.989, 1.015] | 0.001 [-0.008, 0.012] | 0.990 | 0.73 / 0.73 | D: undetermined |
|
||||
| Rm5 c=0 | không | 0.998 [0.988, 1.007] | 1.003 [0.988, 1.017] | 0.995 [0.979, 1.008] | -0.006 [-0.023, 0.008] | 0.994 | 1.10 / 1.09 | D: undetermined |
|
||||
|
||||
**Luật đã khai báo:** (A) CI(Control/B3d-Sa) < 1 và CI(D_ctl) ∋ 0; (B) CI(Control/B3d-Sa) ∋ 1 trong khi M2-Sa có lợi; (C) đối chứng có lợi nhưng kém M2-Sa; kết luận chung = loại chiếm đa số trong 8 ô rộng. **Kết quả: A 4, C 3, B 1 — không loại nào quá bán; loại A chiếm đa số tương đối.** Bank đối chứng có lợi (CI < 1) ở 7/8 ô rộng. Ở c = 1 nó bằng M2-Sa ở 3/4 ô (R0h 0.970 so với 0.970; R10tb 0.904 so với 0.890; Rm5 0.984 so với 0.982) và kém một chút ở R0 (0.987 [0.972, 1.003] so với 0.967; D_ctl = +0.016 p.u. [0.011, 0.022]; loại B theo luật, nhưng ở sát ranh giới). Ở c = 2 đối chứng có lợi nhưng kém M2-Sa rõ (R0 0.969 so với 0.952; R0h 0.944 so với 0.904; R10tb 0.753 so với 0.667; Rm5 c=2 loại A). Ô hẹp: 0.994–0.998, không có hại.
|
||||
|
||||
**Cách đọc.** Phần lớn lợi ích ở c = 1 có được với một bank chỉ mang độ rộng và tương quan của posterior, không mang thông tin về hạt nào khớp seismic: nhất quán với (a) tăng cường nhãn. Phần vượt của M2-Sa so với đối chứng xuất hiện ở c = 2 (posterior không ổn định, nhiều giếng đa mode, Bảng (iii)) và nhẹ ở R0 c=1: ở đó bank SMC mang thông tin ngoài hai mômen đầu (đa mode, liên hệ hạt–seismic) mà đối chứng không có, phù hợp với (c) và/hoặc (b) đóng góp thêm. Lưu ý đối chứng không phải "không thông tin": hiệp phương sai posterior đã mã hóa ràng buộc của seismic lên độ rộng.
|
||||
|
||||
## 4. Phép kiểm (iii): tách theo đa mode
|
||||
|
||||
Thống kê theo giếng train (khai báo §3 iii): GMM 2 so với 1 thành phần trên offset trung bình cửa sổ của hạt a_s; đa mode nếu ΔBIC > 10, |μ₁ − μ₂| > 4 ms, min w ≥ 0.1. m_u = tỉ lệ giếng đa mode trong đơn vị (regime, c, rid). Cột `m_u (b)` là thống kê phụ trên b = U[:, 0] (không dùng trong luật).
|
||||
|
||||
| Ô (N=16) | m_u (a_s) | m_u (b) | đơn vị m_u ≥ 0.25 | đơn vị m_u > 0 | SD posterior của a_s (ms) |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| R0 c=0 | 0.000 | 0.000 | 0 | 0 | 0.410 |
|
||||
| R0 c=1 | 0.047 | 0.055 | 0 | 6 | 0.850 |
|
||||
| R0 c=2 | 0.070 | 0.203 | 1 | 5 | 1.530 |
|
||||
| R0h c=0 | 0.000 | 0.000 | 0 | 0 | 0.430 |
|
||||
| R0h c=1 | 0.078 | 0.055 | 0 | 6 | 1.040 |
|
||||
| R0h c=2 | 0.188 | 0.219 | 3 | 7 | 2.520 |
|
||||
| R10 c=0 | 0.000 | 0.000 | 0 | 0 | 0.150 |
|
||||
| R10 c=1 | 0.008 | 0.836 | 0 | 1 | 0.240 |
|
||||
| R10 c=2 | 0.008 | 0.695 | 0 | 1 | 0.530 |
|
||||
| R10tb c=0 | 0.000 | 0.000 | 0 | 0 | 0.150 |
|
||||
| R10tb c=1 | 0.148 | 0.336 | 2 | 8 | 1.730 |
|
||||
| R10tb c=2 | 0.508 | 0.195 | 8 | 8 | 11.550 |
|
||||
| Rm5 c=0 | 0.000 | 0.000 | 0 | 0 | 0.680 |
|
||||
| Rm5 c=1 | 0.070 | 0.008 | 0 | 6 | 1.540 |
|
||||
| Rm5 c=2 | 0.039 | 0.047 | 0 | 4 | 2.100 |
|
||||
|
||||
Đa mode theo a_s hiếm ngoài R10tb c=2 (m_u = 0.51; 8/8 đơn vị có m_u ≥ 0.25) và R0h c=2 (0.19; 3/8); ở c = 1 tối đa 0.15 (R10tb) và không đơn vị nào đạt 0.25 ngoài R10tb c=1 (2/8). Thống kê trên b cho tỉ lệ cao ở R10 c=1,2 (0.84, 0.70) dù posterior ở cửa sổ hẹp (SD a_s 0.24–0.53 ms): b là offset tại τ = 100 ms, ngoài cửa sổ, nên không phản ánh đa mode của nhãn; điều này ủng hộ lựa chọn a_s làm thống kê chính.
|
||||
|
||||
So sánh log ρ_u = log(band RMSE M2-Sa / B3d-Sa) theo đơn vị (dự đoán đã đăng ký) giữa nhóm đa mode và đơn mode, 64 đơn vị của 8 ô rộng:
|
||||
|
||||
| nhóm | n đa mode | n đơn mode | ô có cả hai nhóm | D không hiệu chỉnh [CI] | D hiệu chỉnh theo ô [CI] | Spearman(m_u, log ρ_u) | kết luận |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| m_u ≥ 0.25 (chính) | 14 | 50 | 3 | -0.235 [-0.323, -0.181] | -0.012 [-0.043, 0.020] | -0.71 | no evidence for (b) |
|
||||
| m_u > 0 (độ nhạy) | 50 | 14 | 6 | -0.091 [-0.112, -0.070] | -0.017 [-0.031, -0.000] | -0.71 | evidence for (b) |
|
||||
|
||||
Spearman trong từng ô và số đơn vị theo nhóm:
|
||||
|
||||
| Ô | Spearman trong ô | đơn vị m_u ≥ 0.25 | đơn vị m_u > 0 |
|
||||
| --- | --- | --- | --- |
|
||||
| R0 c=1 | 0.130 | 0 | 6 |
|
||||
| R0 c=2 | -0.200 | 1 | 5 |
|
||||
| R0h c=1 | -0.620 | 0 | 6 |
|
||||
| R0h c=2 | -0.880 | 3 | 7 |
|
||||
| R10tb c=1 | 0.230 | 2 | 8 |
|
||||
| R10tb c=2 | -0.270 | 8 | 8 |
|
||||
| Rm5 c=1 | -0.940 | 0 | 6 |
|
||||
| Rm5 c=2 | 0.460 | 0 | 4 |
|
||||
|
||||
**Luật đã khai báo:** bằng chứng cho (b) nếu D hiệu chỉnh theo ô < 0 với CI không chứa 0, nhóm m_u ≥ 0.25. **Kết quả: không có bằng chứng cho (b)** (D hiệu chỉnh −0.012 [−0.043, +0.020]; chỉ 3 ô có cả hai nhóm). Độ nhạy m_u > 0: D hiệu chỉnh −0.017 [−0.031, −0.0002], sát 0, "evidence for (b)" theo luật cơ học nhưng ở mức biên. D không hiệu chỉnh (−0.23) và Spearman −0.71 trên 64 đơn vị bị trộn với ô: R10tb c=2 vừa đa mode nhất vừa có lợi ích lớn nhất (vì σ_post 11.5 ms), còn Spearman trong ô đổi dấu giữa các ô. Kết luận: trên P2r, (b) nhiều nhất là đóng góp nhỏ; phép tách có ít lực vì đa mode hiếm ngoài ô không ổn định.
|
||||
|
||||
## 5. Phép kiểm (iv): Berkson hay classical
|
||||
|
||||
Offset trung bình cửa sổ theo giếng train trên tập nút K_w (từ tie anchor B3b): a* (thật), â^m (phương pháp), e = â^m − a*. Thống kê **neo theo anchor** (chính): â′ = â^m − â^{B3b}, a*′ = a* − â^{B3b}; Berkson dự đoán r′_B = corr(e, â′) = 0 và r′_C = corr(e, a*′) < 0; classical (với e ⊥ nhiễu anchor) dự đoán r′_C = 0 và r′_B > 0. Thống kê **thô** (r_B = corr(e, â), r_C = corr(e, a*)) như bài mục 4.3, lực thấp vì SD(a*) = c·19.4 ms ≫ SD(e). CI: bootstrap cụm trên realization. Ô kết luận: bốn ô rộng c = 1, N = 16 và hai tập gộp c = 1.
|
||||
|
||||
| Ô | pp | n giếng | SD e (ms) | SD a*′ (ms) | r′_B = corr(e, â′) [CI] | r′_C = corr(e, a*′) [CI] | Var(â′)/Var(a*′) | kết luận (neo) | r_B thô [CI] | r_C thô [CI] | kết luận thô |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| R0 c=1 N=16 | B3d-Sa | 128 | 1.400 | 2.670 | 0.017 [-0.138, 0.210] | -0.508 [-0.580, -0.391] | 0.740 | Berkson | 0.205 [0.104, 0.310] | 0.171 [0.076, 0.275] | neither (no structure) |
|
||||
| R0 c=1 N=16 | B3c-R | 128 | 2.300 | 2.670 | 0.321 [0.189, 0.465] | -0.586 [-0.667, -0.453] | 0.730 | neither (no structure) | 0.255 [0.098, 0.397] | 0.201 [0.044, 0.345] | neither (no structure) |
|
||||
| R0h c=1 N=16 | B3d-Sa | 128 | 2.000 | 3.620 | -0.035 [-0.140, 0.085] | -0.580 [-0.668, -0.427] | 0.660 | Berkson | 0.145 [-0.029, 0.288] | 0.096 [-0.058, 0.242] | neither (no power) |
|
||||
| R0h c=1 N=16 | B3c-R | 128 | 2.340 | 3.620 | -0.019 [-0.179, 0.160] | -0.662 [-0.768, -0.507] | 0.560 | Berkson | 0.138 [0.019, 0.261] | 0.081 [-0.047, 0.216] | classical |
|
||||
| R10tb c=1 N=16 | B3d-Sa | 128 | 5.680 | 13.800 | -0.027 [-0.157, 0.077] | -0.436 [-0.520, -0.334] | 0.810 | Berkson | -0.004 [-0.143, 0.120] | -0.146 [-0.293, -0.012] | Berkson |
|
||||
| R10tb c=1 N=16 | B3c-R | 128 | 11.740 | 13.800 | -0.193 [-0.302, -0.097] | -0.925 [-0.942, -0.904] | 0.150 | neither (no structure) | -0.041 [-0.098, 0.019] | -0.332 [-0.407, -0.254] | Berkson |
|
||||
| Rm5 c=1 N=16 | B3d-Sa | 128 | 1.970 | 2.670 | -0.052 [-0.264, 0.177] | -0.771 [-0.829, -0.682] | 0.410 | Berkson | 0.106 [-0.064, 0.268] | 0.057 [-0.110, 0.219] | neither (no power) |
|
||||
| Rm5 c=1 N=16 | B3c-R | 128 | 3.060 | 2.670 | 0.551 [0.463, 0.639] | -0.637 [-0.702, -0.513] | 0.850 | neither (no structure) | 0.210 [0.026, 0.339] | 0.137 [-0.048, 0.272] | classical |
|
||||
| R10 c=1 N=16 | B3d-Sa | 128 | 0.460 | 2.670 | -0.161 [-0.231, -0.127] | -0.327 [-0.414, -0.212] | 0.920 | neither (no structure) | 0.122 [-0.088, 0.212] | 0.111 [-0.095, 0.196] | neither (no power) |
|
||||
| R10 c=1 N=16 | B3c-R | 128 | 1.510 | 2.670 | 0.076 [-0.033, 0.219] | -0.501 [-0.590, -0.363] | 0.750 | Berkson | 0.158 [-0.099, 0.371] | 0.121 [-0.124, 0.339] | neither (no power) |
|
||||
| gộp mọi ô c=1 (5 regime × 2 N) | B3d-Sa | 800 | 3.010 | 6.590 | -0.042 [-0.126, 0.049] | -0.493 [-0.561, -0.402] | 0.760 | Berkson | 0.091 [-0.006, 0.216] | 0.013 [-0.095, 0.141] | neither (no power) |
|
||||
| gộp mọi ô c=1 (5 regime × 2 N) | B3c-R | 800 | 5.440 | 6.590 | -0.089 [-0.155, -0.015] | -0.869 [-0.898, -0.829] | 0.250 | neither (no structure) | 0.055 [-0.018, 0.125] | -0.085 [-0.171, -0.005] | Berkson |
|
||||
| gộp 4 ô rộng c=1, N=16 | B3d-Sa | 512 | 3.240 | 7.440 | -0.026 [-0.124, 0.072] | -0.458 [-0.529, -0.376] | 0.790 | Berkson | 0.059 [-0.012, 0.151] | -0.022 [-0.098, 0.073] | neither (no power) |
|
||||
| gộp 4 ô rộng c=1, N=16 | B3c-R | 512 | 6.310 | 7.440 | -0.086 [-0.163, -0.004] | -0.887 [-0.912, -0.851] | 0.210 | neither (no structure) | 0.046 [-0.006, 0.100] | -0.112 [-0.182, -0.049] | Berkson |
|
||||
|
||||
Ô c = 2 (cờ unstable posterior), N = 16:
|
||||
|
||||
| Ô | pp | n giếng | SD e (ms) | SD a*′ (ms) | r′_B = corr(e, â′) [CI] | r′_C = corr(e, a*′) [CI] | Var(â′)/Var(a*′) | kết luận (neo) | r_B thô [CI] | r_C thô [CI] | kết luận thô |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| R0 c=2 N=16 | B3d-Sa | 128 | 1.620 | 2.750 | -0.218 [-0.326, -0.093] | -0.741 [-0.788, -0.673] | 0.470 | neither (no structure) | 0.105 [-0.031, 0.245] | 0.085 [-0.051, 0.238] | neither (no power) |
|
||||
| R0 c=2 N=16 | B3c-R | 128 | 2.290 | 2.750 | 0.248 [0.100, 0.408] | -0.636 [-0.713, -0.520] | 0.630 | neither (no structure) | 0.194 [-0.017, 0.354] | 0.166 [-0.042, 0.326] | neither (no power) |
|
||||
| R0h c=2 N=16 | B3d-Sa | 128 | 2.690 | 4.000 | -0.263 [-0.367, -0.146] | -0.827 [-0.875, -0.772] | 0.340 | neither (no structure) | 0.170 [-0.016, 0.307] | 0.137 [-0.047, 0.276] | neither (no power) |
|
||||
| R0h c=2 N=16 | B3c-R | 128 | 2.910 | 4.000 | -0.072 [-0.252, 0.098] | -0.774 [-0.851, -0.656] | 0.400 | Berkson | 0.154 [-0.027, 0.320] | 0.118 [-0.061, 0.298] | neither (no power) |
|
||||
| R10 c=2 N=16 | B3d-Sa | 128 | 0.630 | 2.750 | -0.228 [-0.289, -0.140] | -0.441 [-0.510, -0.319] | 0.850 | neither (no structure) | 0.040 [-0.149, 0.180] | 0.032 [-0.158, 0.169] | neither (no power) |
|
||||
| R10 c=2 N=16 | B3c-R | 128 | 1.540 | 2.750 | 0.052 [-0.054, 0.181] | -0.516 [-0.626, -0.379] | 0.740 | Berkson | 0.120 [-0.133, 0.332] | 0.100 [-0.148, 0.305] | neither (no power) |
|
||||
| R10tb c=2 N=16 | B3d-Sa | 128 | 20.290 | 26.590 | -0.112 [-0.213, -0.030] | -0.826 [-0.859, -0.793] | 0.320 | neither (no structure) | 0.048 [-0.054, 0.142] | -0.209 [-0.327, -0.086] | Berkson |
|
||||
| R10tb c=2 N=16 | B3c-R | 128 | 26.160 | 26.590 | -0.049 [-0.222, 0.102] | -0.991 [-0.993, -0.987] | 0.020 | Berkson | -0.016 [-0.107, 0.061] | -0.345 [-0.422, -0.247] | Berkson |
|
||||
| Rm5 c=2 N=16 | B3d-Sa | 128 | 2.310 | 2.750 | -0.130 [-0.327, 0.045] | -0.898 [-0.928, -0.862] | 0.200 | Berkson | 0.087 [-0.100, 0.255] | 0.058 [-0.126, 0.228] | neither (no power) |
|
||||
| Rm5 c=2 N=16 | B3c-R | 128 | 3.060 | 2.750 | 0.503 [0.371, 0.619] | -0.697 [-0.742, -0.620] | 0.690 | neither (no structure) | 0.173 [-0.007, 0.309] | 0.135 [-0.055, 0.279] | neither (no power) |
|
||||
|
||||
N = 4, c = 1 (CI rộng, 32 giếng):
|
||||
|
||||
| Ô | pp | r′_B [CI] | r′_C [CI] | kết luận (neo) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| R0 c=1 N=4 | B3d-Sa | 0.055 [-0.707, 0.611] | -0.688 [-0.883, -0.395] | Berkson |
|
||||
| R0 c=1 N=4 | B3c-R | 0.004 [-0.465, 0.616] | -0.741 [-0.891, -0.511] | Berkson |
|
||||
| R0h c=1 N=4 | B3d-Sa | 0.003 [-0.447, 0.233] | -0.661 [-0.833, -0.362] | Berkson |
|
||||
| R0h c=1 N=4 | B3c-R | -0.094 [-0.461, 0.401] | -0.679 [-0.856, -0.225] | Berkson |
|
||||
| R10 c=1 N=4 | B3d-Sa | 0.141 [-0.588, 0.498] | -0.439 [-0.676, -0.082] | Berkson |
|
||||
| R10 c=1 N=4 | B3c-R | -0.220 [-0.542, 0.231] | -0.571 [-0.723, -0.393] | Berkson |
|
||||
| R10tb c=1 N=4 | B3d-Sa | -0.183 [-0.355, 0.005] | -0.667 [-0.818, -0.381] | Berkson |
|
||||
| R10tb c=1 N=4 | B3c-R | -0.221 [-0.357, -0.126] | -0.861 [-0.939, -0.722] | neither (no structure) |
|
||||
| Rm5 c=1 N=4 | B3d-Sa | 0.143 [-0.284, 0.566] | -0.864 [-0.930, -0.607] | Berkson |
|
||||
| Rm5 c=1 N=4 | B3c-R | 0.465 [0.002, 0.829] | -0.760 [-0.862, -0.625] | neither (no structure) |
|
||||
|
||||
Độ nhạy theo mẫu (offset theo nút, gộp ≈ 15.700 mẫu mỗi ô, N = 16, c = 1):
|
||||
|
||||
| Ô (N=16, c=1) | pp | n mẫu | r′_B [CI] | r′_C [CI] | kết luận (neo) | kết luận thô |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| R10 | B3d-Sa | 15689 | -0.014 [-0.088, 0.038] | -0.162 [-0.229, -0.075] | Berkson | neither (no power) |
|
||||
| R10 | B3c-R | 15689 | 0.192 [0.123, 0.251] | -0.559 [-0.591, -0.520] | neither (no structure) | classical |
|
||||
| R0 | B3d-Sa | 15689 | 0.055 [-0.047, 0.159] | -0.369 [-0.412, -0.319] | Berkson | classical |
|
||||
| R0 | B3c-R | 15689 | 0.449 [0.398, 0.489] | -0.590 [-0.614, -0.558] | neither (no structure) | classical |
|
||||
| Rm5 | B3d-Sa | 15689 | 0.024 [-0.095, 0.148] | -0.563 [-0.619, -0.489] | Berkson | neither (no power) |
|
||||
| Rm5 | B3c-R | 15689 | 0.625 [0.602, 0.655] | -0.622 [-0.647, -0.589] | neither (no structure) | classical |
|
||||
| R0h | B3d-Sa | 15683 | 0.024 [-0.069, 0.111] | -0.503 [-0.564, -0.429] | Berkson | neither (no power) |
|
||||
| R0h | B3c-R | 15683 | 0.331 [0.280, 0.383] | -0.536 [-0.586, -0.477] | neither (no structure) | classical |
|
||||
| R10tb | B3d-Sa | 15707 | -0.023 [-0.110, 0.056] | -0.502 [-0.551, -0.435] | Berkson | Berkson |
|
||||
| R10tb | B3c-R | 15707 | 0.108 [0.067, 0.146] | -0.857 [-0.879, -0.826] | neither (no structure) | Berkson |
|
||||
|
||||
**Kết quả cho B3d-Sa (luật đã khai báo).** **Berkson ở cả bốn ô rộng c = 1, N = 16** (r′_B = 0.017, −0.035, −0.027, −0.052 với CI chứa 0; r′_C = −0.44 … −0.77 với CI xa 0), ở hai tập gộp c = 1 (wide16: r′_B = −0.026 [−0.124, 0.072]; mọi ô c = 1: −0.042 [−0.126, 0.049]), ở cả 5 regime tại N = 4 và trong phiên bản theo mẫu (5/5 regime c = 1). Tỉ số phương sai Var(â′)/Var(a*′) = 0.41–0.81 < 1: offset của warp trung bình **ít phân tán hơn** offset thật quanh tie anchor, đúng như co rút kiểu Berkson. Ở ô hẹp R10 c=1: "neither" vì r′_B = −0.16 [−0.23, −0.13] (sai số chỉ 0.46 ms; hiệu chỉnh theo seismic hơi nhỏ so với cần thiết). Ở c = 2: "neither (no structure)" với r′_B âm (−0.11 … −0.26): sai số của warp trung bình tương quan âm với chính phần hiệu chỉnh theo seismic, tức ở posterior không ổn định warp trung bình không còn là trung bình có điều kiện đúng; nhất quán với cờ unstable và với việc B3d-Sa thua đối chứng ở (ii). **B3c-R:** "neither" ở hầu hết ô (r′_B dương mạnh ở R0, Rm5: 0.32, 0.55 — dịch theo tương quan thêm sai số tương quan với chính nó), chỉ R0h ra Berkson với CI rộng; đúng như cảnh báo trong khai báo, phiên bản neo không sạch cho B3c-R (sai số chứa nhiễu anchor) nên không rút kết luận cấu trúc cho B3c-R. **Thô:** chủ yếu "no power" như dự đoán; R0 c=1 (B3d-Sa) cho cả hai tương quan thô dương (0.21, 0.17) → một thành phần nhỏ tỉ lệ với offset thật (hệ số ≈ 0.012, tức ≈ 0.2 ms ở offset 20 ms) không nằm trong cả hai lý tưởng hóa; R10tb thô ra Berkson.
|
||||
|
||||
**Hệ quả cho Bảng `tab:h2b`.** Với B3d-Sa ở c = 1, cận áp dụng là **1/B_b**. Đối chiếu tỉ số H2b đã đăng ký với 1/B_b (Bảng B, C của khai báo): tại σ_post thấp hơn cận ở R0 (0.967 < 0.982), R0h (0.970 < 0.972) và R10tb (0.890 < 0.893), không ở Rm5 (0.982 > 0.904); tại sai số warp đo được: 0/4. Hai lề ≤ 0.003 nằm trong CI của tỉ số. Ở c = 2 không cấu trúc nào được xác lập nên **không claim cận nào**. Kết luận: không xác lập được lợi ích vượt hiệu chỉnh quần thể của cấu trúc Berkson; cách đọc "vượt cận classical ở 7/8 ô" không áp dụng cho B3d-Sa.
|
||||
|
||||
## 6. Phép kiểm (v): ngân sách 500
|
||||
|
||||
Huấn luyện lại B3d-Sa (PM), M2-Sa (RML) và Oracle (O) với ngân sách [250, 500] trên một quỹ đạo, seed 0–4; tỉ số của trung bình ô band RMSE. Cột "đã đăng ký" lấy từ `outputs/p2r` (trùng số huấn luyện lại, mục 1). Phần khoảng cách do số vòng lặp = 1 − [1 − O(500)/PM(500)]/[1 − O(500)/PM(250)].
|
||||
|
||||
| Ô | O(500)/PM(250) đã đăng ký | O(500)/PM(500) [CI] | O(250)/PM(250) [CI] | PM(500)/PM(250) [CI] | RML(250)/PM(250) (H2b) | RML(500)/PM(500) [CI] | RML(500)/RML(250) | O(500)/O(250) | phần khoảng cách do số vòng lặp |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| R0 c=1 | 0.927 | 0.949 [0.930, 0.965] | 0.945 [0.932, 0.956] | 0.977 [0.971, 0.984] | 0.967 | 0.980 [0.966, 0.994] | 0.990 | 0.981 | 0.300 |
|
||||
| R0h c=1 | 0.919 | 0.944 [0.920, 0.967] | 0.939 [0.922, 0.953] | 0.973 [0.962, 0.985] | 0.970 | 0.981 [0.970, 0.994] | 0.984 | 0.979 | 0.310 |
|
||||
| R10tb c=1 | 0.758 | 0.745 [0.702, 0.795] | 0.765 [0.712, 0.818] | 1.017 [0.999, 1.034] | 0.890 | 0.887 [0.869, 0.910] | 1.014 | 0.990 | -0.050 |
|
||||
| Rm5 c=1 | 0.933 | 0.957 [0.942, 0.971] | 0.954 [0.943, 0.967] | 0.976 [0.970, 0.982] | 0.982 | 0.986 [0.974, 1.000] | 0.980 | 0.978 | 0.350 |
|
||||
| R0 c=2 | 0.899 | 0.924 [0.908, 0.937] | 0.923 [0.906, 0.941] | 0.973 [0.963, 0.983] | 0.952 | 0.962 [0.952, 0.971] | 0.983 | 0.974 | 0.240 |
|
||||
| Rm5 c=2 | 0.909 | 0.924 [0.909, 0.939] | 0.932 [0.918, 0.947] | 0.984 [0.974, 0.993] | 0.964 | 0.966 [0.957, 0.974] | 0.986 | 0.976 | 0.160 |
|
||||
| R0h c=2 | 0.853 | 0.871 [0.854, 0.887] | 0.874 [0.855, 0.894] | 0.980 [0.973, 0.987] | 0.904 | 0.913 [0.898, 0.928] | 0.989 | 0.977 | 0.120 |
|
||||
| R10tb c=2 | 0.408 | 0.414 [0.387, 0.446] | 0.410 [0.384, 0.440] | 0.985 [0.976, 0.993] | 0.667 | 0.687 [0.632, 0.733] | 1.014 | 0.995 | 0.010 |
|
||||
| R10 c=0 | 0.984 | 0.985 [0.961, 1.009] | 0.992 [0.969, 1.010] | 0.999 [0.986, 1.013] | 0.994 | 0.989 [0.981, 0.997] | 0.994 | 0.992 | 0.080 |
|
||||
| R0 c=0 | 0.969 | 0.991 [0.984, 0.999] | 0.994 [0.983, 1.007] | 0.978 [0.968, 0.988] | 0.993 | 0.995 [0.986, 1.004] | 0.981 | 0.975 | 0.720 |
|
||||
| Rm5 c=0 | 0.986 | 1.006 [0.994, 1.017] | 1.006 [0.991, 1.021] | 0.980 [0.975, 0.986] | 1.003 | 1.002 [0.993, 1.012] | 0.979 | 0.980 | — |
|
||||
|
||||
**Kết quả.** B3d-Sa tốt hơn ở 500 vòng lặp trong 7/8 ô rộng (PM(500)/PM(250) = 0.973–0.985, CI dưới 1; R10tb c=1: 1.017 [0.999, 1.034]); ngân sách 250 chọn trên dev (R10, c = 1) không tối ưu cho B3d-Sa ở các ô này. Ở cùng ngân sách 500, Oracle hơn B3d-Sa 5.1%, 5.6%, 4.3% ở R0, R0h, Rm5 (c = 1) thay vì 7.3%, 8.1%, 6.7%: **29–35% khoảng cách B3d-Sa–Oracle đã đăng ký ở c = 1 là do số vòng lặp**, phần còn lại (≈ 4–6%) quy cho sai số nhãn; ở R10tb c=1 khoảng cách không đổi (−5%), ở c = 2 phần do số vòng lặp 1–24%. Ở ô hẹp c = 0, khoảng cách 1–3% đã đăng ký gần như biến mất khi cùng ngân sách (O(500)/PM(500) = 0.991, 0.985, 1.006; phần do số vòng lặp 0.72 ở R0). Lợi ích bank ở cùng ngân sách 500 **còn nhưng nhỏ hơn** ở R0, R0h (RML(500)/PM(500) = 0.980 [0.966, 0.994], 0.981 [0.970, 0.994] so với 0.967, 0.970 đã đăng ký), gần như không đổi ở R10tb c=1 (0.887) và Rm5 c=1 (0.986 [0.974, 1.000]), và ở c = 2 là 0.962, 0.913, 0.687, 0.966. M2-Sa cũng tốt hơn ở 500 (0.98–0.99) trừ R10tb (1.014). Các so sánh đã đăng ký ở 250 vẫn là số được báo trong bài; (v) chỉ bổ sung mô tả.
|
||||
|
||||
## 7. Tổng hợp
|
||||
|
||||
Năm phép kiểm cùng nói rằng: (1) nhãn tại warp trung bình posterior có sai số cấu trúc Berkson ở c = 1 (iv), nên cận quần thể áp dụng cho B3d-Sa là 1/B_b, và so với cận này lợi ích H2b không vượt hiệu chỉnh quần thể (tối đa 3/8 ô tại σ_post với lề ≤ 0.015, 0/8 tại sai số warp); (2) khoảng cách B3d-Sa–Oracle đã đăng ký gồm khoảng một phần ba do số vòng lặp và phần còn lại 4–6% do sai số nhãn ở c = 1 (v), và lợi ích bank còn ở cùng ngân sách nhưng nhỏ hơn; (3) về cơ chế của phần lợi ích hữu hạn mẫu, tái đăng ký ngầm (c) có thật như hiện tượng trên giếng train ở 8/8 ô rộng (i), nhưng một bank chỉ mang hai mômen đầu của posterior thu được phần lớn lợi ích ở c = 1 (ii), nên lợi ích ở c = 1 được giải thích chủ yếu bằng tăng cường nhãn (a) mà không cần (c); thông tin riêng của bank SMC (và theo đó (c), có thể cả (b)) chỉ cần đến ở c = 2, nơi posterior không ổn định và đa mode, còn tách theo đa mode không cho bằng chứng cho (b) theo luật chính (iii). Cả (a) lẫn (c) là hiệu ứng mẫu hữu hạn, phù hợp với lập luận heuristic ở `docs/theory.md` §6.5 rằng với ít giếng hiệu ứng mẫu hữu hạn có thể lấn sai lệch quần thể. Không kết luận nào ở đây là confirmatory; không "cơ chế nào được chứng minh"; H2a, H2b và mọi số đã đăng ký giữ nguyên.
|
||||
|
||||
## 8. Giới hạn
|
||||
|
||||
- Exploratory: thiết kế sau khi đã thấy P2r và phân tích post hoc 29/10 (công bố ở khai báo §0.2); realization 8–15 dùng lại; không có realization mới nên không thể xác nhận.
|
||||
- Huấn luyện lại tất định trên máy và torch hiện tại (sai lệch 0.0), nhưng điều đó không bảo đảm trên GPU/phiên bản khác; mọi tỉ số được báo với cả mẫu số đã đăng ký và mẫu số huấn luyện lại (ở đây trùng nhau).
|
||||
- (i) là đại lượng in-sample trên giếng train; phụ thuộc λ: tại λ = 1, 3 hiện tượng tương tự nhưng ở ô hẹp λ = 3 làm xấu warp; không claim về λ (giữ λ = 1/τ_c như giao thức).
|
||||
- (ii) bank đối chứng dùng hiệp phương sai posterior nên vẫn mang thông tin về độ rộng do seismic đặt; "không thông tin" chỉ theo nghĩa ngoài hai mômen đầu. Luật "đa số" không cho loại quá bán (4/8 A).
|
||||
- (iii) đa mode hiếm ngoài R10tb c=2 nên lực thấp; nhóm trộn với ô; thống kê chính a_s thay cho b đã được lý giải trước khi tính.
|
||||
- (iv) phiên bản neo chỉ sạch cho giả thuyết Berkson; phía classical cần thêm e ⊥ nhiễu anchor, không đúng cho B3c-R; c = 0 suy biến; c = 2 không ổn định; phiên bản thô ít lực và ở R0 c=1 lộ một thành phần tỉ lệ nhỏ không nằm trong hai lý tưởng hóa.
|
||||
- (v) một quỹ đạo cho hai ngân sách (tương đương huấn luyện riêng theo docstring của `bank_train`); không chọn lại ngân sách; số đã đăng ký ở 250 giữ nguyên.
|
||||
|
||||
## 9. Deviation so với khai báo
|
||||
|
||||
Không có deviation phân tích: mọi ô, đại lượng, ước lượng và luật quyết định đúng như `t2-mechanism.md` (hash không đổi). Ghi chú tài nguyên và bổ sung mô tả:
|
||||
|
||||
1. Giai đoạn huấn luyện chạy lần đầu trên cuda:0 với 4 worker (như khai báo), bị dừng chủ động ở 13/88 theo yêu cầu điều phối rồi chạy lại chia theo realization trên cuda:0 (4 worker, rid 8–11) và cuda:1 (3 worker, rid 12–15). Khai báo cho phép chọn lại GPU khi tình trạng đổi; kết quả tất định nên cách chia không ảnh hưởng (mục 1).
|
||||
2. Responsibilities của M2-Sa còn được lưu ở bước 500 (mô tả; không khai báo trước; không dùng trong luật nào).
|
||||
3. Luật kết luận chung của (ii) ("loại chiếm đa số") không cho loại nào quá bán; báo số đếm từng loại và loại chiếm đa số tương đối.
|
||||
@@ -152,3 +152,39 @@ run_id,parent,name,status,exit_code,start,end,wall_s,wall,device,git,dirty,code_
|
||||
20261029-012825_p4_train_sensitivity,,p4_train_sensitivity,ok,0,2026-10-29T01:28:25+00:00,2026-10-29T02:21:04+00:00,3159.2,0:52:39,cuda:0,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py train --device cuda:0 --workers 8 --arms sensitivity
|
||||
20261029-022117_p4_summarize_all,,p4_summarize_all,ok,0,2026-10-29T02:21:17+00:00,2026-10-29T02:21:36+00:00,18.7,0:00:19,cpu,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py summarize --device cpu --workers 4 --arms all
|
||||
20261029-040703_p4x_summarize_partial,,p4x_summarize_partial,ok,0,2026-10-29T04:07:03+00:00,2026-10-29T04:07:10+00:00,7.1,0:00:07,,7da6b077b6e3,True,9b97ea3ba76b1136,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python exploratory/p4x_volve.py summarize
|
||||
20261029-124821_t2_particles,,t2_particles,ok,0,2026-10-29T12:48:21+00:00,2026-10-29T12:55:07+00:00,405.9,0:06:46,,0cfe202a8b5a,True,6fc54aafba932674,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/32_t2_mechanism.py --tests iii iv --workers 4
|
||||
20261029-124821_t2_train,,t2_train,interrupted,-15,2026-10-29T12:48:21+00:00,2026-10-29T12:57:32+00:00,551.2,0:09:11,cuda:0,0cfe202a8b5a,True,6fc54aafba932674,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/32_t2_mechanism.py --tests i ii v --device cuda:0 --workers 4
|
||||
20261029-125820_t2_train_a,,t2_train_a,ok,0,2026-10-29T12:58:20+00:00,2026-10-29T13:16:13+00:00,1072.1,0:17:52,cuda:0,0cfe202a8b5a,True,d5ffd3022ad63893,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/32_t2_mechanism.py --tests i ii v --device cuda:0 --workers 4 --rids 8 9 10 11
|
||||
20261029-125820_t2_train_b,,t2_train_b,ok,0,2026-10-29T12:58:20+00:00,2026-10-29T13:23:49+00:00,1528.1,0:25:28,cuda:1,0cfe202a8b5a,True,d5ffd3022ad63893,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/32_t2_mechanism.py --tests i ii v --device cuda:1 --workers 3 --rids 12 13 14 15
|
||||
20261029-132408_t2_summary,,t2_summary,ok,0,2026-10-29T13:24:08+00:00,2026-10-29T13:26:35+00:00,147.4,0:02:27,,0cfe202a8b5a,True,01ca5e31bfcacc2a,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/32_t2_mechanism.py --tests summary
|
||||
20261029-132859_bench_dev_smoke_r902,,bench_dev_smoke_r902,ok,0,2026-10-29T13:28:59+00:00,2026-10-29T13:31:37+00:00,157.8,0:02:38,cuda:1,0cfe202a8b5a,True,b988c8d625db1fb0,runlog,.venv/bin/python scripts/34_run_bench.py posterior train --dev --studies S1 --rids 902 --regimes R10 --drift 1 --n-train 4 --seeds 0 --device cuda:1 --workers 1 --gpu-mem-gb 2
|
||||
20261029-130144_bench_gen_smc_rid902,,bench_gen_smc_rid902,ok,0,2026-10-29T13:01:44+00:00,2026-10-29T13:34:15+00:00,1950.7,0:32:31,cuda:1,0cfe202a8b5a,True,915234d81957318d,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/33_bench_generator_qc.py --rid 902 --skip-qc --smc --device cuda:1 --regimes R10 Rm5 --n-train 4 --particles 1024 --gpu-mem-gb 2
|
||||
20261029-133329_bench_repro_r8,,bench_repro_r8,ok,0,2026-10-29T13:33:29+00:00,2026-10-29T13:37:18+00:00,228.2,0:03:48,cuda:1,0cfe202a8b5a,True,bb548925ace61986,runlog,.venv/bin/python scripts/34_run_bench.py repro --device cuda:1 --workers 1 --gpu-mem-gb 3
|
||||
20261029-134258_bench_dev_smoke_s8,,bench_dev_smoke_s8,ok,0,2026-10-29T13:42:58+00:00,2026-10-29T13:43:55+00:00,57.0,0:00:57,cuda:1,0cfe202a8b5a,True,d39fff13e52542d0,runlog,.venv/bin/python scripts/34_run_bench.py train --dev --studies S8 --rids 902 --regimes R10 --n-train 4 --seeds 0 --device cuda:1 --workers 1
|
||||
20261029-134525_bench_dev_smoke_s34_post,,bench_dev_smoke_s34_post,ok,0,2026-10-29T13:45:25+00:00,2026-10-29T13:48:25+00:00,179.7,0:03:00,cuda:1,0cfe202a8b5a,True,80aee9582b02e6a1,runlog,.venv/bin/python scripts/34_run_bench.py posterior --dev --studies S1 --rids 903 --regimes R10 --drift 1 --n-train 4 --device cuda:1 --workers 1 --gpu-mem-gb 2
|
||||
20261029-134825_bench_dev_smoke_s34_train,,bench_dev_smoke_s34_train,ok,0,2026-10-29T13:48:25+00:00,2026-10-29T13:49:56+00:00,91.1,0:01:31,cuda:1,0cfe202a8b5a,True,180f5354143361ce,runlog,.venv/bin/python scripts/34_run_bench.py train --dev --studies S3 S4 --rids 903 --regimes R10 --drift 1 --n-train 4 --seeds 0 --device cuda:1 --workers 1
|
||||
20261029-131331_bench_cal_smc_rid903,,bench_cal_smc_rid903,ok,0,2026-10-29T13:13:31+00:00,2026-10-29T13:51:09+00:00,2257.4,0:37:37,cuda:0,0cfe202a8b5a,True,d4161e1bad992af2,runlog,.venv/bin/python scripts/33_bench_generator_qc.py --rid 903 --skip-qc --smc --device cuda:0 --regimes R10 Rm5 --n-train 4 --particles 1024 --gpu-mem-gb 2 --presets cand_rp_a cand_rp_b cand_rp_c cand_wv_a cand_wv_b cand_wv_c cand_wv_d cand_wv_e cand_dr_h cand_dr_s cand_dr_hs cand_dr_s2
|
||||
20261029-135351_bench_status,,bench_status,ok,0,2026-10-29T13:53:51+00:00,2026-10-29T13:53:54+00:00,3.0,0:00:03,cuda:0,0cfe202a8b5a,True,b94e242cb0842a56,runlog,.venv/bin/python scripts/34_run_bench.py status --device cuda:0 --workers 4 --threads 2 --gpu-mem-gb 6 --studies S8 --dev
|
||||
20261029-133932_bench_cal_smc_rid904,,bench_cal_smc_rid904,ok,0,2026-10-29T13:39:32+00:00,2026-10-29T14:04:35+00:00,1503.1,0:25:03,cuda:0,0cfe202a8b5a,True,b589912958c89ef3,runlog,.venv/bin/python scripts/33_bench_generator_qc.py --rid 904 --skip-qc --smc --device cuda:0 --regimes R10 Rm5 --n-train 4 --particles 1024 --gpu-mem-gb 2 --presets rp_L1 rp_L2 wv_L1 wv_L2 wv_Q dr_L1 dr_L2
|
||||
20261029-133619_bench_cal_smc_rid902b,,bench_cal_smc_rid902b,ok,0,2026-10-29T13:36:19+00:00,2026-10-29T14:05:35+00:00,1755.8,0:29:16,cuda:1,0cfe202a8b5a,True,ab1b54d59886b91e,runlog,.venv/bin/python scripts/33_bench_generator_qc.py --rid 902 --skip-qc --smc --device cuda:1 --regimes R10 Rm5 --n-train 4 --particles 1024 --gpu-mem-gb 2 --presets cand_rp_c cand_rp_d cand_wv_a cand_wv_b cand_wv_d cand_wv_e cand_wv_f cand_wv_g cand_wv_h cand_dr_hs cand_dr_s2
|
||||
20261029-133933_bench_cal_smc_rid905,,bench_cal_smc_rid905,ok,0,2026-10-29T13:39:33+00:00,2026-10-29T14:06:24+00:00,1611.3,0:26:51,cuda:1,0cfe202a8b5a,True,b589912958c89ef3,runlog,.venv/bin/python scripts/33_bench_generator_qc.py --rid 905 --skip-qc --smc --device cuda:1 --regimes R10 Rm5 --n-train 4 --particles 1024 --gpu-mem-gb 2 --presets rp_L1 rp_L2 wv_L1 wv_L2 wv_Q dr_L1 dr_L2
|
||||
20261029-133330_bench_dev_budgets_tcn,,bench_dev_budgets_tcn,ok,0,2026-10-29T13:33:30+00:00,2026-10-29T14:37:24+00:00,3833.3,1:03:53,cuda:0,0cfe202a8b5a,True,bb548925ace61986,runlog,.venv/bin/python scripts/34_run_bench.py dev-budgets --device cuda:0 --workers 1 --gpu-mem-gb 4
|
||||
20261029-143914_bench_lock,,bench_lock,ok,0,2026-10-29T14:39:14+00:00,2026-10-29T14:39:21+00:00,6.9,0:00:07,cuda:0,0cfe202a8b5a,True,0e0956f31f33d3ee,runlog,.venv/bin/python scripts/34_run_bench.py lock --device cuda:0 --workers 4 --threads 2 --gpu-mem-gb 6 --studies S1 S2 S3 S4 S8
|
||||
20261029-144311_bench_posterior_S2_cuda1,,bench_posterior_S2_cuda1,interrupted,-15,2026-10-29T14:43:11+00:00,2026-10-29T15:26:55+00:00,2624.6,0:43:45,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:1 --workers 3 --threads 2 --gpu-mem-gb 2 --studies S2
|
||||
20261029-144311_bench_posterior_S1_cuda0,,bench_posterior_S1_cuda0,interrupted,-15,2026-10-29T14:43:11+00:00,2026-10-29T15:26:55+00:00,2624.6,0:43:45,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:0 --workers 3 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R10 Rm5 R0h
|
||||
20261029-144311_bench_train_S3_S4_S8_cuda1,,bench_train_S3_S4_S8_cuda1,interrupted,-15,2026-10-29T14:43:11+00:00,2026-10-29T15:26:55+00:00,2624.6,0:43:45,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py train --device cuda:1 --workers 2 --threads 2 --gpu-mem-gb 6 --studies S3 S4 S8
|
||||
20261029-144311_bench_posterior_S1_cuda1,,bench_posterior_S1_cuda1,interrupted,-15,2026-10-29T14:43:11+00:00,2026-10-29T15:26:56+00:00,2625.2,0:43:45,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:1 --workers 1 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R0 R10tb
|
||||
20261029-154110_bench_posterior_S2_cuda0,,bench_posterior_S2_cuda0,interrupted,-1,2026-10-29T15:41:10+00:00,2026-10-29T16:06:44+00:00,1534.2,0:25:34,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:0 --workers 2 --threads 2 --gpu-mem-gb 2 --studies S2
|
||||
20261029-154110_bench_train_S3_S4_S8_cuda0,,bench_train_S3_S4_S8_cuda0,interrupted,-1,2026-10-29T15:41:10+00:00,2026-10-29T16:07:30+00:00,1580.1,0:26:20,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py train --device cuda:0 --workers 2 --threads 2 --gpu-mem-gb 6 --studies S3 S4 S8
|
||||
20261029-160659_bench_posterior_S2_cuda1,,bench_posterior_S2_cuda1,ok,0,2026-10-29T16:06:59+00:00,2026-10-29T21:04:21+00:00,17841.6,4:57:22,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:1 --workers 6 --threads 2 --gpu-mem-gb 2 --studies S2
|
||||
20261029-160659_bench_posterior_S1_cuda0,,bench_posterior_S1_cuda0,ok,0,2026-10-29T16:06:59+00:00,2026-10-29T21:39:32+00:00,19952.6,5:32:33,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:0 --workers 5 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R10 Rm5 R0
|
||||
20261029-160659_bench_posterior_S1_cuda1,,bench_posterior_S1_cuda1,interrupted,-15,2026-10-29T16:06:59+00:00,2026-10-29T22:26:15+00:00,22755.5,6:19:16,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:1 --workers 2 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R0h R10tb
|
||||
20261029-210421_bench_train_S2_cuda1,,bench_train_S2_cuda1,ok,0,2026-10-29T21:04:21+00:00,2026-10-30T00:12:09+00:00,11268.3,3:07:48,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py train --device cuda:1 --workers 6 --threads 2 --gpu-mem-gb 2 --studies S2
|
||||
20261029-222635_bench_posterior_S1_cuda1,,bench_posterior_S1_cuda1,interrupted,-15,2026-10-29T22:26:35+00:00,2026-10-30T00:16:37+00:00,6602.4,1:50:02,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:1 --workers 6 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R0h R10tb
|
||||
20261030-001657_bench_posterior_S1_cuda1,,bench_posterior_S1_cuda1,ok,0,2026-10-30T00:16:57+00:00,2026-10-30T00:38:49+00:00,1311.6,0:21:52,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:1 --workers 10 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R0h R10tb
|
||||
20261029-160738_bench_train_S3_S4_S8_cuda0,,bench_train_S3_S4_S8_cuda0,ok,0,2026-10-29T16:07:38+00:00,2026-10-30T00:58:19+00:00,31840.7,8:50:41,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py train --device cuda:0 --workers 4 --threads 2 --gpu-mem-gb 6 --studies S3 S4 S8
|
||||
20261030-003849_bench_train_S1_cuda1,,bench_train_S1_cuda1,interrupted,-15,2026-10-30T00:38:49+00:00,2026-10-30T01:01:59+00:00,1390.2,0:23:10,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py train --device cuda:1 --workers 10 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R0h R10tb
|
||||
20261029-213932_bench_train_S1_cuda0,,bench_train_S1_cuda0,interrupted,-15,2026-10-29T21:39:32+00:00,2026-10-30T01:02:37+00:00,12185.3,3:23:05,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py train --device cuda:0 --workers 5 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R10 Rm5 R0
|
||||
20261030-010257_bench_posterior_S1_cuda0,,bench_posterior_S1_cuda0,ok,0,2026-10-30T01:02:57+00:00,2026-10-30T01:03:12+00:00,14.4,0:00:14,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:0 --workers 14 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R0h
|
||||
20261030-010257_bench_posterior_S1_cuda1,,bench_posterior_S1_cuda1,ok,0,2026-10-30T01:02:57+00:00,2026-10-30T01:03:12+00:00,14.4,0:00:14,cuda:1,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:1 --workers 14 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R10tb
|
||||
20261030-010257_bench_posterior_S1_cuda0-2,,bench_posterior_S1_cuda0,ok,0,2026-10-30T01:02:57+00:00,2026-10-30T01:03:12+00:00,14.6,0:00:15,cuda:0,0cfe202a8b5a,True,ba88b1f22934cb8d,runlog,.venv/bin/python scripts/34_run_bench.py posterior --device cuda:0 --workers 8 --threads 2 --gpu-mem-gb 2 --studies S1 --regimes R10 Rm5 R0
|
||||
|
||||
|
7
ml_porosity/benchmark/__init__.py
Normal file
7
ml_porosity/benchmark/__init__.py
Normal file
@@ -0,0 +1,7 @@
|
||||
"""protocol_bench (phase P6, level B): registration-aware synthetic benchmark on D2.
|
||||
|
||||
Studies (configs/protocol_bench.yaml, `studies:`): S1 grid fill, S2 misspecification axes, S3 anchor-free B4
|
||||
baselines under the P2r cells, S4 second backbone (TCN), S8 controlled cycle-skip (two-mode) regime. The modules
|
||||
mirror ml_porosity/volve (freeze/check/lock, fingerprinted resume) and scripts 14/15/18 (SMC posterior, training,
|
||||
summary) so that the default generator path reproduces protocol_p2r.
|
||||
"""
|
||||
153
ml_porosity/benchmark/cells.py
Normal file
153
ml_porosity/benchmark/cells.py
Normal file
@@ -0,0 +1,153 @@
|
||||
"""Cell enumeration and output paths of protocol_bench.
|
||||
|
||||
A cell is one (study, regime, preset, c, N, rid[, Δ]) with its method list, budgets and backbone. Paths are flat and
|
||||
deterministic. Posterior files follow the protocol_p2r layout (r{rid}_c{c}_n{N}_s{reg_seed}{.csv,_particles.npz,
|
||||
_phase.json}) so that scripts 15/18-style readers and the P2r reference share one reader.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from ml_porosity.paths import outputs_dir
|
||||
|
||||
P2R_GRID = {"drift_factors": (0.0, 1.0, 2.0), "n_train": (4, 16)}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Cell:
|
||||
study: str
|
||||
regime: str
|
||||
preset: str | None # misspecification preset of configs/d2_synth_bench.yaml (None: nominal)
|
||||
c: float
|
||||
n_train: int
|
||||
rid: int
|
||||
methods: tuple[str, ...]
|
||||
backbone: str = "cnngru" # cnngru (bank_train.train_predict, as P2r) | tcn (f3.training.TCNHetero)
|
||||
posterior: str = "bench" # bench (this protocol's SMC) | p2r (outputs/p2r/posterior) | none
|
||||
delta_ms: float | None = None # S8 two-mode separation
|
||||
tags: tuple[str, ...] = field(default_factory=tuple)
|
||||
|
||||
@property
|
||||
def setting(self) -> str:
|
||||
return self.regime if self.preset in (None, "nominal") else f"{self.regime}__{self.preset}"
|
||||
|
||||
@property
|
||||
def tag(self) -> str:
|
||||
t = f"r{self.rid}_c{self.c:g}_n{self.n_train}"
|
||||
if self.delta_ms is not None:
|
||||
t += f"_d{self.delta_ms:g}"
|
||||
return t
|
||||
|
||||
def suffix(self) -> str:
|
||||
return "" if self.backbone == "cnngru" else f"__{self.backbone}"
|
||||
|
||||
|
||||
def bench_root(dev: bool = False, repro: bool = False) -> Path:
|
||||
root = outputs_dir() / "bench"
|
||||
return root / ("repro" if repro else "dev" if dev else "")
|
||||
|
||||
|
||||
def posterior_dir(cell: Cell, root: Path) -> Path | None:
|
||||
if cell.posterior == "none":
|
||||
return None
|
||||
if cell.posterior == "p2r":
|
||||
return outputs_dir() / "p2r" / "posterior" / cell.regime
|
||||
return root / "posterior" / cell.setting # shared by every study that needs the same (regime, preset) posterior
|
||||
|
||||
|
||||
def posterior_paths(cell: Cell, root: Path, reg_seed: int) -> dict[str, Path]:
|
||||
d = posterior_dir(cell, root)
|
||||
tag = f"r{cell.rid}_c{cell.c:g}_n{cell.n_train}_s{reg_seed}"
|
||||
return {"csv": d / f"{tag}.csv", "particles": d / f"{tag}_particles.npz", "phase": d / f"{tag}_phase.json",
|
||||
"meta": d / f"{tag}.json"}
|
||||
|
||||
|
||||
def train_dir(cell: Cell, root: Path) -> Path:
|
||||
return root / cell.study.lower() / "train" / cell.setting / "cells"
|
||||
|
||||
|
||||
def train_paths(cell: Cell, root: Path) -> dict[str, Path]:
|
||||
d = train_dir(cell, root)
|
||||
stem = cell.tag + cell.suffix()
|
||||
return {"csv": d / f"{stem}.csv", "npz": d / f"{stem}.npz", "diag": d / f"{stem}_diag.csv", "meta": d / f"{stem}.json"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- study → cells
|
||||
|
||||
def _rids(p: dict, rids) -> list[int]:
|
||||
return [int(r) for r in (p["grid"]["realizations"] if rids is None else rids)]
|
||||
|
||||
|
||||
def _grid(s: dict, grid: dict | None) -> tuple[list, list]:
|
||||
g = grid or {}
|
||||
return list(g.get("drift_factors") or s.get("drift_factors", [])), list(g.get("n_train") or s["n_train"])
|
||||
|
||||
|
||||
def s1_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
"""grid: dev-only override {drift_factors, n_train}; with an override the P2r-grid exclusion is lifted."""
|
||||
s = p["studies"]["S1"]
|
||||
cs, ns = _grid(s, grid)
|
||||
cells = []
|
||||
for reg in (regimes or s["regimes"]):
|
||||
for c, N in itertools.product(cs, ns):
|
||||
if grid is None and float(c) in P2R_GRID["drift_factors"] and int(N) in P2R_GRID["n_train"]:
|
||||
continue # existing protocol_p2r cell: read, not recomputed
|
||||
for rid in _rids(p, rids):
|
||||
cells.append(Cell("S1", reg, None, float(c), int(N), rid, tuple(s["methods"])))
|
||||
return cells
|
||||
|
||||
|
||||
def s2_cells(p: dict, rids=None, regimes=None, presets=None, controls: bool = False, grid: dict | None = None) -> list[Cell]:
|
||||
s = p["studies"]["S2"]
|
||||
names = presets or [name for axis in s["presets"].values() for name in axis]
|
||||
if controls:
|
||||
names = list(names) + list(s.get("controls", {}).get("presets", []))
|
||||
cs, ns0 = _grid(s, grid)
|
||||
cells = []
|
||||
for reg in (regimes or s["regimes"]):
|
||||
for name in names:
|
||||
ns = ns0 if (grid or name not in s.get("controls", {}).get("presets", [])) else s["controls"]["n_train"]
|
||||
for c, N in itertools.product(cs, ns):
|
||||
for rid in _rids(p, rids):
|
||||
cells.append(Cell("S2", reg, name, float(c), int(N), rid, tuple(s["methods"])))
|
||||
return cells
|
||||
|
||||
|
||||
def s3_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
s = p["studies"]["S3"]
|
||||
cs, ns = _grid(s, grid)
|
||||
post = "bench" if grid is not None else s.get("posterior", "none") # dev override: dev posteriors of the setting
|
||||
return [Cell("S3", reg, None, float(c), int(N), rid, tuple(s["methods"]), posterior=post)
|
||||
for reg in (regimes or s["regimes"]) for c, N in itertools.product(cs, ns) for rid in _rids(p, rids)]
|
||||
|
||||
|
||||
def s4_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
"""Dev override: posterior 'bench' (dev posteriors of the same setting) instead of the P2r particles."""
|
||||
s = p["studies"]["S4"]
|
||||
ns = _grid(s, grid)[1]
|
||||
return [Cell("S4", cell["regime"], None, float(cell["c"]), int(N), rid, tuple(s["methods"]), backbone=s["backbone"],
|
||||
posterior="bench" if grid is not None else s["posterior"])
|
||||
for cell in s["cells"] if regimes is None or cell["regime"] in regimes
|
||||
for N in ns for rid in _rids(p, rids)]
|
||||
|
||||
|
||||
def s8_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
s = p["studies"]["S8"]
|
||||
cs, ns = _grid(s, grid)
|
||||
return [Cell("S8", reg, None, float(c), int(N), rid, tuple(s["methods"]), posterior="none", delta_ms=float(d))
|
||||
for reg in (regimes or s["regimes"]) for d in s["delta_ms"]
|
||||
for c, N in itertools.product(cs, ns) for rid in _rids(p, rids)]
|
||||
|
||||
|
||||
STUDIES = {"S1": s1_cells, "S2": s2_cells, "S3": s3_cells, "S4": s4_cells, "S8": s8_cells}
|
||||
|
||||
|
||||
def study_cells(p: dict, study: str, rids=None, regimes=None, **kw) -> list[Cell]:
|
||||
return STUDIES[study](p, rids=rids, regimes=regimes, **kw)
|
||||
|
||||
|
||||
def needs_posterior(cell: Cell) -> bool:
|
||||
return cell.posterior == "bench"
|
||||
90
ml_porosity/benchmark/data.py
Normal file
90
ml_porosity/benchmark/data.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""Inputs of protocol_bench: generator configuration, horizon grid, warp prior, wavelet, and the registration /
|
||||
training / metric blocks of protocol_p2 (the same objects scripts 11/14/15 build), plus the realization builder with
|
||||
misspecification presets and the nominal-fingerprint helper of tests/test_d2_misspec.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.benchmark.protocol import generator_config, protocol_p2
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid, preset_misspec
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
WELL_FIELDS = ("seis_clean", "noise_unit", "phi_t", "z_g", "z_b", "boundaries_t", "eps_a")
|
||||
OBS_KEYS = ("seis", "phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true")
|
||||
FP_DRIFT, FP_SNR_DB, FP_SIGMA_A, FP_DENSITY = (0.0, 1.0, 2.0), 10, 7.0, "full"
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def load_script(name: str):
|
||||
"""scripts/<name> as a module (scripts 11's reg_settings / method_specs / evaluate are the P2r semantics)."""
|
||||
spec = importlib.util.spec_from_file_location("bench_" + name[:2], REPO_ROOT / "scripts" / name)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
@dataclass
|
||||
class Inputs:
|
||||
p: dict
|
||||
cfg: dict
|
||||
hg: object
|
||||
prior_hyper: dict
|
||||
wav: np.ndarray
|
||||
P2: dict
|
||||
reg: dict
|
||||
tcfg: dict
|
||||
f_c: float
|
||||
|
||||
def realization(self, rid: int, preset: str | None) -> D2Realization:
|
||||
return D2Realization(self.cfg, int(rid), self.hg, WarpHyper(**self.prior_hyper), self.wav,
|
||||
misspec=preset_misspec(self.cfg, preset))
|
||||
|
||||
def regime(self, name: str) -> dict:
|
||||
return dict(self.cfg["regimes"][name])
|
||||
|
||||
@property
|
||||
def sigma_a(self) -> float:
|
||||
return float(self.cfg["anchors"]["sigma_a_ms"])
|
||||
|
||||
def observe(self, R: D2Realization, c: float, regime: str, N: int) -> tuple[list[dict], list[dict]]:
|
||||
"""Training observations (first N pool wells, regime anchors) and the 8 test wells (full anchors, same SNR),
|
||||
exactly as scripts 14/15."""
|
||||
st = self.regime(regime)
|
||||
obs = [R.observe(w, c, st["snr_db"], self.sigma_a, st["anchor_density"]) for w in R.pool[:N]]
|
||||
test = [R.observe(w, c, st["snr_db"], self.sigma_a) for w in R.test]
|
||||
return obs, test
|
||||
|
||||
|
||||
def load_inputs(p: dict) -> Inputs:
|
||||
cfg = generator_config(p)
|
||||
P2 = protocol_p2(p)
|
||||
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
|
||||
wp = p["inputs"]["warp_prior"]
|
||||
prior = json.loads((REPO_ROOT / wp["path"]).read_text())["fits"][wp["fit"]]
|
||||
wav = np.load(REPO_ROOT / p["inputs"]["wavelet"]["path"])[p["inputs"]["wavelet"]["key"]]
|
||||
run_d2 = load_script("11_run_d2.py")
|
||||
return Inputs(p, cfg, hg, prior["hyper"], wav, P2, run_d2.reg_settings(P2),
|
||||
P2["training"]["model"] | P2["training"]["optimizer"], float(P2["metrics"]["bands"]["f_c_hz"]))
|
||||
|
||||
|
||||
def _sha(chunks) -> str:
|
||||
h = hashlib.sha256()
|
||||
for a in chunks:
|
||||
h.update(np.ascontiguousarray(np.asarray(a)).tobytes())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def fingerprint_realization(R: D2Realization) -> dict:
|
||||
"""{"wells": {field: sha}, "obs": {key: sha}} as tests/test_d2_misspec.py records them."""
|
||||
wells = R.test + R.pool[:4]
|
||||
obs = [R.observe(w, c, FP_SNR_DB, FP_SIGMA_A, FP_DENSITY) for c in FP_DRIFT for w in wells]
|
||||
return {"wells": {k: _sha(getattr(w, k) for w in R.wells) for k in WELL_FIELDS},
|
||||
"obs": {k: _sha(o[k] for o in obs) for k in OBS_KEYS}}
|
||||
73
ml_porosity/benchmark/devbudgets.py
Normal file
73
ml_porosity/benchmark/devbudgets.py
Normal file
@@ -0,0 +1,73 @@
|
||||
"""S4 TCN budgets on dev realizations (protocol_p2 budget_selection rule applied to the TCN backbone).
|
||||
|
||||
Every S4 method is trained with the TCN at every candidate budget (one trajectory per seed) on dev realizations
|
||||
902–905 at R10, c = 1, N ∈ {4, 16}, seeds 0–1; per method the budget with the smallest mean total RMSE (macro over
|
||||
test wells → mean over rid × N × seed) is selected. The dev SMC posteriors of those cells are produced by the
|
||||
ordinary posterior stage (outputs/bench/dev/posterior/R10). Output: outputs/bench/dev/budgets_tcn.json; the chosen
|
||||
values are copied into protocol_bench.yaml training.budgets_tcn before the lock.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell, bench_root, posterior_paths, train_paths
|
||||
from ml_porosity.benchmark.protocol import check_rids, dev_stamp, fingerprint
|
||||
from ml_porosity.benchmark.runner import cell_from, make_jobs, posterior_worker, run_jobs
|
||||
from ml_porosity.f3.progress import write_json
|
||||
|
||||
DEV_RIDS = (902, 903, 904, 905)
|
||||
DEV_SEEDS = (0, 1)
|
||||
|
||||
|
||||
def dev_budget_worker(job: dict) -> dict:
|
||||
import torch
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.training import train_cell
|
||||
|
||||
torch.set_num_threads(job["threads"])
|
||||
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
|
||||
paths = train_paths(cell, root)
|
||||
if paths["meta"].exists() and json.loads(paths["meta"].read_text()).get("fingerprint") == job["key"]:
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
cand = [int(b) for b in p["training"]["budget_candidates"]]
|
||||
post = posterior_paths(cell, root, int(p["registration"]["reg_seed"]))
|
||||
rows, diag, _, meta = train_cell(cell, p, load_inputs(p), job["device"], post, save_preds=False, seeds=job["seeds"],
|
||||
budget_lists={m.removesuffix("-TCN"): cand for m in cell.methods})
|
||||
paths["csv"].parent.mkdir(parents=True, exist_ok=True)
|
||||
pd.DataFrame(diag).to_csv(paths["diag"], index=False)
|
||||
pd.DataFrame(rows).to_csv(paths["csv"], index=False)
|
||||
write_json(paths["meta"], meta | {"fingerprint": job["key"], "candidates": cand, "cell": dataclasses.asdict(cell)})
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
def dev_budgets(p: dict, device: str, workers: int, mem_gb: float, threads: int, rids=None) -> dict:
|
||||
rids = [int(r) for r in (rids or DEV_RIDS)]
|
||||
check_rids(rids, p, dev=True)
|
||||
s4, root, stamp = p["studies"]["S4"], bench_root(dev=True), dev_stamp(p)
|
||||
cells = [Cell("S4", "R10", None, 1.0, int(N), rid, tuple(s4["methods"]), backbone=s4["backbone"], posterior="bench")
|
||||
for N in s4["n_train"] for rid in rids]
|
||||
run_jobs(make_jobs(p, cells, "posterior", stamp, root, device, mem_gb, threads), posterior_worker, workers, root,
|
||||
"posterior:dev-budgets")
|
||||
jobs = []
|
||||
for c in cells:
|
||||
settings = dict(stage="dev-budgets", setting=c.setting, misspec=None, rid=c.rid, c=c.c, n_train=c.n_train, methods=list(c.methods),
|
||||
backbone=c.backbone, candidates=list(p["training"]["budget_candidates"]), seeds=list(DEV_SEEDS))
|
||||
jobs.append(dict(p=p, cell=dataclasses.asdict(c), root=str(root), device=device, mem_gb=mem_gb, threads=threads,
|
||||
seeds=list(DEV_SEEDS), key=fingerprint(stamp, **settings)))
|
||||
jobs.sort(key=lambda j: -j["cell"]["n_train"])
|
||||
run_jobs(jobs, dev_budget_worker, workers, root, "train:dev-budgets")
|
||||
df = pd.concat([pd.read_csv(train_paths(cell_from(j["cell"]), root)["csv"]) for j in jobs], ignore_index=True)
|
||||
run = df.groupby(["method", "budget", "rid", "n_train", "seed"])["rmse"].mean().groupby(["method", "budget"]).mean()
|
||||
chosen = {m.removesuffix("-TCN"): int(run.loc[m].idxmin()) for m in run.index.get_level_values(0).unique()}
|
||||
table = run.unstack("budget")
|
||||
out = {"rule": "protocol_p2 budget_selection (lowest mean total RMSE at c = 1 over dev rid × N × seed) applied to the TCN backbone",
|
||||
"rids": rids, "seeds": list(DEV_SEEDS), "candidates": list(p["training"]["budget_candidates"]), "budgets_tcn": chosen,
|
||||
"mean_total_rmse": {m: {int(b): float(v) for b, v in r.items()} for m, r in table.iterrows()}}
|
||||
(root / "budgets_tcn.json").write_text(json.dumps(out, indent=1))
|
||||
print(table.round(4).to_string())
|
||||
return out
|
||||
196
ml_porosity/benchmark/protocol.py
Normal file
196
ml_porosity/benchmark/protocol.py
Normal file
@@ -0,0 +1,196 @@
|
||||
"""Protocol loading, locking and realization guards for protocol_bench.
|
||||
|
||||
The lock (configs/protocol_bench.lock.json + .sha256) records the protocol text, the code (ml_porosity/**/*.py, the
|
||||
bench scripts, pyproject.toml), the environment, every hash-listed input, the protocol_p2r artifacts that S2/S4 read,
|
||||
and the nominal generator fingerprints of two realizations. Main realizations 8–15 are refused unless the lock exists
|
||||
and matches; dev realizations 900–905 never need the lock; the protocol_p2 realizations 0–7 are always refused.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from ml_porosity.f3.protocol import digest, environment
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
__all__ = ["CONFIG", "LOCK", "check_rids", "current_stamp", "dev_stamp", "fingerprint", "freeze", "load_protocol",
|
||||
"protocol_p2", "protocol_p2r", "generator_config"]
|
||||
|
||||
CONFIG = REPO_ROOT / "configs/protocol_bench.yaml"
|
||||
LOCK = REPO_ROOT / "configs/protocol_bench.lock.json"
|
||||
SCRIPTS = ("scripts/34_run_bench.py", "scripts/run_bench.sh")
|
||||
RESULT_DIRS = ("s1", "s2", "s3", "s4", "s8", "summary")
|
||||
|
||||
|
||||
def load_protocol(check_inputs: bool = True) -> dict:
|
||||
p = yaml.safe_load(CONFIG.read_text(encoding="utf-8"))
|
||||
if check_inputs:
|
||||
for k, v in p["inputs"].items():
|
||||
f = REPO_ROOT / v["path"]
|
||||
if not f.exists():
|
||||
raise FileNotFoundError(f"protocol_bench input {k} missing: {v['path']} (sync outputs/ first)")
|
||||
h = digest(f, text=f.suffix in (".yaml", ".json"))
|
||||
if v.get("sha256") not in (None, "TBD") and h != v["sha256"]:
|
||||
raise RuntimeError(f"{v['path']} differs from the hash recorded in protocol_bench ({h[:12]} ≠ {v['sha256'][:12]})")
|
||||
from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec
|
||||
cfg = generator_config(p)
|
||||
for name, spec in (p.get("calibration", {}).get("chosen") or {}).items():
|
||||
if normalize_misspec(spec) != normalize_misspec(preset_misspec(cfg, name)):
|
||||
raise RuntimeError(f"preset {name} in {p['inputs']['d2_config']['path']} differs from calibration.chosen of protocol_bench")
|
||||
return p
|
||||
|
||||
|
||||
def generator_config(p: dict) -> dict:
|
||||
return yaml.safe_load((REPO_ROOT / p["inputs"]["d2_config"]["path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def protocol_p2(p: dict) -> dict:
|
||||
"""protocol_p2: source of the registration, training and metric blocks (as scripts 14/15 use it)."""
|
||||
return yaml.safe_load((REPO_ROOT / p["inputs"]["protocol_p2"]["path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def protocol_p2r(p: dict) -> dict:
|
||||
return yaml.safe_load((REPO_ROOT / p["inputs"]["protocol_p2r"]["path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def code_files() -> list[Path]:
|
||||
paths = sorted((REPO_ROOT / "ml_porosity").rglob("*.py"))
|
||||
paths += [REPO_ROOT / s for s in SCRIPTS if (REPO_ROOT / s).exists()]
|
||||
return paths + [REPO_ROOT / "pyproject.toml"]
|
||||
|
||||
|
||||
def source_hash() -> str:
|
||||
h = hashlib.sha256()
|
||||
for f in code_files():
|
||||
h.update(f.relative_to(REPO_ROOT).as_posix().encode() + b"\0")
|
||||
h.update(f.read_bytes().replace(b"\r\n", b"\n") + b"\0")
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def p2r_reference_files(p: dict) -> list[Path]:
|
||||
"""protocol_p2r artifacts the benchmark reads: SMC particles and phase of the S4 cells, the per-regime runs.csv
|
||||
(S1 grid, S2 nominal reference, S3 join) and sigma_post.csv."""
|
||||
root = outputs_dir() / "p2r"
|
||||
ref = p["reference"]["p2r"]
|
||||
files = [root / "summary" / "sigma_post.csv"]
|
||||
files += [root / "train" / reg / "runs.csv" for reg in ref["regimes"]]
|
||||
for cell in p["studies"]["S4"]["cells"]:
|
||||
for N in p["studies"]["S4"]["n_train"]:
|
||||
for rid in p["grid"]["realizations"]:
|
||||
tag = f"r{rid}_c{cell['c']:g}_n{N}_s{p['registration']['reg_seed']}"
|
||||
files += [root / "posterior" / cell["regime"] / f"{tag}_particles.npz",
|
||||
root / "posterior" / cell["regime"] / f"{tag}_phase.json"]
|
||||
return files
|
||||
|
||||
|
||||
def portable(path: Path) -> str:
|
||||
path = path.resolve()
|
||||
for prefix, base in (("outputs", outputs_dir()), ("repo", REPO_ROOT)):
|
||||
try:
|
||||
return f"{prefix}:{path.relative_to(base.resolve()).as_posix()}"
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError(f"input outside the repository and outputs roots: {path}")
|
||||
|
||||
|
||||
def nominal_fingerprints(p: dict) -> dict:
|
||||
"""Recompute the nominal generator fingerprints of the realizations listed in the protocol and compare them with
|
||||
tests/data/d2_fingerprints.json (recorded before the misspecification parameters were added)."""
|
||||
from ml_porosity.benchmark.data import fingerprint_realization, load_inputs
|
||||
|
||||
inp = load_inputs(p)
|
||||
stored = json.loads((REPO_ROOT / p["inputs"]["fingerprints"]["path"]).read_text(encoding="utf-8"))
|
||||
out = {}
|
||||
for rid in p["reference"]["fingerprint_rids"]:
|
||||
fp = fingerprint_realization(inp.realization(rid, None))
|
||||
ref = stored["realizations"][str(rid)]
|
||||
ok = all(ref[block].get(k) == v for block, d in fp.items() for k, v in d.items() if k in ref[block])
|
||||
out[str(rid)] = {"match": bool(ok), "sha256_of_fingerprint": hashlib.sha256(json.dumps(fp, sort_keys=True).encode()).hexdigest()}
|
||||
if not ok:
|
||||
raise RuntimeError(f"nominal generator fingerprint of realization {rid} differs from tests/data/d2_fingerprints.json")
|
||||
return out
|
||||
|
||||
|
||||
def current_stamp(p: dict | None = None, with_fingerprints: bool = True) -> dict:
|
||||
p = load_protocol() if p is None else p
|
||||
inputs = {k: REPO_ROOT / v["path"] for k, v in p["inputs"].items()}
|
||||
refs = p2r_reference_files(p)
|
||||
missing = [f for f in list(inputs.values()) + refs if not f.exists()]
|
||||
if missing:
|
||||
raise FileNotFoundError(f"protocol_bench inputs missing (sync outputs/ first): {[str(f) for f in missing[:5]]}"
|
||||
f"{' ...' if len(missing) > 5 else ''}")
|
||||
stamp = {"protocol_sha256": digest(CONFIG, True), "code_sha256": source_hash(), "environment": environment(),
|
||||
"inputs": {portable(f): digest(f, f.suffix in (".yaml", ".json")) for f in inputs.values()},
|
||||
"p2r_reference": {portable(f): digest(f, f.suffix == ".json") for f in refs}}
|
||||
if with_fingerprints:
|
||||
stamp["nominal_fingerprints"] = nominal_fingerprints(p)
|
||||
return stamp
|
||||
|
||||
|
||||
def freeze(check: bool = False) -> dict:
|
||||
"""Return the lock; create it if absent and check is False. Any difference from an existing lock is an error."""
|
||||
p = load_protocol()
|
||||
stamp = current_stamp(p)
|
||||
if LOCK.exists():
|
||||
old = json.loads(LOCK.read_text(encoding="utf-8"))
|
||||
for k, v in stamp.items():
|
||||
if old[k] != v:
|
||||
raise RuntimeError(f"protocol_bench lock mismatch: {k}. Preserve results and create a new protocol version.")
|
||||
return old
|
||||
if check:
|
||||
raise RuntimeError("protocol_bench is not locked. Run the lock stage before any main-grid run.")
|
||||
if any((outputs_dir() / "bench" / d).exists() for d in RESULT_DIRS):
|
||||
raise RuntimeError("Refusing a first lock after protocol_bench results already exist.")
|
||||
if any(v.get("sha256") in (None, "TBD") for v in p["inputs"].values()):
|
||||
raise RuntimeError("protocol_bench.yaml has an input without a recorded sha256 (TBD): fill it before locking.")
|
||||
if p.get("status", "").upper().startswith("DRAFT"):
|
||||
raise RuntimeError("protocol_bench.yaml still says DRAFT: set status to LOCKED (with the date) before locking.")
|
||||
stamp |= {"locked_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and text inputs; binary inputs exact",
|
||||
"studies": sorted(p["studies"]), "realizations": p["grid"]["realizations"]}
|
||||
LOCK.write_text(json.dumps(stamp, indent=2), encoding="utf-8")
|
||||
CONFIG.with_suffix(".sha256").write_text(stamp["protocol_sha256"] + " configs/protocol_bench.yaml\n", encoding="utf-8")
|
||||
return stamp
|
||||
|
||||
|
||||
def dev_stamp(p: dict) -> dict:
|
||||
"""Resume key for dev and repro runs: the nominal generator (configuration without the preset block) and the
|
||||
registration block only; the misspecification preset enters the job settings as its normalised dict. Code and
|
||||
protocol edits during dev therefore do not invalidate the cache (dev outputs are never results)."""
|
||||
cfg = {k: v for k, v in generator_config(p).items() if k != "misspec_presets"}
|
||||
return {"dev": True, "generator_nominal_sha256": hashlib.sha256(json.dumps(cfg, sort_keys=True, default=str).encode()).hexdigest(),
|
||||
"registration": p["registration"]}
|
||||
|
||||
|
||||
def fingerprint(stamp: dict, **settings) -> str:
|
||||
return hashlib.sha256(json.dumps({"lock": stamp, **settings}, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def check_rids(rids, p: dict, dev: bool, repro: bool = False) -> None:
|
||||
"""Main realizations only under the lock; dev realizations only with dev=True; protocol_p2 realizations never;
|
||||
no mixing. repro: the single reproduction cell (reproduction.rid) is allowed without the lock."""
|
||||
rids = sorted(set(int(r) for r in rids))
|
||||
p2 = protocol_p2(p)["grid"]
|
||||
if bad := sorted(set(rids) & set(p2["realizations"])):
|
||||
raise SystemExit(f"realizations {bad} belong to the protocol_p2 main grid and are never used by protocol_bench")
|
||||
main, devs = set(p["grid"]["realizations"]), set(p["grid"]["dev_realizations"])
|
||||
if set(rids) & main and set(rids) & devs:
|
||||
raise SystemExit("do not mix main-grid and dev realizations in one run")
|
||||
if unknown := sorted(set(rids) - main - devs):
|
||||
raise SystemExit(f"realizations {unknown} are neither main-grid nor dev realizations of protocol_bench")
|
||||
if dev:
|
||||
if set(rids) & main:
|
||||
raise SystemExit("--dev runs use dev realizations 900–905 only")
|
||||
return
|
||||
if repro:
|
||||
if rids != [int(p["reproduction"]["rid"])]:
|
||||
raise SystemExit("the reproduction stage runs the single cell of protocol_bench reproduction:")
|
||||
return
|
||||
if set(rids) & devs:
|
||||
raise SystemExit("dev realizations require --dev (outputs go to outputs/bench/dev)")
|
||||
freeze(check=True)
|
||||
111
ml_porosity/benchmark/registration.py
Normal file
111
ml_porosity/benchmark/registration.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""SMC tie posterior of one cell: the computation of scripts/14_diag_posterior.py run_job restricted to the arm
|
||||
protocol_p2r used (statistical wavelet with the re-estimated phase, "estR"), with the same random streams
|
||||
(anchor samples [k, i, 13], phase fit [k, 19], SMC [k, i, 17]) and the same γ checkpoints (g_old, g_acf, g_one), so
|
||||
that the default generator reproduces the protocol_p2r particles. Only the γ = 1/κ (g_acf) particles are stored.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
OLD = ["B3b", "B3c", "B3d", "M1", "M2"]
|
||||
CHECKPOINTS = ("g_old", "g_acf", "g_one")
|
||||
|
||||
|
||||
def posterior_cell(R, inp, obs: list[dict], c: float, N: int, regime: dict, reg_seed: int, smc_seed: int,
|
||||
particles: int, device: str, mem_gb: float, paths: dict[str, Path], save=("estR/g_acf",),
|
||||
checkpoints=CHECKPOINTS, extra_meta: dict | None = None, phase_kw: dict | None = None) -> pd.DataFrame:
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.registration.pipeline import register
|
||||
from ml_porosity.registration.sampler import sample_warps
|
||||
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet, residual_kappa
|
||||
from ml_porosity.registration.tie_likelihood import synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
reg, cfg = dict(inp.reg), inp.cfg
|
||||
k = smc_seed
|
||||
mm = (R.t_ext >= R.t_main[0]) & (R.t_ext <= R.t_main[-1])
|
||||
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
|
||||
if device == "cpu":
|
||||
from ml_porosity.registration.smc import smc_fit_phase, smc_tie_posterior
|
||||
wrap = lambda T: T
|
||||
else:
|
||||
import torch
|
||||
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
|
||||
dev = torch.device(device)
|
||||
if dev.type == "cuda": # shared GPU: exceeding the cap makes this job OOM rather than encroach on others
|
||||
total = torch.cuda.get_device_properties(dev).total_memory
|
||||
torch.cuda.set_per_process_memory_fraction(min(1.0, mem_gb * 2**30 / total), dev)
|
||||
wrap = lambda T: TiePosteriorTorch(T, device)
|
||||
|
||||
t_all = time.time()
|
||||
out = register(R, obs, reg, reg_seed)
|
||||
h = WarpHyper(**out["hyper"])
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
B = phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), int(round(R.dt / cfg["fine_dt_ms"])))
|
||||
Ts, Z0s = [], []
|
||||
for i, o in enumerate(obs):
|
||||
smp = sample_warps(R.grid, h, o["tau_k"], o["t_k"], particles, reg["g_max"], np.random.default_rng([k, i, 13]))
|
||||
Ts.append(wrap(TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine,
|
||||
R.t_ext, phase_wavelet(B, out["phase"]), seis[i], (R.t_main[0], R.t_main[-1]))))
|
||||
Z0s.append(Ts[-1].z(smp["u"]))
|
||||
t0 = time.time()
|
||||
phase_r, ph = smc_fit_phase(Ts, Z0s, B, out["phase"], [k, 19], **(phase_kw or {}))
|
||||
key = dict(rid=R.rid, c=c, n_train=N, seed=reg_seed, smc_seed=k, particles=particles, snr_db=regime["snr_db"],
|
||||
anchor_density=regime["anchor_density"], sigma_a_reg=reg["sigma_a_ms"], phase=out["phase"],
|
||||
phase_R=phase_r, phase_n=len(ph["phases"]), phase_edge=ph["edge"], phase_time_s=time.time() - t0)
|
||||
wavelets = {"estR": phase_wavelet(B, phase_r)}
|
||||
rows, saved = [], {}
|
||||
for i, o in enumerate(obs):
|
||||
d = out["diag"][i]
|
||||
for m in OLD:
|
||||
e = {kk.removeprefix(f"{m}_"): v for kk, v in d.items() if kk.startswith(f"{m}_warp")}
|
||||
rows.append(key | {"well": o["name"], "method": m, "wavelet": "est",
|
||||
"gamma": d["gamma"] if m == "M2" else np.nan} | e)
|
||||
ut = np.concatenate([[o["b"]], o["g"]])[None]
|
||||
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
|
||||
for wn, wf in wavelets.items():
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wf)[0]
|
||||
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
rows.append(key | {"well": o["name"], "method": "B3c", "wavelet": wn}
|
||||
| warp_errors(t3c[None], R.tau_fine, o["t_of_tau_true"], R.t_main))
|
||||
T = Ts[i].with_wavelet(wf)
|
||||
_, l0 = T.parts(Z0s[i])
|
||||
cks_all = {"g_old": d["gamma"], "g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
|
||||
cks = {n: cks_all[n] for n in checkpoints}
|
||||
t0, T.n_eval = time.time(), 0
|
||||
res = smc_tie_posterior(T, Z0s[i], cks.values(), np.random.default_rng([k, i, 17]))
|
||||
sg = pd.DataFrame(res["stages"])
|
||||
info = {"well": o["name"], "wavelet": wn, "kappa0": 1.0 / cks_all["g_acf"], "ll_true": float(T.loglik(ut)[0]),
|
||||
"ll_anchor_max": float(l0.max()), "n_stages": len(sg), "n_eval": T.n_eval,
|
||||
"time_s": time.time() - t0, "shrink_mean": float(sg["shrink"].mean()),
|
||||
"jump_z_min": float(sg["jump_z"].min()), "r_true": ncc(T.synth(ut)[0], seis[i])}
|
||||
for name, gk in cks.items():
|
||||
U = T.u(res["Z"][float(gk)])
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
|
||||
e = warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)
|
||||
syn_m = T.synth(U.mean(0)[None])[0]
|
||||
rows.append(key | info | {"method": f"SMC_{name}", "gamma": gk, "logZ": res["logZ"][float(gk)],
|
||||
"ll_max": float(res["ll"][float(gk)].max()),
|
||||
"ll_mean": float(res["ll"][float(gk)].mean()),
|
||||
"kappa_post": residual_kappa(syn_m, seis[i]), "r_post": ncc(syn_m, seis[i])} | e)
|
||||
if f"{wn}/{name}" in save:
|
||||
saved[f"{o['name']}/{wn}/{name}"] = U.astype(np.float32)
|
||||
paths["phase"].parent.mkdir(parents=True, exist_ok=True)
|
||||
paths["phase"].write_text(json.dumps({"phase0": out["phase"], "phase_R": phase_r} | ph))
|
||||
tmp = paths["particles"].with_suffix(".tmp.npz")
|
||||
np.savez_compressed(tmp, **saved)
|
||||
tmp.replace(paths["particles"])
|
||||
df = pd.DataFrame(rows)
|
||||
df.to_csv(paths["csv"], index=False)
|
||||
meta = {"wall_seconds": time.time() - t_all, "device": device, "particles": particles, "phase0": out["phase"],
|
||||
"phase_R": phase_r, "misspec_active": R.misspec_active, "monotone_repairs": R.misspec_info["monotone_repairs"],
|
||||
"hyper": out["hyper"], "lam": out["lam"], "tau_c": out["tau_c"], "checkpoints": list(checkpoints),
|
||||
"saved": sorted(saved)} | (extra_meta or {})
|
||||
return df, meta
|
||||
74
ml_porosity/benchmark/repro.py
Normal file
74
ml_porosity/benchmark/repro.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""P2r reproduction check: compare the reproduction cell of protocol_bench (outputs/bench/repro) with the stored
|
||||
protocol_p2r artifacts. The P2r guard hashes no code, so this comparison is the evidence that the runner's default
|
||||
path (generator, registration, SMC, label banks, training) is the one that produced outputs/p2r."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell, bench_root, posterior_paths, train_paths
|
||||
from ml_porosity.f3.progress import write_json
|
||||
from ml_porosity.paths import outputs_dir
|
||||
|
||||
|
||||
def _max_abs(a, b) -> float:
|
||||
a, b = np.asarray(a, float), np.asarray(b, float)
|
||||
return float(np.nanmax(np.abs(a - b))) if a.shape == b.shape else float("inf")
|
||||
|
||||
|
||||
def compare(p: dict) -> dict:
|
||||
rp = p["reproduction"]
|
||||
cell = Cell("S1", rp["regime"], None, float(rp["c"]), int(rp["n_train"]), int(rp["rid"]), tuple(rp["methods"]))
|
||||
root = bench_root(repro=True)
|
||||
reg_seed = int(p["registration"]["reg_seed"])
|
||||
new, ref = posterior_paths(cell, root, reg_seed), {}
|
||||
tag = f"r{cell.rid}_c{cell.c:g}_n{cell.n_train}_s{reg_seed}"
|
||||
p2r = outputs_dir() / "p2r"
|
||||
ref = {"csv": p2r / "posterior" / cell.regime / f"{tag}.csv", "particles": p2r / "posterior" / cell.regime / f"{tag}_particles.npz",
|
||||
"phase": p2r / "posterior" / cell.regime / f"{tag}_phase.json",
|
||||
"train_csv": p2r / "train" / cell.regime / "cells" / f"{cell.tag}.csv", "train_npz": p2r / "train" / cell.regime / "cells" / f"{cell.tag}.npz",
|
||||
"train_diag": p2r / "train" / cell.regime / "cells" / f"{cell.tag}_diag.csv"}
|
||||
out = {"cell": {"regime": cell.regime, "rid": cell.rid, "c": cell.c, "n_train": cell.n_train}, "posterior": {}, "train": {}}
|
||||
# posterior: phase, particles, warp diagnostics
|
||||
pn, pr = json.loads(new["phase"].read_text()), json.loads(ref["phase"].read_text())
|
||||
out["posterior"]["phase0"] = {"new": pn["phase0"], "p2r": pr["phase0"], "equal": pn["phase0"] == pr["phase0"]}
|
||||
out["posterior"]["phase_R"] = {"new": pn["phase_R"], "p2r": pr["phase_R"], "abs_diff_deg": abs(pn["phase_R"] - pr["phase_R"])}
|
||||
out["posterior"]["logZ_max_abs_diff"] = _max_abs(pn["logZ"], pr["logZ"]) if np.shape(pn["logZ"]) == np.shape(pr["logZ"]) else "shape differs"
|
||||
with np.load(new["particles"]) as zn, np.load(ref["particles"]) as zr:
|
||||
keys = sorted(k for k in zn.files if k in zr.files)
|
||||
out["posterior"]["particle_keys_compared"] = keys
|
||||
diffs = {k: _max_abs(zn[k], zr[k]) for k in keys}
|
||||
out["posterior"]["particles_max_abs_diff"] = diffs
|
||||
out["posterior"]["particles_bitwise"] = all(np.array_equal(zn[k], zr[k]) for k in keys)
|
||||
out["posterior"]["warp_mean_max_abs_diff_ms"] = {k: _max_abs(zn[k].mean(0), zr[k].mean(0)) for k in keys}
|
||||
dn, dr = pd.read_csv(new["csv"]), pd.read_csv(ref["csv"])
|
||||
m = dn.merge(dr, on=["well", "method", "wavelet"], suffixes=("_new", "_p2r"))
|
||||
cols = ["warp_rmse_ms", "warp_cov90", "warp_width90_ms", "logZ", "kappa_post", "r_post"]
|
||||
out["posterior"]["csv_max_abs_diff"] = {c: _max_abs(m[f"{c}_new"], m[f"{c}_p2r"]) for c in cols if f"{c}_new" in m}
|
||||
out["posterior"]["n_stages"] = {"new": dn[dn.method == "SMC_g_acf"].n_stages.tolist(), "p2r": dr[dr.method == "SMC_g_acf"].n_stages.tolist()}
|
||||
# training: per (method, seed, test well) metrics and predictions
|
||||
tn, tr = pd.read_csv(train_paths(cell, root)["csv"]), pd.read_csv(ref["train_csv"])
|
||||
keys = ["method", "seed", "budget", "test_well"]
|
||||
mt = tn.merge(tr, on=keys, suffixes=("_new", "_p2r"))
|
||||
out["train"]["rows_compared"] = int(len(mt))
|
||||
for c in ("band_rmse", "rmse", "band_pcc", "nll", "coverage_90"):
|
||||
out["train"][f"{c}_max_abs_diff"] = _max_abs(mt[f"{c}_new"], mt[f"{c}_p2r"])
|
||||
per_m = {m_: _max_abs(g[f"band_rmse_new"], g[f"band_rmse_p2r"]) for m_, g in mt.groupby("method")}
|
||||
out["train"]["band_rmse_max_abs_diff_per_method"] = per_m
|
||||
cm = mt.groupby("method")[["band_rmse_new", "band_rmse_p2r"]].mean()
|
||||
out["train"]["cell_mean_band_rmse"] = {m_: {"new": float(r.band_rmse_new), "p2r": float(r.band_rmse_p2r)} for m_, r in cm.iterrows()}
|
||||
with np.load(train_paths(cell, root)["npz"]) as zn, np.load(ref["train_npz"]) as zr:
|
||||
ks = sorted(k for k in zn.files if k in zr.files and k.endswith("/mu"))
|
||||
out["train"]["pred_mu_max_abs_diff_pu"] = {k: _max_abs(zn[k], zr[k]) for k in ks}
|
||||
out["train"]["pred_bitwise"] = all(np.array_equal(zn[k], zr[k]) for k in ks)
|
||||
out["train"]["y_true_bitwise"] = bool(np.array_equal(zn["y_true"], zr["y_true"]))
|
||||
gn, gr = pd.read_csv(train_paths(cell, root)["diag"]), pd.read_csv(ref["train_diag"])
|
||||
g = gn.merge(gr, on="well", suffixes=("_new", "_p2r"))
|
||||
out["train"]["diag_max_abs_diff"] = {c: _max_abs(g[f"{c}_new"], g[f"{c}_p2r"]) for c in ("B3c-R_warp_rmse_ms", "B3d-Sa_warp_rmse_ms", "lam", "phase_R")}
|
||||
out["train"]["M2-Sa_n_valid_equal"] = bool((g["M2-Sa_n_valid_new"] == g["M2-Sa_n_valid_p2r"]).all())
|
||||
write_json(root / "comparison.json", out)
|
||||
return out
|
||||
233
ml_porosity/benchmark/runner.py
Normal file
233
ml_porosity/benchmark/runner.py
Normal file
@@ -0,0 +1,233 @@
|
||||
"""Resumable stages of protocol_bench: posterior (SMC), train, with fingerprinted completion markers.
|
||||
|
||||
Completion marker of a job: its `.json` sidecar carrying the resume fingerprint (lock stamp + cell settings) and the
|
||||
SHA-256 of every artifact. A job whose sidecar matches is skipped; a sidecar with a different fingerprint or a
|
||||
mismatched artifact raises (use a new output root), as in ml_porosity/volve/runner.py. Dev runs (realizations
|
||||
900–905) write under outputs/bench/dev with a protocol-and-generator-only fingerprint; the reproduction cell writes
|
||||
under outputs/bench/repro. Neither is a result.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
|
||||
from datetime import datetime
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import (Cell, bench_root, needs_posterior, posterior_dir, posterior_paths,
|
||||
study_cells, train_paths)
|
||||
from ml_porosity.benchmark.protocol import check_rids, dev_stamp, digest, fingerprint, freeze, generator_config
|
||||
from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec
|
||||
from ml_porosity.f3.progress import write_json
|
||||
|
||||
|
||||
def _threads(n: int) -> None:
|
||||
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS", "NUMBA_NUM_THREADS"):
|
||||
os.environ.setdefault(k, str(n))
|
||||
|
||||
|
||||
def cell_from(d: dict) -> Cell:
|
||||
d = dict(d)
|
||||
d["methods"], d["tags"] = tuple(d["methods"]), tuple(d.get("tags", ()))
|
||||
return Cell(**d)
|
||||
|
||||
|
||||
def reusable(meta: Path, key: str, artifacts: list[Path]) -> bool:
|
||||
if not meta.exists():
|
||||
return False
|
||||
stored = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if stored.get("fingerprint") != key:
|
||||
raise RuntimeError(f"resume fingerprint mismatch: {meta}. Use a new output root (or a new protocol version).")
|
||||
for a in artifacts:
|
||||
if not a.exists() or digest(a) != stored.get("artifact_sha256", {}).get(a.name):
|
||||
raise RuntimeError(f"missing or mismatched completed artifact: {a}")
|
||||
return True
|
||||
|
||||
|
||||
def sidecar(meta_path: Path, key: str, artifacts: list[Path], extra: dict) -> None:
|
||||
write_json(meta_path, extra | {"fingerprint": key, "artifact_sha256": {a.name: digest(a) for a in artifacts},
|
||||
"finished": datetime.now().astimezone().isoformat(timespec="seconds")})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- workers (importable, spawn context)
|
||||
|
||||
def posterior_worker(job: dict) -> dict:
|
||||
import torch
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.registration import posterior_cell
|
||||
|
||||
torch.set_num_threads(job["threads"])
|
||||
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
|
||||
reg_seed = int(p["registration"]["reg_seed"])
|
||||
paths = posterior_paths(cell, root, reg_seed)
|
||||
arts = [paths["csv"], paths["particles"], paths["phase"]]
|
||||
if reusable(paths["meta"], job["key"], arts):
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
inp = load_inputs(p)
|
||||
R = inp.realization(cell.rid, cell.preset)
|
||||
obs, _ = inp.observe(R, cell.c, cell.regime, cell.n_train)
|
||||
smc = p["registration"]["smc"]
|
||||
_, meta = posterior_cell(R, inp, obs, cell.c, cell.n_train, inp.regime(cell.regime), reg_seed,
|
||||
int(smc["smc_seed"]), int(smc["particles"]), job["device"], job["mem_gb"], paths,
|
||||
checkpoints=tuple(smc["checkpoints"]), extra_meta={"cell": dataclasses.asdict(cell)},
|
||||
phase_kw={k: smc[f"phase_{k}"] for k in ("step", "half_width", "max_extra") if f"phase_{k}" in smc})
|
||||
sidecar(paths["meta"], job["key"], arts, meta)
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
def training_worker(job: dict) -> dict:
|
||||
import torch
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.training import train_cell
|
||||
|
||||
torch.set_num_threads(job["threads"])
|
||||
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
|
||||
paths = train_paths(cell, root)
|
||||
arts = [paths["csv"], paths["npz"], paths["diag"]]
|
||||
if reusable(paths["meta"], job["key"], arts):
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
post = posterior_paths(cell, root, int(p["registration"]["reg_seed"])) if cell.posterior != "none" else None
|
||||
if post is not None and not post["particles"].exists():
|
||||
raise FileNotFoundError(f"{cell.tag}: posterior not available at {post['particles']}")
|
||||
inp = load_inputs(p)
|
||||
rows, diag, preds, meta = train_cell(cell, p, inp, job["device"], post, save_preds=True, seeds=job.get("seeds"))
|
||||
paths["csv"].parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = paths["npz"].with_suffix(".tmp.npz")
|
||||
np.savez_compressed(tmp, **preds)
|
||||
tmp.replace(paths["npz"])
|
||||
pd.DataFrame(diag).to_csv(paths["diag"], index=False)
|
||||
pd.DataFrame(rows).to_csv(paths["csv"], index=False)
|
||||
sidecar(paths["meta"], job["key"], arts, meta | {"cell": dataclasses.asdict(cell)})
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- pools
|
||||
|
||||
def progress(root: Path, name: str, **values) -> None:
|
||||
path = root / "progress.json"
|
||||
for attempt in range(10):
|
||||
try:
|
||||
old = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||
old[name] = old.get(name, {}) | values | {"updated": datetime.now().astimezone().isoformat(timespec="seconds")}
|
||||
write_json(path, old)
|
||||
return
|
||||
except (PermissionError, json.JSONDecodeError):
|
||||
time.sleep(0.25 * (attempt + 1))
|
||||
|
||||
|
||||
def run_jobs(jobs: list[dict], fn, workers: int, root: Path, name: str) -> list[dict]:
|
||||
if not jobs:
|
||||
print(f"{name}: nothing to do", flush=True)
|
||||
return []
|
||||
started, results = time.perf_counter(), []
|
||||
progress(root, name, status="running", completed=0, total=len(jobs), error=None)
|
||||
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context("spawn")) as pool:
|
||||
futures = {pool.submit(fn, job): job for job in jobs}
|
||||
pending = set(futures)
|
||||
while pending:
|
||||
done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED)
|
||||
for fut in done:
|
||||
try:
|
||||
result = fut.result()
|
||||
except Exception as exc:
|
||||
for other in pending:
|
||||
other.cancel()
|
||||
progress(root, name, status="failed; pending jobs cancelled", error=f"{futures[fut]['cell']['study']} "
|
||||
f"{futures[fut]['cell']['regime']} {futures[fut]['cell']['rid']}: {exc}")
|
||||
raise
|
||||
results.append(result)
|
||||
fresh = sum(not r.get("cached") for r in results)
|
||||
elapsed = time.perf_counter() - started
|
||||
eta = elapsed / fresh * (len(jobs) - len(results)) if fresh else None
|
||||
progress(root, name, completed=len(results), cached=len(results) - fresh, elapsed_seconds=elapsed, eta_seconds=eta)
|
||||
print(f"[{name} {len(results)}/{len(jobs)}] {'cached ' if result.get('cached') else ''}{result['path']}"
|
||||
f"{'' if result.get('cached') else f' ({result.get('wall_seconds', 0):.0f} s)'} "
|
||||
f"elapsed {elapsed:.0f} s{'' if eta is None else f', eta {eta:.0f} s'}", flush=True)
|
||||
progress(root, name, status="done", eta_seconds=0)
|
||||
return results
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- planning
|
||||
|
||||
def plan(p: dict, studies: list[str], rids=None, regimes=None, presets=None, controls: bool = False,
|
||||
grid: dict | None = None) -> list[Cell]:
|
||||
cells = []
|
||||
for s in studies:
|
||||
kw = {"presets": presets, "controls": controls} if s == "S2" else {}
|
||||
cells += study_cells(p, s, rids=rids, regimes=regimes, grid=grid, **kw)
|
||||
return cells
|
||||
|
||||
|
||||
def stamp_for(p: dict, mode: str) -> dict:
|
||||
if mode == "dev":
|
||||
return dev_stamp(p)
|
||||
if mode == "repro":
|
||||
return dev_stamp(p) | {"repro": True}
|
||||
return freeze(check=True)
|
||||
|
||||
|
||||
def make_jobs(p: dict, cells: list[Cell], stage: str, stamp: dict, root: Path, device: str, workers_mem_gb: float,
|
||||
threads: int, seeds=None) -> list[dict]:
|
||||
jobs, seen = [], set()
|
||||
cfg = generator_config(p)
|
||||
for cell in cells:
|
||||
misspec = normalize_misspec(preset_misspec(cfg, cell.preset))
|
||||
if stage == "posterior":
|
||||
if not needs_posterior(cell):
|
||||
continue
|
||||
ident = (cell.study, cell.setting, cell.rid, cell.c, cell.n_train)
|
||||
settings = dict(stage="posterior", setting=cell.setting, regime=cell.regime, preset=cell.preset, misspec=misspec,
|
||||
rid=cell.rid, c=cell.c, n_train=cell.n_train, reg_seed=p["registration"]["reg_seed"],
|
||||
smc=p["registration"]["smc"])
|
||||
else:
|
||||
ident = (cell.study, cell.setting, cell.tag, cell.backbone)
|
||||
settings = dict(stage="train", study=cell.study, setting=cell.setting, regime=cell.regime, preset=cell.preset,
|
||||
misspec=misspec, rid=cell.rid, c=cell.c, n_train=cell.n_train, methods=list(cell.methods), backbone=cell.backbone,
|
||||
delta_ms=cell.delta_ms, posterior=cell.posterior, seeds=list(p["grid"]["seeds"] if seeds is None else seeds),
|
||||
budgets={m: p["training"]["budgets"].get(m.removesuffix("-TCN")) for m in cell.methods},
|
||||
equal_budget_arm=p["training"].get("equal_budget_arm"))
|
||||
if ident in seen:
|
||||
continue
|
||||
seen.add(ident)
|
||||
jobs.append(dict(p=p, cell=dataclasses.asdict(cell), root=str(root), device=device, mem_gb=workers_mem_gb,
|
||||
threads=threads, seeds=seeds, key=fingerprint(stamp, **settings)))
|
||||
# largest N first keeps the wall-clock tail short (as scripts 14/15)
|
||||
jobs.sort(key=lambda j: (-j["cell"]["n_train"], j["cell"]["rid"]))
|
||||
return jobs
|
||||
|
||||
|
||||
def run(stage: str, p: dict, studies: list[str], device: str, workers: int, mem_gb: float, threads: int = 2,
|
||||
mode: str = "main", rids=None, regimes=None, presets=None, controls: bool = False, seeds=None,
|
||||
root: Path | None = None, grid: dict | None = None) -> list[dict]:
|
||||
"""stage: posterior | train. mode: main (locked), dev (outputs/bench/dev), repro (outputs/bench/repro).
|
||||
grid / seeds: dev-only overrides of the (c, N) lists and the network seeds."""
|
||||
_threads(threads)
|
||||
if (grid or seeds) and mode != "dev":
|
||||
raise SystemExit("--drift / --n-train / --seeds are dev-only overrides")
|
||||
if mode == "repro":
|
||||
rp = p["reproduction"]
|
||||
rids, regimes = [rp["rid"]], [rp["regime"]]
|
||||
cells = [Cell("S1", rp["regime"], None, float(rp["c"]), int(rp["n_train"]), int(rp["rid"]), tuple(rp["methods"]))]
|
||||
else:
|
||||
cells = plan(p, studies, rids=rids, regimes=regimes, presets=presets, controls=controls, grid=grid)
|
||||
check_rids([c.rid for c in cells] or (rids or []), p, dev=(mode == "dev"), repro=(mode == "repro"))
|
||||
stamp = stamp_for(p, mode)
|
||||
root = root or bench_root(dev=(mode == "dev"), repro=(mode == "repro"))
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
jobs = make_jobs(p, cells, stage, stamp, root, device, mem_gb, threads, seeds)
|
||||
name = f"{stage}:{'+'.join(studies) if mode != 'repro' else 'repro'}:{mode}"
|
||||
print(f"{name}: {len(jobs)} jobs, {workers} workers, device {device}, root {root}", flush=True)
|
||||
fn = posterior_worker if stage == "posterior" else training_worker
|
||||
return run_jobs(jobs, fn, workers, root, name)
|
||||
|
||||
|
||||
def status(root: Path) -> str:
|
||||
path = root / "progress.json"
|
||||
return path.read_text(encoding="utf-8") if path.exists() else "protocol_bench has not started."
|
||||
539
ml_porosity/benchmark/summary.py
Normal file
539
ml_porosity/benchmark/summary.py
Normal file
@@ -0,0 +1,539 @@
|
||||
"""Pre-declared analyses of protocol_bench (hypotheses block of configs/protocol_bench.yaml), applied as written.
|
||||
|
||||
Rules are those of protocol_p2 / protocol_p2r through scripts/13 (gate_gb, boot) and scripts/18 (pair_cell). Runs of
|
||||
the P2r cells come from outputs/p2r (reference, read-only). Everything is reported regardless of direction; a
|
||||
hypothesis of kind `claim` gets a pass/fail, `descriptive` items get tables only.
|
||||
→ <root>/summary/: s1_cells.csv, s1_h2a.csv, s1_families.csv, s1_additivity.csv, s2_cells.csv, s2_smc.csv, s2_h2a.csv,
|
||||
s2_degradation.csv, s3_h2a.csv, s3_table.csv, s4_cells.csv, s4_h2a.csv, s8_cells.csv, s8_transfer.csv, verdict.json,
|
||||
summary.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell, bench_root, study_cells, train_paths
|
||||
from ml_porosity.benchmark.data import load_script
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
sp13 = load_script("13_summarize_p2.py")
|
||||
METRICS = sp13.METRICS
|
||||
Z90 = 3.29
|
||||
NFFT = 256
|
||||
POINT_TIES = ["B3b", "B3c", "B3c-R"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- loading
|
||||
|
||||
def _runs_from_cells(files: list[Path], budgets: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
if not files:
|
||||
return pd.DataFrame(), pd.DataFrame()
|
||||
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
df = df[df["budget"] == df["method"].map(lambda m: budgets.get(m, np.nan))]
|
||||
by = ["study", "regime", "preset", "delta_ms", "rid", "c", "n_train", "method", "seed"]
|
||||
by = [b for b in by if b in df.columns]
|
||||
run = df.groupby(by, as_index=False, dropna=False)[METRICS].mean()
|
||||
return df, run
|
||||
|
||||
|
||||
def study_budgets(p: dict, study: str, arm: int | None = None) -> dict:
|
||||
"""Registered budgets per method (TCN names for S4); arm: the equal-budget arm instead (every method at `arm`)."""
|
||||
b = dict(p["training"]["budgets"])
|
||||
if p["studies"][study].get("backbone", "cnngru") != "cnngru":
|
||||
alt = p["training"].get("budgets_tcn") or {}
|
||||
b = {f"{m}-TCN": int(alt.get(m, v)) for m, v in b.items()}
|
||||
if arm:
|
||||
b = {m: int(arm) for m in b}
|
||||
return b
|
||||
|
||||
|
||||
def load_study(p: dict, root: Path, study: str, arm: int | None = None) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
|
||||
"""(rows, runs, diag) of every completed cell of a study under root at the registered budgets (arm=None) or at
|
||||
the equal-budget arm."""
|
||||
d = root / study.lower() / "train"
|
||||
files = sorted(f for f in d.glob("*/cells/*.csv") if not f.name.endswith("_diag.csv")) if d.exists() else []
|
||||
rows, run = _runs_from_cells(files, study_budgets(p, study, arm))
|
||||
diag = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True) if files else pd.DataFrame()
|
||||
return rows, run, diag
|
||||
|
||||
|
||||
USE_P2R = True # set to False by summarize(dev=True): a dev summary must never read main-grid results
|
||||
|
||||
|
||||
def p2r_runs(p: dict) -> pd.DataFrame:
|
||||
root = REPO_ROOT / p["reference"]["p2r"]["root"]
|
||||
parts = []
|
||||
if not USE_P2R:
|
||||
return pd.DataFrame()
|
||||
for reg in p["reference"]["p2r"]["regimes"]:
|
||||
f = root / "train" / reg / "runs.csv"
|
||||
if f.exists():
|
||||
parts.append(pd.read_csv(f).assign(regime=reg, preset="nominal", study="P2r"))
|
||||
return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame()
|
||||
|
||||
|
||||
def sigma_post_table(dirs: dict[str, Path]) -> pd.DataFrame:
|
||||
"""σ_post and SMC diagnostics per (setting, c, N) from posterior CSVs (SMC_g_acf, estR), mean over wells then rids."""
|
||||
rows = []
|
||||
for setting, d in dirs.items():
|
||||
files = sorted(d.glob("r*_s*.csv")) if d.exists() else []
|
||||
if not files:
|
||||
continue
|
||||
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
s = df[(df.method == "SMC_g_acf") & (df.wavelet == "estR")]
|
||||
per = s.groupby(["c", "n_train", "rid"]).agg(width90=("warp_width90_ms", "mean"), warp_rmse_ms=("warp_rmse_ms", "mean"),
|
||||
warp_cov90=("warp_cov90", "mean"), kappa_post=("kappa_post", "mean"),
|
||||
r_post=("r_post", "mean"), phase_R=("phase_R", "first"), phase0=("phase", "first"))
|
||||
per["sigma_post_ms"] = per.width90 / Z90
|
||||
per["overconfidence"] = per.warp_rmse_ms / per.sigma_post_ms
|
||||
g = per.groupby(["c", "n_train"]).agg(sigma_post_ms=("sigma_post_ms", "mean"), warp_rmse_ms=("warp_rmse_ms", "mean"),
|
||||
warp_cov90=("warp_cov90", "mean"), overconfidence=("overconfidence", "mean"),
|
||||
kappa_post=("kappa_post", "mean"), r_post=("r_post", "mean"),
|
||||
phase_R_mean=("phase_R", "mean"), phase_R_abs_mean=("phase_R", lambda x: float(np.mean(np.abs(x)))),
|
||||
n_rid=("sigma_post_ms", "size")).reset_index()
|
||||
rows.append(g.assign(setting=setting))
|
||||
return pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- rules
|
||||
|
||||
def h2a_cells(run: pd.DataFrame, cand: str, comp: list[str], rng, n_boot: int) -> pd.DataFrame:
|
||||
"""protocol_p2 cell rule with `cand` in the role of M2 against the best of `comp` (scripts/13 gate_gb)."""
|
||||
r = run[run.method.isin(comp) | (run.method == cand)].replace({"method": {cand: "M2"}})
|
||||
if r.empty or "M2" not in set(r.method) or not (set(r.method) & set(comp)):
|
||||
return pd.DataFrame()
|
||||
if any(m.endswith("-TCN") for m in comp): # gate_gb reads 'B3b' by name: drop the backbone suffix locally
|
||||
r = r.assign(method=r.method.str.replace("-TCN", "", regex=False))
|
||||
comp = [m.removesuffix("-TCN") for m in comp]
|
||||
grid = {"n_train": sorted(r.n_train.unique().tolist()), "drift_factors": sorted(r.c.unique().tolist()),
|
||||
"realistic_drift": 1, "realizations": sorted(r.rid.unique().tolist()), "seeds": sorted(r.seed.unique().tolist())}
|
||||
cells, _ = sp13.gate_gb(r, {"grid": grid, "gates": {"G-B": {"competitors": comp}}}, n_boot, rng)
|
||||
return cells
|
||||
|
||||
|
||||
def pair(run: pd.DataFrame, a: str, b: str, rng, n_boot: int) -> dict:
|
||||
"""Ratio mean(a)/mean(b) of band RMSE with CI over realizations and the 'better' rule (scripts/18 pair_cell)."""
|
||||
x = run[run.method == a].set_index(["rid", "seed"])["band_rmse"]
|
||||
y = run[run.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index)
|
||||
ok = y.notna()
|
||||
x, y = x[ok], y[ok]
|
||||
if len(x) == 0:
|
||||
return {}
|
||||
d = x - y
|
||||
ds, dr = d.groupby("seed").mean(), d.groupby("rid").mean()
|
||||
lo, hi = sp13.boot(x.groupby("rid").mean().to_numpy(), y.groupby("rid").mean().to_numpy(), n_boot, rng)
|
||||
return {"ratio": float(x.mean() / y.mean()), "ratio_lo": lo, "ratio_hi": hi, "seeds_better": int((ds < 0).sum()),
|
||||
"rids_better": int((dr < 0).sum()), "n_seed": len(ds), "n_rid": len(dr),
|
||||
"better": bool((ds < 0).sum() >= math.ceil(sp13.SEED_FRAC * len(ds) - 1e-9) and (dr < 0).sum() > len(dr) / 2)}
|
||||
|
||||
|
||||
def perm_spearman(x, y, groups, rng, n_perm: int) -> tuple[float, float]:
|
||||
"""Spearman ρ(x, y) and one-sided permutation p (ρ ≤ observed) permuting y within groups."""
|
||||
from scipy.stats import spearmanr
|
||||
|
||||
x, y, groups = np.asarray(x, float), np.asarray(y, float), np.asarray(groups)
|
||||
if len(x) < 3:
|
||||
return float("nan"), float("nan")
|
||||
rho = spearmanr(x, y).statistic
|
||||
idx = {g: np.flatnonzero(groups == g) for g in np.unique(groups)}
|
||||
cnt = 0
|
||||
for _ in range(n_perm):
|
||||
yp = y.copy()
|
||||
for ii in idx.values():
|
||||
yp[ii] = y[rng.permutation(ii)]
|
||||
cnt += spearmanr(x, yp).statistic <= rho
|
||||
return float(rho), float(cnt / n_perm)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S1
|
||||
|
||||
def s1(p: dict, root: Path, rng, n_boot: int, n_perm: int) -> tuple[dict, dict]:
|
||||
_, run_new, _ = load_study(p, root, "S1")
|
||||
run = pd.concat([p2r_runs(p), run_new], ignore_index=True) if len(run_new) else p2r_runs(p)
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
sp = sigma_post_table({reg: root / "posterior" / reg for reg in p["studies"]["S1"]["regimes"]})
|
||||
sp_ref = REPO_ROOT / p["reference"]["p2r"]["root"] / "summary" / "sigma_post.csv"
|
||||
if sp_ref.exists() and USE_P2R:
|
||||
ref = pd.read_csv(sp_ref).rename(columns={"setting": "regime"})
|
||||
ref = ref[ref.regime.isin(p["studies"]["S1"]["regimes"])][["regime", "c", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]]
|
||||
sp = pd.concat([sp.rename(columns={"setting": "regime"}), ref.assign(source="p2r")], ignore_index=True) if len(sp) else ref.assign(source="p2r")
|
||||
else:
|
||||
sp = sp.rename(columns={"setting": "regime"})
|
||||
tables, verdict = {}, {}
|
||||
# phase-diagram cells: per (regime, c, N) band RMSE per method, ratios with CI
|
||||
cells = []
|
||||
for (reg, c, N), g in run.groupby(["regime", "c", "n_train"]):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "c": c, "n_train": N, "n_rid": g.rid.nunique(), "n_seed": g.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
if "M2-Sa" in mean and "B3d-Sa" in mean:
|
||||
row |= {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa", "B3d-Sa", rng, n_boot).items()}
|
||||
pt = [m for m in POINT_TIES if m in mean.index]
|
||||
if pt and "B3d-Sa" in mean:
|
||||
best = mean.loc[pt].idxmin()
|
||||
row |= {"best_point_tie": best} | {f"pm_best_{k}": v for k, v in pair(g, "B3d-Sa", best, rng, n_boot).items()}
|
||||
cells.append(row)
|
||||
cells = pd.DataFrame(cells).merge(sp[["regime", "c", "n_train", "sigma_post_ms"]].drop_duplicates(["regime", "c", "n_train"]),
|
||||
on=["regime", "c", "n_train"], how="left")
|
||||
tables["s1_cells"] = cells
|
||||
# H2a rule at every (regime, c, N) (S1-H1: R10, c = 1.5, both N)
|
||||
h2a = []
|
||||
for reg, g in run.groupby("regime"):
|
||||
t = h2a_cells(g, "B3d-Sa", POINT_TIES, rng, n_boot)
|
||||
if len(t):
|
||||
h2a.append(t.assign(regime=reg))
|
||||
h2a = pd.concat(h2a, ignore_index=True) if h2a else pd.DataFrame()
|
||||
tables["s1_h2a"] = h2a
|
||||
if len(h2a):
|
||||
t = h2a[(h2a.regime == "R10") & (h2a.c == 1.5)]
|
||||
verdict["S1-H1"] = {"cells": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()},
|
||||
"ratios": {int(r.n_train): [r.ratio, r.ratio_lo, r.ratio_hi] for r in t.itertuples()},
|
||||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None,
|
||||
"complete": bool(len(t) == 2 and (t.n_rid == len(p["grid"]["realizations"])).all())}
|
||||
# S1-H2: families with σ_post(N = 16) ≥ 1.5 ms; r(N) decreasing in N
|
||||
wide16 = cells[(cells.n_train == 16) & (cells.sigma_post_ms >= 1.5)][["regime", "c"]]
|
||||
fam = cells.merge(wide16, on=["regime", "c"]).dropna(subset=["m2_pm_ratio"])
|
||||
fam["family"] = fam.regime + "_c" + fam.c.map(lambda v: f"{v:g}")
|
||||
tables["s1_families"] = fam[["family", "regime", "c", "n_train", "sigma_post_ms", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better"]]
|
||||
if len(fam):
|
||||
r16 = fam[fam.n_train == 16].set_index("family").m2_pm_ratio
|
||||
r2 = fam[fam.n_train == 2].set_index("family").m2_pm_ratio
|
||||
both = r16.index.intersection(r2.index)
|
||||
sign = int((r16[both] < r2[both]).sum())
|
||||
rho, pval = perm_spearman(np.log2(fam.n_train), fam.m2_pm_ratio, fam.family, rng, n_perm)
|
||||
a = bool(len(both) > 0 and sign >= math.ceil(2 / 3 * len(both) - 1e-9))
|
||||
b = bool(rho < 0 and pval < 0.05)
|
||||
verdict["S1-H2"] = {"families": sorted(fam.family.unique()), "families_with_N2_and_N16": int(len(both)), "r16_below_r2": sign,
|
||||
"a_sign": a, "spearman_rho": rho, "perm_p_one_sided": pval, "b_dose": b,
|
||||
"pass": (a and b) if len(both) > 0 and fam.n_train.nunique() >= 3 else None}
|
||||
# S1-D additivity: band_rmse²(B3d-Sa) = band_rmse²(Oracle) + β σ_post² per regime
|
||||
add = []
|
||||
for reg, g in cells.dropna(subset=["sigma_post_ms"]).groupby("regime"):
|
||||
if "band_rmse_B3d-Sa" not in g or "band_rmse_Oracle" not in g:
|
||||
continue
|
||||
y = g["band_rmse_B3d-Sa"] ** 2 - g["band_rmse_Oracle"] ** 2
|
||||
x = g["sigma_post_ms"] ** 2
|
||||
if len(g) < 3 or x.var() == 0:
|
||||
continue
|
||||
beta = float((x * y).sum() / (x * x).sum())
|
||||
resid = y - beta * x
|
||||
add.append({"regime": reg, "n_cells": len(g), "beta_pu2_per_ms2": beta,
|
||||
"r2": float(1 - (resid ** 2).sum() / ((y - y.mean()) ** 2).sum()) if (y - y.mean()).abs().sum() > 0 else float("nan")})
|
||||
tables["s1_additivity"] = pd.DataFrame(add)
|
||||
return tables, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S2
|
||||
|
||||
def s2(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
_, run, diag = load_study(p, root, "S2")
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
s = p["studies"]["S2"]
|
||||
axes = {name: axis for axis, names in s["presets"].items() for name in names}
|
||||
levels = {name: i + 1 for names in s["presets"].values() for i, name in enumerate(names)}
|
||||
settings = {f"{reg}__{name}": root / "posterior" / f"{reg}__{name}" for reg in s["regimes"] for name in list(axes) + list(s.get("controls", {}).get("presets", []))}
|
||||
smc = sigma_post_table(settings)
|
||||
if len(smc):
|
||||
smc["regime"] = smc.setting.str.split("__").str[0]
|
||||
smc["preset"] = smc.setting.str.split("__").str[1]
|
||||
smc["axis"] = smc.preset.map(lambda n: axes.get(n, "control"))
|
||||
smc["level"] = smc.preset.map(lambda n: levels.get(n, 0))
|
||||
tables = {"s2_smc": smc}
|
||||
ref = p2r_runs(p)
|
||||
cells, h2a_rows, verdict = [], [], {"S2-H1": {"per_axis": {}}, "S2-H2": {"pairs": {}}}
|
||||
for (reg, name), g in run.groupby(["regime", "preset"]):
|
||||
h = h2a_cells(g, "B3d-Sa", POINT_TIES, rng, n_boot)
|
||||
if len(h):
|
||||
h2a_rows.append(h.assign(regime=reg, preset=name, axis=axes.get(name, "control"), level=levels.get(name, 0)))
|
||||
ratios = {}
|
||||
for N, gN in g.groupby("n_train"):
|
||||
mean = gN.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "preset": name, "axis": axes.get(name, "control"), "level": levels.get(name, 0), "c": 1.0, "n_train": N,
|
||||
"n_rid": gN.rid.nunique(), "n_seed": gN.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
pr = pair(gN, "M2-Sa", "B3d-Sa", rng, n_boot)
|
||||
row |= {f"m2_pm_{k}": v for k, v in pr.items()}
|
||||
ratios[N] = pr.get("ratio", np.nan)
|
||||
if "Ctl-GP" in mean.index: # disclosed (T2 ii)
|
||||
row |= {f"ctl_pm_{k}": v for k, v in pair(gN, "Ctl-GP", "B3d-Sa", rng, n_boot).items()}
|
||||
row |= {f"m2_ctl_{k}": v for k, v in pair(gN, "M2-Sa", "Ctl-GP", rng, n_boot).items()}
|
||||
pt = [m for m in POINT_TIES if m in mean.index]
|
||||
if pt and "B3d-Sa" in mean:
|
||||
best = mean.loc[pt].idxmin()
|
||||
row |= {"best_point_tie": best} | {f"pm_best_{k}": v for k, v in pair(gN, "B3d-Sa", best, rng, n_boot).items()}
|
||||
row["pm_no_harm"] = bool(row["pm_best_ratio"] <= sp13.GUARD)
|
||||
# degradation vs the P2r nominal cell (descriptive)
|
||||
if len(ref):
|
||||
nom = ref[(ref.regime == reg) & (ref.c == 1) & (ref.n_train == N)]
|
||||
for m in mean.index:
|
||||
nm = nom[nom.method == m]
|
||||
if len(nm):
|
||||
row[f"degradation_{m}"] = float(mean[m] / nm.band_rmse.mean())
|
||||
sm = smc[(smc.setting == f"{reg}__{name}") & (smc.n_train == N)] if len(smc) else pd.DataFrame()
|
||||
if len(sm):
|
||||
row |= {k: float(sm.iloc[0][k]) for k in ("sigma_post_ms", "warp_rmse_ms", "warp_cov90", "overconfidence")}
|
||||
row["wide"] = bool(row["sigma_post_ms"] >= 1.5)
|
||||
cells.append(row)
|
||||
if name in axes:
|
||||
mean_ratio = float(np.nanmean(list(ratios.values()))) if ratios else float("nan")
|
||||
verdict["S2-H2"]["pairs"][f"{reg}/{name}"] = {"mean_ratio_M2-Sa/B3d-Sa": mean_ratio, "ok": bool(mean_ratio <= sp13.GUARD),
|
||||
"n_cells": len(ratios)}
|
||||
tables["s2_cells"] = pd.DataFrame(cells)
|
||||
h2a = pd.concat(h2a_rows, ignore_index=True) if h2a_rows else pd.DataFrame()
|
||||
tables["s2_h2a"] = h2a
|
||||
for axis, names in s["presets"].items():
|
||||
l1 = names[0]
|
||||
t = h2a[(h2a.regime == "R10") & (h2a.preset == l1) & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||||
per = {}
|
||||
for reg in s["regimes"]:
|
||||
for name in names:
|
||||
tt = h2a[(h2a.regime == reg) & (h2a.preset == name) & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||||
per[f"{reg}/{name}"] = {int(r.n_train): {"cell_pass": bool(r.cell_pass), "ratio": r.ratio, "ci": [r.ratio_lo, r.ratio_hi], "best": r.best}
|
||||
for r in tt.itertuples()}
|
||||
verdict["S2-H1"]["per_axis"][axis] = {"L1_R10_cells_pass": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()},
|
||||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None,
|
||||
"complete": bool(len(t) == 2 and (t.n_rid == len(p["grid"]["realizations"])).all()),
|
||||
"all_cells": per}
|
||||
verdict["S2-H1"]["axes_pass"] = [a for a, v in verdict["S2-H1"]["per_axis"].items() if v["pass"]]
|
||||
verdict["S2-H1"]["pass_all_axes"] = bool(len(verdict["S2-H1"]["axes_pass"]) == len(s["presets"]))
|
||||
pairs = verdict["S2-H2"]["pairs"]
|
||||
expected = len(s["regimes"]) * sum(len(v) for v in s["presets"].values())
|
||||
verdict["S2-H2"]["complete"] = bool(len(pairs) == expected)
|
||||
verdict["S2-H2"]["pass"] = all(v["ok"] for v in pairs.values()) if len(pairs) == expected else None
|
||||
tables["s2_degradation"] = tables["s2_cells"][[c for c in tables["s2_cells"].columns if c.startswith("degradation_") or c in ("regime", "preset", "axis", "level", "n_train")]] if len(cells) else pd.DataFrame()
|
||||
return tables, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S3
|
||||
|
||||
def s3(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
_, run_b4, _ = load_study(p, root, "S3")
|
||||
ref = p2r_runs(p)
|
||||
if run_b4.empty or ref.empty:
|
||||
return {}, {"available": False}
|
||||
comp = POINT_TIES + list(p["studies"]["S3"]["methods"])
|
||||
run = pd.concat([ref, run_b4], ignore_index=True)
|
||||
rows, verdict = [], {"per_regime": {}}
|
||||
for reg, g in run.groupby("regime"):
|
||||
if "B3d-Sa" not in set(g.method):
|
||||
continue
|
||||
cells = h2a_cells(g, "B3d-Sa", comp, rng, n_boot)
|
||||
if not len(cells):
|
||||
continue
|
||||
rows.append(cells.assign(regime=reg, flag=np.where(cells.c == 2, "unstable posterior", "")))
|
||||
c1, c0 = cells[cells.c == 1], cells[cells.c == 0]
|
||||
macro = c0.m2_band_rmse.mean() / c0.best_band_rmse.mean() if len(c0) else float("nan")
|
||||
guard = bool(len(c0) == 2 and macro <= sp13.GUARD and (c0.ratio <= sp13.GUARD).all())
|
||||
verdict["per_regime"][reg] = {"c1_cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}", "best_at_c1": {int(r.n_train): r.best for r in c1.itertuples()},
|
||||
"zero_drift_macro_ratio": macro, "zero_drift_guard": guard,
|
||||
"regime_pass": bool(len(c1) == 2 and c1.cell_pass.all() and guard),
|
||||
"complete": bool((cells.n_rid == len(p["grid"]["realizations"])).all() and len(cells) == 6)}
|
||||
tab = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||||
h2a_regimes = ["R10", "R0", "Rm5"]
|
||||
verdict["pass"] = verdict["per_regime"].get("R10", {}).get("regime_pass")
|
||||
verdict["regimes_pass"] = [r for r in h2a_regimes if verdict["per_regime"].get(r, {}).get("regime_pass")]
|
||||
table = run.groupby(["regime", "c", "n_train", "method"])["band_rmse"].mean().unstack("method").reset_index()
|
||||
ctl = []
|
||||
if "Ctl-GP" in set(run.method): # T2-1 (disclosed): control bank across the P2r grid
|
||||
for (reg, c, N), g in run.groupby(["regime", "c", "n_train"]):
|
||||
if "Ctl-GP" not in set(g.method):
|
||||
continue
|
||||
ctl.append({"regime": reg, "c": c, "n_train": N, "n_rid": g.rid.nunique(), "flag": "unstable posterior" if c == 2 else ""}
|
||||
| {f"ctl_pm_{k}": v for k, v in pair(g, "Ctl-GP", "B3d-Sa", rng, n_boot).items()}
|
||||
| {f"m2_ctl_{k}": v for k, v in pair(g, "M2-Sa", "Ctl-GP", rng, n_boot).items()}
|
||||
| {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa", "B3d-Sa", rng, n_boot).items()})
|
||||
ctl = pd.DataFrame(ctl)
|
||||
if len(ctl) and {"m2_ctl_better", "ctl_pm_better"} <= set(ctl.columns):
|
||||
verdict["T2-1"] = {"cells": int(len(ctl)), "m2_better_than_ctl": int(ctl.m2_ctl_better.sum()),
|
||||
"m2_better_than_ctl_by_c": {f"c{c:g}": int(d.m2_ctl_better.sum()) for c, d in ctl.groupby("c")},
|
||||
"ctl_better_than_pm": int(ctl.ctl_pm_better.sum())}
|
||||
return {"s3_h2a": tab, "s3_table": table, "s3_control": ctl}, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S4
|
||||
|
||||
def s4(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
_, run, _ = load_study(p, root, "S4")
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
pt = [f"{m}-TCN" for m in POINT_TIES]
|
||||
rows, verdict = [], {}
|
||||
for reg, g in run.groupby("regime"):
|
||||
cells = h2a_cells(g, "B3d-Sa-TCN", pt, rng, n_boot)
|
||||
if len(cells):
|
||||
rows.append(cells.assign(regime=reg))
|
||||
h2a = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||||
t = h2a[(h2a.regime == "R10") & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||||
verdict["S4-H1"] = {"cells": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()}, "ratios": {int(r.n_train): [r.ratio, r.ratio_lo, r.ratio_hi] for r in t.itertuples()},
|
||||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None}
|
||||
cells = []
|
||||
ref = p2r_runs(p)
|
||||
for (reg, N), g in run.groupby(["regime", "n_train"]):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "c": 1.0, "n_train": N, "n_rid": g.rid.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
row |= {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa-TCN", "B3d-Sa-TCN", rng, n_boot).items()}
|
||||
if len(ref):
|
||||
nom = ref[(ref.regime == reg) & (ref.c == 1) & (ref.n_train == N)]
|
||||
for m in mean.index:
|
||||
nm = nom[nom.method == m.removesuffix("-TCN")]
|
||||
if len(nm):
|
||||
row[f"tcn_over_cnngru_{m.removesuffix('-TCN')}"] = float(mean[m] / nm.band_rmse.mean())
|
||||
cells.append(row)
|
||||
cells = pd.DataFrame(cells)
|
||||
wide = cells[(cells.n_train == 16) & cells.regime.isin(["Rm5", "R0h"])]
|
||||
verdict["S4-H2"] = {"cells": {r.regime: {"ratio": r.m2_pm_ratio, "ci": [r.m2_pm_ratio_lo, r.m2_pm_ratio_hi], "better": bool(r.m2_pm_better)} for r in wide.itertuples()},
|
||||
"pass": bool(wide.m2_pm_better.all()) if len(wide) == 2 else None}
|
||||
return {"s4_cells": cells, "s4_h2a": h2a}, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S8
|
||||
|
||||
def cross_spectrum(Y: np.ndarray, P: np.ndarray) -> np.ndarray:
|
||||
w = np.hanning(Y.shape[1])
|
||||
Fy = np.fft.rfft((Y - Y.mean(1, keepdims=True)) * w, NFFT)
|
||||
Fp = np.fft.rfft((P - P.mean(1, keepdims=True)) * w, NFFT)
|
||||
return np.real(np.conj(Fy) * Fp).sum(0)
|
||||
|
||||
|
||||
def s8(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
rows_all, run, _ = load_study(p, root, "S8")
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
f = np.fft.rfftfreq(NFFT, 4.0 / 1000.0)
|
||||
f_c = 6.0
|
||||
budgets = study_budgets(p, "S8")
|
||||
cells, transfer, verdict = [], [], {"S8-H1": {"cells": {}}, "S8-H2": {"cells": {}}}
|
||||
for (reg, d, N), g in run.groupby(["regime", "delta_ms", "n_train"]):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "delta_ms": d, "n_train": N, "n_rid": g.rid.nunique(), "n_seed": g.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
for a, b, tag in (("PM2", "Oracle", "pm_or"), ("BK2", "PM2", "bk_pm"), ("HM2", "PM2", "hm_pm"), ("BK2", "Oracle", "bk_or")):
|
||||
row |= {f"{tag}_{k}": v for k, v in pair(g, a, b, rng, n_boot).items()}
|
||||
# transfer Ĥ(f) relative to the Oracle predictions, pooled over rids, seeds and test wells
|
||||
S = {m: np.zeros(len(f)) for m in ("Oracle", "PM2", "BK2", "HM2")}
|
||||
for rid in sorted(g.rid.unique()):
|
||||
cell = Cell("S8", reg, None, 1.0, int(N), int(rid), tuple(p["studies"]["S8"]["methods"]), posterior="none", delta_ms=float(d))
|
||||
npz = train_paths(cell, root)["npz"]
|
||||
if not npz.exists():
|
||||
continue
|
||||
with np.load(npz) as z:
|
||||
Y = z["y_true"].astype(float)
|
||||
for m in S:
|
||||
for k in (k for k in z.files if k.startswith(f"{m}/s") and k.endswith(f"/b{budgets[m]}/mu")):
|
||||
S[m] += cross_spectrum(Y, z[k].astype(float))
|
||||
band = f >= f_c
|
||||
use = band & (S["Oracle"] >= 0.1 * S["Oracle"][band].max())
|
||||
lo, hi = 1000.0 / (2 * d), 3000.0 / (2 * d)
|
||||
flip = use & (f > lo) & (f < hi)
|
||||
for m in ("PM2", "BK2", "HM2"):
|
||||
H = S[m] / np.where(S["Oracle"] == 0, np.nan, S["Oracle"])
|
||||
theory = np.cos(np.pi * f * d / 1000.0)
|
||||
zero = f[band][np.flatnonzero(np.diff(np.sign(H[band])) != 0)[:1]]
|
||||
transfer.append({"regime": reg, "delta_ms": d, "n_train": N, "method": m, "flip_band_hz": [lo, hi], "n_freq_flip": int(flip.sum()),
|
||||
"mean_H_flip_band": float(np.nanmean(H[flip])) if flip.any() else float("nan"),
|
||||
"mean_cos_flip_band": float(theory[flip].mean()) if flip.any() else float("nan"),
|
||||
"first_zero_crossing_hz": float(zero[0]) if len(zero) else float("nan"), "theory_zero_hz": lo,
|
||||
"H": H.tolist(), "f_hz": f.tolist()})
|
||||
row[f"meanH_flip_{m}"] = transfer[-1]["mean_H_flip_band"]
|
||||
cells.append(row)
|
||||
if reg == "R10" and d == 32:
|
||||
verdict["S8-H1"]["cells"][int(N)] = {"mean_H_PM2_flip_band": row["meanH_flip_PM2"], "negative": bool(row["meanH_flip_PM2"] < 0)}
|
||||
if N == 16 and d in (16, 32):
|
||||
verdict["S8-H2"]["cells"][f"{reg}/d{d:g}"] = {"ratio_BK2_PM2": row.get("bk_pm_ratio"), "ci": [row.get("bk_pm_ratio_lo"), row.get("bk_pm_ratio_hi")],
|
||||
"better": bool(row.get("bk_pm_better", False))}
|
||||
cells = pd.DataFrame(cells)
|
||||
verdict["S8-H1"]["pass"] = all(v["negative"] for v in verdict["S8-H1"]["cells"].values()) if len(verdict["S8-H1"]["cells"]) == 2 else None
|
||||
d8 = cells[cells.delta_ms == 8]
|
||||
no_harm = float(d8.bk_pm_ratio.mean()) if len(d8) else float("nan")
|
||||
verdict["S8-H2"]["no_harm_mean_ratio_d8"] = no_harm
|
||||
verdict["S8-H2"]["pass"] = all(v["better"] for v in verdict["S8-H2"]["cells"].values()) if len(verdict["S8-H2"]["cells"]) == 4 else None
|
||||
verdict["S8-H2"]["d8_descriptive"] = {f"{r.regime}/n{int(r.n_train)}": [r.bk_pm_ratio, r.bk_pm_ratio_lo, r.bk_pm_ratio_hi] for r in d8.itertuples()}
|
||||
tr = pd.DataFrame(transfer)
|
||||
return {"s8_cells": cells, "s8_transfer": tr.drop(columns=["H", "f_hz"]) if len(tr) else tr,
|
||||
"s8_transfer_curves": tr}, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- equal-budget arm (disclosed, T2 v)
|
||||
|
||||
def equal_budget(p: dict, root: Path, rng, n_boot: int) -> pd.DataFrame:
|
||||
arm = p["training"].get("equal_budget_arm")
|
||||
if not arm:
|
||||
return pd.DataFrame()
|
||||
rows = []
|
||||
for study in p["studies"]:
|
||||
_, run, _ = load_study(p, root, study, arm=int(arm))
|
||||
if run.empty:
|
||||
continue
|
||||
keys = [k for k in ("regime", "preset", "delta_ms", "c", "n_train") if k in run.columns]
|
||||
for key, g in run.groupby(keys, dropna=False):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"study": study, "budget": int(arm)} | dict(zip(keys, key)) | {"n_rid": g.rid.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
sfx = "-TCN" if p["studies"][study].get("backbone", "cnngru") != "cnngru" else ""
|
||||
for a, b, tag in ((f"M2-Sa{sfx}", f"B3d-Sa{sfx}", "m2_pm"), (f"B3d-Sa{sfx}", f"Oracle{sfx}", "pm_or"), ("Ctl-GP", f"B3d-Sa{sfx}", "ctl_pm"),
|
||||
("BK2", "PM2", "bk_pm"), ("PM2", "Oracle", "pm2_or")):
|
||||
if a in mean.index and b in mean.index:
|
||||
row |= {f"{tag}_{k}": v for k, v in pair(g, a, b, rng, n_boot).items() if k in ("ratio", "ratio_lo", "ratio_hi", "better")}
|
||||
rows.append(row)
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- report
|
||||
|
||||
def _md(df: pd.DataFrame, cols=None, fmt: str = ".3f") -> str:
|
||||
if df is None or not len(df):
|
||||
return "(no data)"
|
||||
d = df[[c for c in cols if c in df.columns]] if cols else df
|
||||
return d.to_markdown(index=False, floatfmt=fmt)
|
||||
|
||||
|
||||
def summarize(p: dict, root: Path, n_boot: int = 2000, dev: bool = False, n_perm: int = 10000) -> dict:
|
||||
global USE_P2R
|
||||
USE_P2R = not dev
|
||||
out = root / "summary"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
rng = np.random.default_rng(0)
|
||||
tables, verdict = {}, {"protocol": "configs/protocol_bench.yaml", "dev": dev, "root": str(root)}
|
||||
sha = REPO_ROOT / "configs" / "protocol_bench.sha256"
|
||||
verdict["protocol_sha256"] = sha.read_text().split()[0] if sha.exists() else "UNLOCKED"
|
||||
for name, fn, extra in (("S1", s1, (n_perm,)), ("S2", s2, ()), ("S3", s3, ()), ("S4", s4, ()), ("S8", s8, ())):
|
||||
t, v = fn(p, root, rng, n_boot, *extra)
|
||||
tables |= t
|
||||
verdict[name] = v
|
||||
tables["equal_budget"] = equal_budget(p, root, rng, n_boot)
|
||||
for name, df in tables.items():
|
||||
if name == "s8_transfer_curves":
|
||||
(out / "s8_transfer_curves.json").write_text(df.to_json(orient="records"))
|
||||
elif isinstance(df, pd.DataFrame):
|
||||
df.to_csv(out / f"{name}.csv", index=False)
|
||||
(out / "verdict.json").write_text(json.dumps(verdict, indent=1, default=float))
|
||||
L = [f"# protocol_bench summary ({'DEV — never a result' if dev else 'main grid'})", "",
|
||||
"Rules of configs/protocol_bench.yaml applied as written. Realizations and seeds as recorded per cell.", ""]
|
||||
hyp = p["hypotheses"]
|
||||
for key in ("S1-H1", "S1-H2", "S2-H1", "S2-H2", "S3-H1", "S4-H1", "S4-H2", "S8-H1", "S8-H2"):
|
||||
v = verdict.get(key.split("-")[0], {})
|
||||
v = v.get(key, v) if key != "S3-H1" else v
|
||||
res = v.get("pass") if isinstance(v, dict) else None
|
||||
L.append(f"- **{key}** ({hyp[key]['kind']}): {'PASS' if res else 'FAIL' if res is False else 'not available'} — {hyp[key]['statement'].strip()[:160]}…")
|
||||
L.append("")
|
||||
sections = [("S1 cells (phase diagram)", "s1_cells", ["regime", "c", "n_train", "sigma_post_ms", "best_point_tie", "pm_best_ratio", "pm_best_ratio_lo", "pm_best_ratio_hi", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better", "n_rid"]),
|
||||
("S1 families (S1-H2)", "s1_families", None), ("S1 additivity (descriptive)", "s1_additivity", None),
|
||||
("S2 SMC diagnostics", "s2_smc", ["regime", "preset", "axis", "level", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90", "overconfidence", "phase_R_mean", "kappa_post", "r_post", "n_rid"]),
|
||||
("S2 cells", "s2_cells", ["regime", "preset", "axis", "level", "n_train", "best_point_tie", "pm_best_ratio", "pm_best_ratio_lo", "pm_best_ratio_hi", "pm_no_harm", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better", "wide", "n_rid"]),
|
||||
("S2 H2a rule per preset", "s2_h2a", ["regime", "preset", "axis", "level", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]),
|
||||
("S3 H2a rule with B4 competitors", "s3_h2a", ["regime", "c", "n_train", "best", "runner_up", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass", "flag"]),
|
||||
("S3 benchmark table (band RMSE)", "s3_table", None),
|
||||
("S3 control bank across the P2r grid (T2-1, disclosed)", "s3_control", ["regime", "c", "n_train", "ctl_pm_ratio", "ctl_pm_ratio_lo", "ctl_pm_ratio_hi", "ctl_pm_better", "m2_ctl_ratio", "m2_ctl_ratio_lo", "m2_ctl_ratio_hi", "m2_ctl_better", "m2_pm_ratio", "flag", "n_rid"]),
|
||||
("S4 cells (TCN)", "s4_cells", None), ("S4 H2a rule (TCN)", "s4_h2a", ["regime", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]),
|
||||
("S8 cells", "s8_cells", ["regime", "delta_ms", "n_train", "pm_or_ratio", "bk_pm_ratio", "bk_pm_ratio_lo", "bk_pm_ratio_hi", "bk_pm_better", "hm_pm_ratio", "meanH_flip_PM2", "meanH_flip_BK2", "n_rid"]),
|
||||
("S8 transfer", "s8_transfer", ["regime", "delta_ms", "n_train", "method", "n_freq_flip", "mean_H_flip_band", "mean_cos_flip_band", "first_zero_crossing_hz", "theory_zero_hz"]),
|
||||
("Equal-budget arm, 500 iterations for every method (disclosed, T2 v; no rule uses it)", "equal_budget", None)]
|
||||
for title, key, cols in sections:
|
||||
L += [f"## {title}", "", _md(tables.get(key), cols), ""]
|
||||
L += ["## Verdicts (json)", "", "```", json.dumps({k: v for k, v in verdict.items() if k.startswith("S")}, indent=1, default=float), "```", ""]
|
||||
(out / "summary.md").write_text("\n".join(L))
|
||||
print("\n".join(L[:14]))
|
||||
return verdict
|
||||
296
ml_porosity/benchmark/training.py
Normal file
296
ml_porosity/benchmark/training.py
Normal file
@@ -0,0 +1,296 @@
|
||||
"""Training of one protocol_bench cell: scripts/15_diag_train.py run_cell (variant "a": estR wavelet, γ = 1/κ) with
|
||||
three additions. (1) B4a–d from the protocol_p2 label banks (S3). (2) The S8 two-mode banks built from the true
|
||||
warp: per training well a side s = ±1 is drawn from a declared stream, the two modes are t_true and t_true + sΔ,
|
||||
PM2 labels sit at the posterior-mean warp t_true + sΔ/2, BK2 is the two-member bank with uniform π and the
|
||||
protocol λ, HM2 the same bank with the hard-min loss. (3) A second backbone (TCNHetero of ml_porosity/f3/training.py)
|
||||
trained with the same loop as bank_train.train_predict; the CNN-GRU path delegates to bank_train unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell
|
||||
from ml_porosity.benchmark.data import Inputs, load_script
|
||||
|
||||
REGISTER_METHODS = ("Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M1", "M2")
|
||||
POSTERIOR_METHODS = ("B3c-R", "B3d-Sa", "M2-Sa")
|
||||
TWO_MODE_METHODS = ("PM2", "BK2", "HM2")
|
||||
CONTROL_METHODS = ("Ctl-GP",)
|
||||
SIDE_STREAM = 20261030 # S8: rng [rid, SIDE_STREAM, 8, i] → side s_i = ±1 of training well i
|
||||
MIN_SLOPE_MS, MAX_ATTEMPTS = 0.05, 1280 # Ctl-GP: monotonicity guard and draw budget, as T2 (scripts/32)
|
||||
|
||||
|
||||
def budget_list(p: dict, method: str, backbone: str) -> list[int]:
|
||||
"""Registered budget plus, if declared, the equal-budget arm (one trajectory; predictions at both steps)."""
|
||||
b = {budget_of(p, method, backbone)}
|
||||
arm = p["training"].get("equal_budget_arm")
|
||||
if arm:
|
||||
b.add(int(arm))
|
||||
return sorted(b)
|
||||
|
||||
|
||||
def base_name(method: str) -> str:
|
||||
return method.removesuffix("-TCN")
|
||||
|
||||
|
||||
def budget_of(p: dict, method: str, backbone: str) -> int:
|
||||
b = base_name(method)
|
||||
if backbone != "cnngru":
|
||||
alt = p["training"].get(f"budgets_{backbone}") or {}
|
||||
if alt.get(b) is not None:
|
||||
return int(alt[b])
|
||||
return int(p["training"]["budgets"][b])
|
||||
|
||||
|
||||
def train_predict_tcn(X, Xte, spec: dict, cfg: dict, seed: int, budgets: list[int], device: str) -> dict:
|
||||
"""bank_train.train_predict with TCNHetero (f3.training) in place of CNNGRUHetero; cudnn deterministic as f3."""
|
||||
from ml_porosity.f3.training import TCNHetero
|
||||
from ml_porosity.losses.rml import bank_loss, gather_windows
|
||||
from ml_porosity.losses.softdtw import dilate_loss_fast, softdtw_loss_fast
|
||||
from ml_porosity.models.bank_train import WIN, window_starts_fixed
|
||||
from ml_porosity.models.train import predict
|
||||
|
||||
torch.backends.cudnn.benchmark = False
|
||||
torch.backends.cudnn.deterministic = True
|
||||
torch.default_generator.manual_seed(seed)
|
||||
if torch.device(device).type == "cuda":
|
||||
torch.cuda.set_device(device)
|
||||
torch.cuda.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
|
||||
x = T(X)
|
||||
N, _, L = X.shape
|
||||
starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device)
|
||||
kind = spec["kind"]
|
||||
if kind == "bank":
|
||||
Y, logpi, lam = T(spec["Y"]), T(spec["logpi"]), spec["lam"]
|
||||
loss_fn = lambda mu, s: bank_loss(mu, s, Y, logpi, starts, WIN, lam)
|
||||
elif kind in ("softdtw", "dilate"):
|
||||
yw = gather_windows(T(spec["Y"]).reshape(N, L), starts, WIN).reshape(-1, WIN)
|
||||
f = softdtw_loss_fast if kind == "softdtw" else dilate_loss_fast
|
||||
kw = {k: spec[k] for k in ("gamma", "band", "alpha") if k in spec}
|
||||
loss_fn = lambda mu, s: f(gather_windows(mu, starts, WIN).reshape(-1, WIN),
|
||||
gather_windows(s, starts, WIN).reshape(-1, WIN), yw, **kw)
|
||||
else:
|
||||
raise ValueError(kind)
|
||||
model = TCNHetero(X.shape[1], cfg["d_channels"], cfg["p_dropout"]).to(device)
|
||||
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
|
||||
out = {}
|
||||
for step in range(1, max(budgets) + 1):
|
||||
model.train()
|
||||
opt.zero_grad()
|
||||
mu, s = model(x)
|
||||
loss = loss_fn(mu[:, 0], s[:, 0])
|
||||
if not torch.isfinite(loss):
|
||||
raise FloatingPointError(f"non-finite loss at step {step}")
|
||||
loss.backward()
|
||||
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
|
||||
opt.step()
|
||||
if step in budgets:
|
||||
out[step] = predict(model, Xte, device)
|
||||
return out
|
||||
|
||||
|
||||
def train_predict_any(X, Xte, spec, cfg, seed, budgets, device, backbone: str) -> dict:
|
||||
if backbone == "cnngru":
|
||||
from ml_porosity.models.bank_train import train_predict
|
||||
return train_predict(X, Xte, spec, cfg, seed, budgets, device)
|
||||
if backbone == "tcn":
|
||||
return train_predict_tcn(X, Xte, spec, cfg, seed, budgets, device)
|
||||
raise ValueError(backbone)
|
||||
|
||||
|
||||
def posterior_banks(R, obs: list[dict], out: dict, reg: dict, ph: dict, smc, reg_seed: int, diag: list[dict]) -> tuple[dict, list]:
|
||||
"""B3c-R, B3d-Sa (mean of all particles) and M2-Sa (S particles without replacement, rng [reg_seed, i, 29],
|
||||
uniform π) exactly as scripts/15 (variant a: estR, g_acf). Appends per-well diagnostics to `diag`."""
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.smc import phase_basis, phase_wavelet
|
||||
from ml_porosity.registration.tie_likelihood import synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors, warp_mean
|
||||
|
||||
cfg = R.cfg
|
||||
f, fac = cfg["fine_dt_ms"], int(round(R.dt / cfg["fine_dt_ms"]))
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"])
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
err = lambda t, o: warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
banks, logpi = {"B3c-R": [], "B3d-Sa": [], "M2-Sa": []}, []
|
||||
for i, o in enumerate(obs):
|
||||
y_aa = antialias(o["phi_log"], f, R.dt)
|
||||
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wR)[0]
|
||||
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
banks["B3c-R"].append(lab(y_aa, t3c))
|
||||
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
|
||||
tm = warp_mean(Tf, np.zeros(len(Tf)))
|
||||
banks["B3d-Sa"].append(lab(y_aa, tm))
|
||||
sub = np.random.default_rng([reg_seed, i, 29]).choice(len(Tf), reg["S"], replace=False)
|
||||
Y = lab(y_aa, Tf[sub])
|
||||
ok = np.all(np.isfinite(Y), 1)
|
||||
Y[~ok] = Y[ok][0]
|
||||
banks["M2-Sa"].append(Y)
|
||||
logpi.append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum()))
|
||||
diag[i] |= {"phase_R": ph["phase_R"], "B3c-R_warp_rmse_ms": err(t3c, o), "B3d-Sa_warp_rmse_ms": err(tm, o),
|
||||
"M2-Sa_n_valid": int(ok.sum()),
|
||||
"sigma_post_ms": warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_width90_ms"] / 3.29}
|
||||
return banks, logpi
|
||||
|
||||
|
||||
def control_gp_bank(R, obs: list[dict], smc: dict, reg: dict, reg_seed: int, diag: list[dict]) -> tuple[list, list]:
|
||||
"""Ctl-GP (T2 test ii, scripts/32 control_bank): S warps T̄ + η_s, η_s Gaussian with the empirical mean and
|
||||
covariance of the SMC particles on the warp grid (no information beyond the first two moments; no link between
|
||||
a member and the seismic). rng [reg_seed, i, 2029]; a draw is kept if t(τ) is strictly increasing (slope >
|
||||
MIN_SLOPE_MS per node), else redrawn (≤ MAX_ATTEMPTS); fallback: Gaussian in u = [b, g] (monotone by
|
||||
construction), flagged. Labels and invalid members as the SMC bank."""
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
|
||||
f = R.cfg["fine_dt_ms"]
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
banks, logpi = [], []
|
||||
for i, o in enumerate(obs):
|
||||
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
|
||||
Tg = R.grid.t_of_tau(U[:, 0], U[:, 1:])
|
||||
Tbar = Tg.mean(0)
|
||||
lam, V = np.linalg.eigh(np.cov(Tg.T, ddof=0))
|
||||
Lm = V * np.sqrt(np.clip(lam, 0.0, None))[None, :]
|
||||
rng = np.random.default_rng([reg_seed, i, 2029])
|
||||
members, n_rej, attempts = [], 0, 0
|
||||
while len(members) < reg["S"] and attempts < MAX_ATTEMPTS:
|
||||
t = Tbar + Lm @ rng.standard_normal(len(Tbar))
|
||||
attempts += 1
|
||||
if np.all(np.diff(t) > MIN_SLOPE_MS):
|
||||
members.append(t)
|
||||
else:
|
||||
n_rej += 1
|
||||
fallback = len(members) < reg["S"]
|
||||
if fallback:
|
||||
lu, Vu = np.linalg.eigh(np.cov(U.T, ddof=0))
|
||||
Lu = Vu * np.sqrt(np.clip(lu, 0.0, None))[None, :]
|
||||
ubar = U.mean(0)
|
||||
while len(members) < reg["S"]:
|
||||
u = ubar + Lu @ rng.standard_normal(len(ubar))
|
||||
members.append(R.grid.t_of_tau(u[0], u[1:])[0])
|
||||
Tc_grid = np.stack(members)
|
||||
Tc = np.stack([np.interp(R.tau_fine, R.grid.tau, t) for t in Tc_grid])
|
||||
Y = lab(antialias(o["phi_log"], f, R.dt), Tc)
|
||||
ok = np.all(np.isfinite(Y), 1)
|
||||
Y[~ok] = Y[ok][0]
|
||||
banks.append(Y)
|
||||
logpi.append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum()))
|
||||
diag[i] |= {"Ctl-GP_n_valid": int(ok.sum()), "Ctl-GP_n_rejected": n_rej, "Ctl-GP_fallback_u": bool(fallback),
|
||||
"Ctl-GP_sd_ratio": float(Tc_grid.std(0).mean() / Tg.std(0).mean())}
|
||||
return banks, logpi
|
||||
|
||||
|
||||
def two_mode_banks(R, obs: list[dict], delta_ms: float, diag: list[dict]) -> dict:
|
||||
"""S8 controlled cycle skip: modes t_true and t_true + s·Δ (s = ±1 per training well from rng
|
||||
[rid, SIDE_STREAM, 8, i]); PM2 at the mean warp t_true + sΔ/2; BK2/HM2 the two-member bank."""
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.ties import warp_errors
|
||||
|
||||
f = R.cfg["fine_dt_ms"]
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
banks = {"PM2": [], "BK2": []}
|
||||
for i, o in enumerate(obs):
|
||||
s = int(np.random.default_rng([R.rid, SIDE_STREAM, 8, i]).integers(2)) * 2 - 1
|
||||
y_aa = antialias(o["phi_log"], f, R.dt)
|
||||
t_true = o["t_of_tau_true"]
|
||||
Ypm = lab(y_aa, t_true + s * delta_ms / 2.0)
|
||||
Ybk = lab(y_aa, np.stack([t_true, t_true + s * delta_ms]))
|
||||
if not (np.all(np.isfinite(Ypm)) and np.all(np.isfinite(Ybk))):
|
||||
raise ValueError(f"{o['name']}: two-mode labels leave the label support at Δ = {delta_ms} ms")
|
||||
banks["PM2"].append(Ypm)
|
||||
banks["BK2"].append(Ybk)
|
||||
diag[i] |= {"delta_ms": delta_ms, "side": s,
|
||||
"PM2_warp_rmse_ms": warp_errors((t_true + s * delta_ms / 2.0)[None], R.tau_fine, t_true, R.t_main)["warp_rmse_ms"]}
|
||||
return banks
|
||||
|
||||
|
||||
def train_cell(cell: Cell, p: dict, inp: Inputs, device: str, post: dict[str, Path] | None, save_preds: bool = True,
|
||||
seeds=None, budget_lists: dict[str, list[int]] | None = None) -> tuple[list[dict], list[dict], dict, dict]:
|
||||
"""Returns (rows, diag, preds, meta). rows: one per (seed, method, budget, test well) with the P2r metrics.
|
||||
budget_lists (dev only): {method: [budgets]} evaluated along one trajectory instead of the locked budget."""
|
||||
from ml_porosity.models.bank_train import zscore_patch
|
||||
from ml_porosity.registration.pipeline import register
|
||||
|
||||
run_d2 = load_script("11_run_d2.py")
|
||||
t0 = time.time()
|
||||
P2, reg, tcfg = inp.P2, inp.reg, inp.tcfg
|
||||
reg_seed = int(p["registration"]["reg_seed"])
|
||||
seeds = list(p["grid"]["seeds"] if seeds is None else seeds)
|
||||
R = inp.realization(cell.rid, cell.preset)
|
||||
obs, test = inp.observe(R, cell.c, cell.regime, cell.n_train)
|
||||
X = np.stack([zscore_patch(o["seis"], R.main) for o in obs])
|
||||
Xte = np.stack([zscore_patch(o["seis"], R.main) for o in test])
|
||||
yt = 100 * np.stack([o["y_true"] for o in test])
|
||||
N = len(obs)
|
||||
out = register(R, obs, reg, reg_seed)
|
||||
m0, s0 = out["norm"]
|
||||
key = dict(rid=cell.rid, c=cell.c, n_train=N)
|
||||
diag = [key | {"reg_seed": reg_seed, "phase": out["phase"], "lam": out["lam"], "tau_c": out["tau_c"], "well": o["name"],
|
||||
"preset": cell.preset or "nominal", "backbone": cell.backbone} for o in obs]
|
||||
methods = [base_name(m) for m in cell.methods]
|
||||
specs = {}
|
||||
old = [m for m in methods if m in REGISTER_METHODS]
|
||||
if old:
|
||||
specs |= run_d2.method_specs(out, P2, old)
|
||||
single = lambda Y: {"kind": "bank", "Y": Y, "logpi": np.zeros((N, 1), np.float32), "lam": out["lam"]}
|
||||
nb = lambda v: ((np.stack(v) - m0) / s0).astype(np.float32)
|
||||
meta = {}
|
||||
if any(m in POSTERIOR_METHODS + CONTROL_METHODS for m in methods):
|
||||
if post is None:
|
||||
raise RuntimeError(f"{cell.tag}: posterior methods requested without a posterior directory")
|
||||
ph = json.loads(post["phase"].read_text())
|
||||
if ph["phase0"] != out["phase"]:
|
||||
raise RuntimeError(f"{cell.tag}: register phase ({out['phase']}) differs from the posterior run ({ph['phase0']})")
|
||||
with np.load(post["particles"]) as smc:
|
||||
smc = {k: smc[k] for k in smc.files}
|
||||
banks, logpi = posterior_banks(R, obs, out, reg, ph, smc, reg_seed, diag)
|
||||
specs["B3c-R"] = single(nb(banks["B3c-R"]))
|
||||
specs["B3d-Sa"] = single(nb(banks["B3d-Sa"]))
|
||||
specs["M2-Sa"] = {"kind": "bank", "Y": nb(banks["M2-Sa"]), "logpi": np.stack(logpi).astype(np.float32), "lam": out["lam"]}
|
||||
meta["posterior"] = str(post["particles"])
|
||||
if any(m in CONTROL_METHODS for m in methods):
|
||||
yc, lpc = control_gp_bank(R, obs, smc, reg, reg_seed, diag)
|
||||
specs["Ctl-GP"] = {"kind": "bank", "Y": nb(yc), "logpi": np.stack(lpc).astype(np.float32), "lam": out["lam"]}
|
||||
if any(m in TWO_MODE_METHODS for m in methods):
|
||||
banks = two_mode_banks(R, obs, float(cell.delta_ms), diag)
|
||||
specs["PM2"] = single(nb(banks["PM2"]))
|
||||
Ybk = nb(banks["BK2"])
|
||||
lp = np.full((N, 2), -np.log(2.0), np.float32)
|
||||
specs["BK2"] = {"kind": "bank", "Y": Ybk, "logpi": lp, "lam": out["lam"]}
|
||||
specs["HM2"] = {"kind": "bank", "Y": Ybk, "logpi": lp, "lam": None}
|
||||
missing = [m for m in methods if m not in specs]
|
||||
if missing:
|
||||
raise ValueError(f"no label specification for methods {missing}")
|
||||
rows, preds = [], {}
|
||||
suffix = "" if cell.backbone == "cnngru" else f"-{cell.backbone.upper()}"
|
||||
for seed in seeds:
|
||||
for m in methods:
|
||||
bud = list(budget_lists[m]) if budget_lists else budget_list(p, m, cell.backbone)
|
||||
for b, (mu, sg) in train_predict_any(X, Xte, specs[m], tcfg, seed, bud, device, cell.backbone).items():
|
||||
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
|
||||
name = m + suffix
|
||||
for w, r in zip(R.test, run_d2.evaluate(yt, mu_p, sg_p, inp.f_c)):
|
||||
rows.append(key | {"seed": seed, "method": name, "budget": b, "test_well": w.name,
|
||||
"regime": cell.regime, "preset": cell.preset or "nominal", "study": cell.study,
|
||||
"delta_ms": cell.delta_ms} | r)
|
||||
if save_preds:
|
||||
preds[f"{name}/s{seed}/b{b}/mu"] = mu_p.astype(np.float32)
|
||||
preds[f"{name}/s{seed}/b{b}/sigma"] = sg_p.astype(np.float32)
|
||||
preds = {"y_true": yt.astype(np.float32), "test_wells": np.array([w.name for w in R.test])} | preds
|
||||
meta |= {"wall_seconds": time.time() - t0, "device": device, "seeds": seeds, "methods": [m + suffix for m in methods],
|
||||
"budgets": {m + suffix: (list(budget_lists[m]) if budget_lists else budget_list(p, m, cell.backbone)) for m in methods},
|
||||
"registered_budgets": {m + suffix: budget_of(p, m, cell.backbone) for m in methods},
|
||||
"phase": out["phase"],
|
||||
"lam": out["lam"], "misspec_active": R.misspec_active, "n_train": N, "backbone": cell.backbone}
|
||||
return rows, diag, preds, meta
|
||||
@@ -16,6 +16,24 @@ Registration: logs lie on the τ axis (sonic time). True warp t(τ) = τ + b +
|
||||
g = c·(m_g + L z), b = c·σ_b·z_b, where (m_g, σ_g, ℓ, σ_b) come from the GP fit to the F3 anchors (scripts/09);
|
||||
z is shared across all drift factors c. Anchors: unit boundaries within the extended window, τ_k = t⁻¹(t_b),
|
||||
t_k = t_b + ε_k, with ε_k ~ N(0, σ_a²) shared across all c.
|
||||
|
||||
Misspecification (phase P6, S2; docs/research/bench-generator.md). `D2Realization(..., misspec=...)` lets the
|
||||
data violate the assumptions of the registration (nominal rock physics in obs["ai_log"], a stationary wavelet with
|
||||
a constant phase, the F3 Matérn-3/2 warp prior) in controlled ways, on three axes:
|
||||
|
||||
rock_physics the earth maps φ → AI with perturbed coefficients (uniform factors; optionally a per-unit
|
||||
shift of the φ–DT intercept, i.e. lithology-dependent matrix slowness) while obs["ai_log"]
|
||||
keeps the nominal relation;
|
||||
wavelet the true wavelet is a transformed version of the nominal one (constant phase, fractional
|
||||
minimum-phase dispersion, peak-frequency factor, bulk delay) and/or a constant-Q time-variant
|
||||
filter is applied in the forward model;
|
||||
drift the true warp is drawn with scaled (σ_b, σ_g, ℓ), plus non-GP components: a jump of the
|
||||
warp just below a horizon (a local log-slowness anomaly) and short-correlation jitter.
|
||||
|
||||
Common random numbers: the misspecified realization uses the same z_g, z_b, ε_a, GRF and noise draws as the
|
||||
nominal one; additional draws (per-unit shifts, jitter) come from separate, rid-seeded streams, so the nominal
|
||||
path consumes its random stream exactly as before. `misspec=None` (or all-nominal values) reproduces the
|
||||
protocol_p2/p2r generator bit for bit (tests/test_d2_misspec.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,13 +41,16 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
from ml_porosity.baselines.inversion import strat_map
|
||||
from ml_porosity.data.wavelet import rotate_phase
|
||||
from ml_porosity.registration.labels import antialias, invert_warps
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, forward_fine
|
||||
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, kernel_matrix
|
||||
|
||||
PHI_DT_A, PHI_DT_B = -0.2018, 0.0011
|
||||
PHI_DT_A, PHI_DT_B = -0.2018, 0.0011 # φ = A + B·DT (DT in µs/m)
|
||||
RHO_0, RHO_1 = 2650.0, 1600.0 # RHOB = ρ0 − ρ1·φ (kg/m³)
|
||||
|
||||
|
||||
def phi_to_ai(phi: np.ndarray) -> np.ndarray:
|
||||
@@ -37,6 +58,203 @@ def phi_to_ai(phi: np.ndarray) -> np.ndarray:
|
||||
return (2650.0 - 1600.0 * phi) * 1e6 / dt
|
||||
|
||||
|
||||
def phi_to_ai_coef(phi: np.ndarray, a: np.ndarray | float, b: float, rho0: float, rho1: float) -> np.ndarray:
|
||||
"""AI for the perturbed relations φ = a + b·DT, RHOB = rho0 − rho1·φ (a may vary per sample)."""
|
||||
dt = (phi - a) / b
|
||||
return (rho0 - rho1 * phi) * 1e6 / dt
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ misspecification parameters
|
||||
|
||||
MISSPEC_DEFAULTS = {
|
||||
"rock_physics": {
|
||||
"dt_slope_factor": 1.0, # B → B·f (φ = A + B·DT; nominal B = 0.0011 per µs/m)
|
||||
"dt_intercept_factor": 1.0, # A → A·f (nominal A = −0.2018; DT_matrix = −A/B)
|
||||
"rho_slope_factor": 1.0, # ρ1 → ρ1·f (nominal 1600)
|
||||
"rho_intercept_factor": 1.0, # ρ0 → ρ0·f (nominal 2650)
|
||||
"unit_dt_intercept_sd": 0.0, # A → A·(1 + sd·ζ_u) per stratigraphic unit, ζ_u ~ N(0, 1) per realization
|
||||
"region": "all", # wells affected: all | test | pool
|
||||
},
|
||||
"wavelet": {
|
||||
"phase_deg": 0.0, # constant phase rotation (inside the registration's family)
|
||||
"minphase_frac": 0.0, # s ∈ [0, 1]: phase spectrum s·θ_min(f) of the nominal amplitude spectrum
|
||||
"peak_freq_factor": 1.0, # w(t) → w(p·t): spectrum stretched by p
|
||||
"delay_ms": 0.0, # bulk timing error of the wavelet (events shifted relative to the anchors)
|
||||
"Q": None, # constant-Q time-variant attenuation relative to Q_t_ref_ms (None: off)
|
||||
"Q_t_ref_ms": 400.0,
|
||||
"Q_dispersion": True, # Kolsky–Futterman phase (reference frequency = peak of the true wavelet)
|
||||
},
|
||||
"drift": {
|
||||
"sigma_b_factor": 1.0,
|
||||
"sigma_g_factor": 1.0,
|
||||
"ell_factor": 1.0,
|
||||
"step_ms": 0.0, # jump J of t(τ) just below step_horizon, independent of c
|
||||
"step_width_ms": 12.0, # τ extent of the log-slowness anomaly that realises the jump
|
||||
"step_horizon": "Truncation",
|
||||
"jitter_sd_ms": 0.0, # Matérn-3/2 jitter of t(τ) on the warp grid (own random stream per well)
|
||||
"jitter_ell_ms": 8.0,
|
||||
},
|
||||
}
|
||||
_STRENGTH_KEYS = {
|
||||
"rock_physics": ("dt_slope_factor", "dt_intercept_factor", "rho_slope_factor", "rho_intercept_factor",
|
||||
"unit_dt_intercept_sd"),
|
||||
"wavelet": ("phase_deg", "minphase_frac", "peak_freq_factor", "delay_ms", "Q"),
|
||||
"drift": ("sigma_b_factor", "sigma_g_factor", "ell_factor", "step_ms", "jitter_sd_ms"),
|
||||
}
|
||||
_RP_UNIFORM = ("dt_slope_factor", "dt_intercept_factor", "rho_slope_factor", "rho_intercept_factor")
|
||||
_WV_STATIONARY = ("phase_deg", "minphase_frac", "peak_freq_factor", "delay_ms")
|
||||
|
||||
|
||||
def normalize_misspec(spec: dict | None) -> dict:
|
||||
"""Fill defaults. Unknown axes or keys raise, so a typo in a locked protocol cannot silently mean 'nominal'."""
|
||||
spec = spec or {}
|
||||
if unknown := set(spec) - set(MISSPEC_DEFAULTS):
|
||||
raise ValueError(f"unknown misspec axes {sorted(unknown)}; expected {sorted(MISSPEC_DEFAULTS)}")
|
||||
out = {}
|
||||
for axis, defaults in MISSPEC_DEFAULTS.items():
|
||||
sub = spec.get(axis) or {}
|
||||
if unknown := set(sub) - set(defaults):
|
||||
raise ValueError(f"unknown misspec keys {sorted(unknown)} in '{axis}'; expected {sorted(defaults)}")
|
||||
out[axis] = {k: (sub[k] if k in sub else v) for k, v in defaults.items()}
|
||||
rp = out["rock_physics"]
|
||||
if rp["region"] not in ("all", "test", "pool"):
|
||||
raise ValueError(f"rock_physics.region must be all | test | pool, got {rp['region']!r}")
|
||||
wv = out["wavelet"]
|
||||
if not 0.0 <= wv["minphase_frac"] <= 1.0 or wv["peak_freq_factor"] <= 0 or (wv["Q"] is not None and wv["Q"] <= 0):
|
||||
raise ValueError("wavelet: minphase_frac ∈ [0, 1], peak_freq_factor > 0, Q > 0 or None")
|
||||
dr = out["drift"]
|
||||
if min(dr["sigma_b_factor"], dr["sigma_g_factor"], dr["ell_factor"]) <= 0 or dr["step_width_ms"] <= 0 \
|
||||
or dr["jitter_sd_ms"] < 0 or dr["jitter_ell_ms"] <= 0:
|
||||
raise ValueError("drift: factors, step_width_ms and jitter_ell_ms must be > 0, jitter_sd_ms ≥ 0")
|
||||
return out
|
||||
|
||||
|
||||
def active_axes(ms: dict) -> dict:
|
||||
"""{axis: {key: value}} for the strength keys that differ from nominal (empty dict: nominal generator)."""
|
||||
out = {}
|
||||
for axis, keys in _STRENGTH_KEYS.items():
|
||||
d = {k: ms[axis][k] for k in keys if ms[axis][k] != MISSPEC_DEFAULTS[axis][k]}
|
||||
if d:
|
||||
out[axis] = d
|
||||
return out
|
||||
|
||||
|
||||
def preset_misspec(cfg: dict, name: str | None) -> dict | None:
|
||||
"""Look up cfg["misspec_presets"][name]; None or "nominal" gives the nominal generator."""
|
||||
if name in (None, "nominal"):
|
||||
return None
|
||||
presets = cfg.get("misspec_presets") or {}
|
||||
if name not in presets:
|
||||
raise KeyError(f"misspec preset {name!r} not in config (have {sorted(presets)})")
|
||||
return {k: v for k, v in presets[name].items() if k != "note"}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ wavelet transforms (fine grid)
|
||||
|
||||
|
||||
def _spectrum_buffer(w: np.ndarray, nfft: int) -> np.ndarray:
|
||||
"""Centred odd-length wavelet → length-nfft buffer with time zero at index 0."""
|
||||
return np.roll(np.concatenate([w, np.zeros(nfft - len(w))]), -(len(w) // 2))
|
||||
|
||||
|
||||
def _extract_centred(buf: np.ndarray, n: int) -> np.ndarray:
|
||||
m = n // 2
|
||||
return np.concatenate([buf[-m:], buf[: m + 1]])
|
||||
|
||||
|
||||
def peak_frequency_hz(w: np.ndarray, dt_ms: float, nfft: int = 4096) -> float:
|
||||
f = np.fft.rfftfreq(nfft, dt_ms / 1000.0)
|
||||
return float(f[np.argmax(np.abs(np.fft.rfft(w, nfft)))])
|
||||
|
||||
|
||||
def fractional_minimum_phase(w: np.ndarray, frac: float, floor_db: float = -80.0) -> np.ndarray:
|
||||
"""Same amplitude spectrum, phase spectrum frac·θ_min(f) (cepstral minimum-phase construction), re-centred at
|
||||
the lag of maximum cross-correlation with the input so that the bulk delay is removed and only the
|
||||
frequency-dependent part of the phase remains. frac = 0 returns the input (up to FFT round-off)."""
|
||||
n = len(w)
|
||||
nfft = 1 << int(np.ceil(np.log2(8 * n)))
|
||||
x = _spectrum_buffer(w, nfft)
|
||||
W = np.fft.rfft(x)
|
||||
A = np.maximum(np.abs(W), 10 ** (floor_db / 20) * np.abs(W).max())
|
||||
c = np.fft.irfft(np.log(A), nfft) # real cepstrum
|
||||
fold = np.zeros(nfft)
|
||||
fold[0], fold[nfft // 2] = c[0], c[nfft // 2]
|
||||
fold[1: nfft // 2] = 2.0 * c[1: nfft // 2]
|
||||
theta_min = np.imag(np.fft.rfft(fold)) # log W_min = ln A + i θ_min
|
||||
y = np.fft.irfft(W * np.exp(1j * frac * theta_min), nfft)
|
||||
xc = np.fft.irfft(np.fft.rfft(y) * np.conj(np.fft.rfft(x)), nfft)
|
||||
lag = int(np.argmax(xc))
|
||||
lag = lag - nfft if lag > nfft // 2 else lag
|
||||
return _extract_centred(np.roll(y, -lag), n)
|
||||
|
||||
|
||||
def true_stationary_wavelet(w_fine: np.ndarray, dt_ms: float, wv: dict) -> np.ndarray:
|
||||
"""Stationary part of the true wavelet on the fine grid: peak-frequency scaling, fractional minimum phase,
|
||||
constant phase rotation, bulk delay, then a Tukey taper (outer 1/8 of each side) and unit peak."""
|
||||
n = len(w_fine)
|
||||
tf = (np.arange(n) - n // 2) * dt_ms
|
||||
w = w_fine.astype(float)
|
||||
if wv["peak_freq_factor"] != 1.0:
|
||||
w = np.interp(wv["peak_freq_factor"] * tf, tf, w, left=0.0, right=0.0)
|
||||
if wv["minphase_frac"] != 0.0:
|
||||
w = fractional_minimum_phase(w, wv["minphase_frac"])
|
||||
if wv["phase_deg"] != 0.0:
|
||||
w = rotate_phase(w, wv["phase_deg"])
|
||||
if wv["delay_ms"] != 0.0:
|
||||
k = int(round(wv["delay_ms"] / dt_ms))
|
||||
w = np.roll(w, k)
|
||||
if k > 0:
|
||||
w[:k] = 0.0
|
||||
elif k < 0:
|
||||
w[k:] = 0.0
|
||||
w = w * signal.windows.tukey(n, 0.25)
|
||||
return w / np.max(np.abs(w))
|
||||
|
||||
|
||||
def q_kernel(w_fine: np.ndarray, dt_ms: float, Q: float, delta_t_ms: float, dispersion: bool, f_ref_hz: float,
|
||||
half_len: int = 256) -> np.ndarray:
|
||||
"""Wavelet after constant-Q propagation over delta_t_ms relative to the reference time: amplitude
|
||||
exp(−π f Δt/Q), Kolsky–Futterman phase (2 f Δt/Q)·ln(f/f_ref) (slower below f_ref, faster above). Returns a
|
||||
centred kernel of length 2·half_len + 1 on the fine grid."""
|
||||
n = len(w_fine)
|
||||
nfft = 1 << int(np.ceil(np.log2(4 * max(n, 2 * half_len + 1))))
|
||||
f = np.fft.rfftfreq(nfft, dt_ms / 1000.0)
|
||||
W = np.fft.rfft(_spectrum_buffer(w_fine, nfft))
|
||||
dts = delta_t_ms / 1000.0
|
||||
H = np.exp(-np.pi * f * dts / Q)
|
||||
if dispersion:
|
||||
with np.errstate(divide="ignore"):
|
||||
ph = np.where(f > 0, 2.0 * f * dts / Q * np.log(np.maximum(f, 1e-12) / f_ref_hz), 0.0)
|
||||
H = H * np.exp(1j * ph)
|
||||
return _extract_centred(np.fft.irfft(W * H, nfft), 2 * half_len + 1)
|
||||
|
||||
|
||||
def forward_fine_q(ai: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray, Q: float,
|
||||
t_ref_ms: float, dispersion: bool, f_ref_hz: float, bank_dt_ms: float = 50.0) -> np.ndarray:
|
||||
"""forward_fine with a constant-Q time-variant wavelet: the reflectivity at time t′ is convolved with the
|
||||
kernel q_kernel(t′ − t_ref). Kernels are tabulated every bank_dt_ms and interpolated linearly in t′ (the
|
||||
operator varies as exp(−π f Δt/Q), so the interpolation error is second order in bank_dt/Q)."""
|
||||
ai = np.atleast_2d(ai)
|
||||
r = (ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])
|
||||
tm = 0.5 * (t_fine[1:] + t_fine[:-1])
|
||||
d = t_fine[1] - t_fine[0]
|
||||
half = 256
|
||||
pad = half * d + bank_dt_ms
|
||||
tb = np.arange(t_out[0] - pad, t_out[-1] + pad + bank_dt_ms / 2, bank_dt_ms)
|
||||
idx = np.clip(np.searchsorted(tb, tm) - 1, 0, len(tb) - 2)
|
||||
lam = np.clip((tm - tb[idx]) / bank_dt_ms, 0.0, 1.0)
|
||||
s = np.zeros_like(r)
|
||||
for k, t_k in enumerate(tb):
|
||||
wk = np.where(idx == k, 1.0 - lam, 0.0) + np.where(idx == k - 1, lam, 0.0)
|
||||
if np.any(wk > 0):
|
||||
ker = q_kernel(w_fine, d, Q, t_k - t_ref_ms, dispersion, f_ref_hz, half)
|
||||
s += signal.fftconvolve(r * wk[None, :], ker[None, :], mode="same", axes=1)
|
||||
return np.stack([np.interp(t_out, tm, si) for si in s])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ earth model primitives
|
||||
|
||||
|
||||
def ou_process(n: int, d: float, sd: float, ell: float, rng) -> np.ndarray:
|
||||
rho = np.exp(-d / ell)
|
||||
e = rng.standard_normal(n) * sd * np.sqrt(1 - rho**2)
|
||||
@@ -86,10 +304,20 @@ class D2Well:
|
||||
|
||||
|
||||
class D2Realization:
|
||||
"""A single realization: earth model, pseudo-well locations, noise, and standard normal draws for drift/picks."""
|
||||
"""A single realization: earth model, pseudo-well locations, noise, and standard normal draws for drift/picks.
|
||||
|
||||
def __init__(self, cfg: dict, rid: int, hg: HorizonGrid, drift: WarpHyper, wavelet: np.ndarray):
|
||||
misspec: None (nominal) or {"rock_physics": {...}, "wavelet": {...}, "drift": {...}} with the keys of
|
||||
MISSPEC_DEFAULTS. The normalised parameters are stored in `misspec`, the non-nominal ones in `misspec_active`.
|
||||
`wavelet`/`w_fine` are the stationary true wavelet (the nominal objects when the wavelet axis is nominal);
|
||||
`wavelet_nominal`/`w_fine_nominal` the analyst's reference; `drift_true` the hyperparameters the truth is
|
||||
drawn from (`drift` when nominal)."""
|
||||
|
||||
def __init__(self, cfg: dict, rid: int, hg: HorizonGrid, drift: WarpHyper, wavelet: np.ndarray,
|
||||
misspec: dict | None = None):
|
||||
self.cfg, self.rid, self.drift = cfg, rid, drift
|
||||
self.misspec = normalize_misspec(misspec)
|
||||
self.misspec_active = active_axes(self.misspec)
|
||||
self.misspec_info = {"monotone_repairs": 0}
|
||||
rng = np.random.default_rng([int(rid), 20261026])
|
||||
f = cfg["fine_dt_ms"]
|
||||
self.dt = cfg["dt_ms"]
|
||||
@@ -101,8 +329,10 @@ class D2Realization:
|
||||
self.t_ext = np.arange(e0, e1 + self.dt / 2, self.dt)
|
||||
self.main = (self.t_ext >= m0) & (self.t_ext <= m1)
|
||||
self.t_main = self.t_ext[self.main]
|
||||
self.wavelet = wavelet
|
||||
self.w_fine = fine_wavelet(wavelet, int(round(self.dt / f)))
|
||||
self.wavelet_nominal = wavelet
|
||||
self.w_fine_nominal = fine_wavelet(wavelet, int(round(self.dt / f)))
|
||||
self.wavelet, self.w_fine = self._true_wavelet()
|
||||
self.f_ref_hz = peak_frequency_hz(self.w_fine, f)
|
||||
|
||||
# Stratigraphic framework
|
||||
valid = hg.valid_mask(cfg["min_gap_ms"], cfg["patch_radius"])
|
||||
@@ -142,6 +372,18 @@ class D2Realization:
|
||||
self.xy_c, self.xy_s = xy_all.mean(0), np.ptp(xy_all, 0) / 2
|
||||
Kg = kernel_matrix(self.grid.tau, self.grid.tau, 1.0, drift.ell_ms, drift.kernel)
|
||||
self.Lg = np.linalg.cholesky(Kg + 1e-8 * np.eye(self.grid.n))
|
||||
self.drift_true, self.Lg_true = self._true_drift()
|
||||
|
||||
# Misspecification draws from separate streams (the nominal stream `rng` is consumed exactly as before)
|
||||
rp = self.misspec["rock_physics"]
|
||||
self.unit_dt_shift = None
|
||||
if rp["unit_dt_intercept_sd"] > 0:
|
||||
self.unit_dt_shift = rp["unit_dt_intercept_sd"] * np.random.default_rng([int(rid), 20261029, 1]).standard_normal(nu)
|
||||
dr = self.misspec["drift"]
|
||||
self.Lj = None
|
||||
if dr["jitter_sd_ms"] > 0:
|
||||
Kj = kernel_matrix(self.grid.tau, self.grid.tau, 1.0, dr["jitter_ell_ms"], "matern32")
|
||||
self.Lj = np.linalg.cholesky(Kj + 1e-8 * np.eye(self.grid.n))
|
||||
|
||||
self.wells: list[D2Well] = []
|
||||
for tag, idx in [("T", test), ("P", train)]:
|
||||
@@ -149,6 +391,83 @@ class D2Realization:
|
||||
self.wells.append(self._make_well(f"{tag}{n:02d}", int(il_all[k]), int(xl_all[k]), rng))
|
||||
self.test = self.wells[: W["n_test"]]
|
||||
self.pool = self.wells[W["n_test"]:]
|
||||
if self.Lj is not None:
|
||||
for k, w in enumerate(self.wells):
|
||||
w.extra["z_jitter"] = np.random.default_rng([int(rid), 20261029, 2, k]).standard_normal(self.grid.n)
|
||||
|
||||
# ------------------------------------------------------------ misspecified truth
|
||||
|
||||
def _true_wavelet(self) -> tuple[np.ndarray, np.ndarray]:
|
||||
wv = self.misspec["wavelet"]
|
||||
if all(wv[k] == MISSPEC_DEFAULTS["wavelet"][k] for k in _WV_STATIONARY):
|
||||
return self.wavelet_nominal, self.w_fine_nominal
|
||||
fac = int(round(self.dt / self.cfg["fine_dt_ms"]))
|
||||
w_fine = true_stationary_wavelet(self.w_fine_nominal, self.cfg["fine_dt_ms"], wv)
|
||||
return w_fine[::fac].copy(), w_fine
|
||||
|
||||
def _true_drift(self) -> tuple[WarpHyper, np.ndarray]:
|
||||
dr, d = self.misspec["drift"], self.drift
|
||||
if dr["sigma_b_factor"] == 1.0 and dr["sigma_g_factor"] == 1.0 and dr["ell_factor"] == 1.0:
|
||||
return d, self.Lg
|
||||
h = WarpHyper(d.m_g, d.sigma_g * dr["sigma_g_factor"], d.ell_ms * dr["ell_factor"],
|
||||
d.sigma_b_ms * dr["sigma_b_factor"], d.sigma_a_ms, d.kernel)
|
||||
Lg = self.Lg
|
||||
if dr["ell_factor"] != 1.0:
|
||||
Kg = kernel_matrix(self.grid.tau, self.grid.tau, 1.0, h.ell_ms, h.kernel)
|
||||
Lg = np.linalg.cholesky(Kg + 1e-8 * np.eye(self.grid.n))
|
||||
return h, Lg
|
||||
|
||||
def rp_applies(self, name: str) -> bool:
|
||||
"""Whether the rock-physics misspecification acts on the well `name` (region all | test | pool)."""
|
||||
rp = self.misspec["rock_physics"]
|
||||
if "rock_physics" not in self.misspec_active:
|
||||
return False
|
||||
return rp["region"] == "all" or (rp["region"] == "test") == name.startswith("T")
|
||||
|
||||
def phi_to_ai_true(self, phi: np.ndarray, unit: np.ndarray | None = None) -> np.ndarray:
|
||||
"""The earth's φ → AI mapping under the rock-physics misspecification (nominal relations when the axis is
|
||||
nominal). `unit`: stratigraphic unit index per sample, required when unit_dt_intercept_sd > 0."""
|
||||
if "rock_physics" not in self.misspec_active:
|
||||
return phi_to_ai(phi)
|
||||
rp = self.misspec["rock_physics"]
|
||||
a = PHI_DT_A * rp["dt_intercept_factor"]
|
||||
if self.unit_dt_shift is not None:
|
||||
if unit is None:
|
||||
raise ValueError("unit index required for the per-unit intercept shift")
|
||||
a = a * (1.0 + self.unit_dt_shift[np.asarray(unit)])
|
||||
return phi_to_ai_coef(phi, a, PHI_DT_B * rp["dt_slope_factor"], RHO_0 * rp["rho_intercept_factor"],
|
||||
RHO_1 * rp["rho_slope_factor"])
|
||||
|
||||
def ai_log_true(self, w: D2Well, obs: dict) -> np.ndarray:
|
||||
"""True AI on the τ axis of the log (what a forward model with the true rock physics would use); equals
|
||||
obs["ai_log"] when the rock physics is nominal for this well."""
|
||||
if not self.rp_applies(w.name):
|
||||
return phi_to_ai(obs["phi_log"])
|
||||
unit = None
|
||||
if self.unit_dt_shift is not None:
|
||||
unit = np.searchsorted(self.S_ref, strat_map(obs["t_of_tau_true"], self.hg.at(w.il, w.xl), self.h_ref))
|
||||
return self.phi_to_ai_true(obs["phi_log"], unit)
|
||||
|
||||
def true_wavelet_at(self, t_ms: float) -> np.ndarray:
|
||||
"""Effective fine wavelet for a reflector at true time t_ms (the stationary wavelet unless Q is set)."""
|
||||
wv = self.misspec["wavelet"]
|
||||
if wv["Q"] is None:
|
||||
return self.w_fine
|
||||
return q_kernel(self.w_fine, self.cfg["fine_dt_ms"], wv["Q"], t_ms - wv["Q_t_ref_ms"], wv["Q_dispersion"],
|
||||
self.f_ref_hz)
|
||||
|
||||
def _ai_true(self, phi: np.ndarray, h_bin: np.ndarray, name: str) -> np.ndarray:
|
||||
if not self.rp_applies(name):
|
||||
return phi_to_ai(phi)
|
||||
unit = self._unit_index(h_bin)[1] if self.unit_dt_shift is not None else None
|
||||
return self.phi_to_ai_true(phi, unit)
|
||||
|
||||
def _forward(self, ai: np.ndarray) -> np.ndarray:
|
||||
wv = self.misspec["wavelet"]
|
||||
if wv["Q"] is None:
|
||||
return forward_fine(ai, self.t_fine, self.t_ext, self.w_fine)
|
||||
return forward_fine_q(ai, self.t_fine, self.t_ext, self.w_fine, wv["Q"], wv["Q_t_ref_ms"], wv["Q_dispersion"],
|
||||
self.f_ref_hz)
|
||||
|
||||
# ------------------------------------------------------------ earth model
|
||||
|
||||
@@ -161,9 +480,13 @@ class D2Realization:
|
||||
s += [h_ref[-1] + k * sub_ms for k in range(0, int((t1 - h_ref[-1]) // sub_ms) + 1)]
|
||||
return np.array(s)
|
||||
|
||||
def _phi_trace(self, h_bin, xy, grf_s, s_axis):
|
||||
def _unit_index(self, h_bin) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Stratigraphic coordinate and unit index of t_fine at a bin with horizon times h_bin."""
|
||||
s = strat_map(self.t_fine, h_bin, self.h_ref)
|
||||
unit = np.searchsorted(self.S_ref, s)
|
||||
return s, np.searchsorted(self.S_ref, s)
|
||||
|
||||
def _phi_trace(self, h_bin, xy, grf_s, s_axis):
|
||||
s, unit = self._unit_index(h_bin)
|
||||
u = (np.asarray(xy) - self.xy_c) / self.xy_s
|
||||
off = self.unit_off[unit] + self.unit_grad[unit] @ u
|
||||
phi = self.phi0 + self.cfg["property"]["slope_per_100ms"] * (self.t_fine - 850.0) / 100.0 + off
|
||||
@@ -183,10 +506,11 @@ class D2Realization:
|
||||
phi = self._phi_trace(h, xy, grf, s_axis)
|
||||
if di == 0 and dj == 0:
|
||||
phi_c = phi
|
||||
traces.append(phi_to_ai(phi))
|
||||
seis = forward_fine(np.stack(traces), self.t_fine, self.t_ext, self.w_fine)
|
||||
white = rng.standard_normal((len(traces), len(self.t_ext) + len(self.wavelet)))
|
||||
noise = np.stack([np.convolve(wn, self.wavelet, "same")[len(self.wavelet) // 2: len(self.wavelet) // 2 + len(self.t_ext)]
|
||||
traces.append(self._ai_true(phi, h, name))
|
||||
seis = self._forward(np.stack(traces))
|
||||
wn_len = len(self.wavelet_nominal)
|
||||
white = rng.standard_normal((len(traces), len(self.t_ext) + wn_len))
|
||||
noise = np.stack([np.convolve(wn, self.wavelet_nominal, "same")[wn_len // 2: wn_len // 2 + len(self.t_ext)]
|
||||
for wn in white])
|
||||
noise /= noise[len(traces) // 2].std()
|
||||
h0 = self.hg.at(il, xl)
|
||||
@@ -199,15 +523,56 @@ class D2Realization:
|
||||
# ------------------------------------------------------------ observations per cell configuration
|
||||
|
||||
def true_warp(self, w: D2Well, c: float) -> tuple[float, np.ndarray]:
|
||||
d = self.drift
|
||||
g = c * (d.m_g + d.sigma_g * (self.Lg @ w.z_g))
|
||||
return c * d.sigma_b_ms * w.z_b, g
|
||||
"""(b, g) of the true warp on the warp grid: the GP part scaled by c, plus the step anomaly (drift
|
||||
misspecification) folded into g. The jitter component is not representable by g; see true_warp_grid."""
|
||||
d = self.drift_true
|
||||
g = c * (d.m_g + d.sigma_g * (self.Lg_true @ w.z_g))
|
||||
b = c * d.sigma_b_ms * w.z_b
|
||||
if self.misspec["drift"]["step_ms"] != 0.0:
|
||||
g = self._add_step(w, b, g)
|
||||
return b, g
|
||||
|
||||
def _add_step(self, w: D2Well, b: float, g: np.ndarray) -> np.ndarray:
|
||||
"""Jump J of t(τ) just below the step horizon: g += a on the first n_w grid nodes after τ_h = t⁻¹(t_h),
|
||||
with a = ln(1 + J / (Δτ Σ e^{g_i})) so that the trapezoid integral gives exactly J below the anomaly."""
|
||||
dr = self.misspec["drift"]
|
||||
t_h = float(self.hg.at(w.il, w.xl)[self.cfg["horizons"].index(dr["step_horizon"])])
|
||||
t_grid = self.grid.t_of_tau(b, g)[0]
|
||||
tau_h = np.interp(t_h, t_grid, self.grid.tau)
|
||||
n_w = max(1, int(round(dr["step_width_ms"] / self.grid.dtau)))
|
||||
i0 = int(np.searchsorted(self.grid.tau, tau_h, side="right"))
|
||||
nodes = np.arange(max(i0, 1), min(i0 + n_w, self.grid.n - 1))
|
||||
if len(nodes) == 0:
|
||||
raise ValueError(f"{w.name}: step horizon {dr['step_horizon']} at t = {t_h} ms lies outside the warp grid")
|
||||
s = self.grid.dtau * np.exp(g[nodes]).sum()
|
||||
if dr["step_ms"] <= -s:
|
||||
raise ValueError(f"{w.name}: step_ms = {dr['step_ms']} would make the warp non-monotone (min {-s:.2f} ms)")
|
||||
g = g.copy()
|
||||
g[nodes] += np.log1p(dr["step_ms"] / s)
|
||||
return g
|
||||
|
||||
def true_warp_grid(self, w: D2Well, c: float) -> np.ndarray:
|
||||
"""t(τ) on the warp grid including every misspecified component (identical to grid.t_of_tau(b, g) unless
|
||||
jitter is set)."""
|
||||
b, g = self.true_warp(w, c)
|
||||
return self._warp_grid(w, b, g)
|
||||
|
||||
def _warp_grid(self, w: D2Well, b: float, g: np.ndarray) -> np.ndarray:
|
||||
t = self.grid.t_of_tau(b, g)[0]
|
||||
if self.Lj is not None:
|
||||
t = t + self.misspec["drift"]["jitter_sd_ms"] * (self.Lj @ w.extra["z_jitter"])
|
||||
dmin = 0.1 * self.grid.dtau
|
||||
dt = np.diff(t)
|
||||
if np.any(dt < dmin): # safeguard: keep t(τ) strictly increasing (counted)
|
||||
self.misspec_info["monotone_repairs"] += int(np.sum(dt < dmin))
|
||||
t = t[0] + np.concatenate([[0.0], np.cumsum(np.maximum(dt, dmin))])
|
||||
return t
|
||||
|
||||
def observe(self, w: D2Well, c: float, snr_db: float | None, sigma_a_ms: float,
|
||||
anchor_density: str = "full") -> dict:
|
||||
"""Data for one well at drift factor c: noisy seismic, logs on τ, anchors and the true warp."""
|
||||
b, g = self.true_warp(w, c)
|
||||
t_tau_grid = self.grid.t_of_tau(b, g)[0]
|
||||
t_tau_grid = self._warp_grid(w, b, g)
|
||||
t_tau = np.interp(self.tau_fine, self.grid.tau, t_tau_grid)
|
||||
if t_tau[0] < self.t_fine[0] or t_tau[-1] > self.t_fine[-1]:
|
||||
raise ValueError(f"{w.name}: warp extends outside the earth-model domain (c = {c})")
|
||||
|
||||
@@ -52,6 +52,12 @@ def bank_loss(mu, sigma, Y, logpi, starts, win: int, lam: float | None):
|
||||
return -(v / (lam * win)).mean()
|
||||
|
||||
|
||||
def responsibilities(mu, sigma, Y, logpi, starts, win: int, lam: float):
|
||||
"""r (B, J, S) = softmax_s(log π_s + λ ℓ_wjs): the weights of Lemma 3 (∇ RML = −(1/n) Σ_s r_s ∇ℓ_s)."""
|
||||
ll = window_loglik(mu, sigma, Y, starts, win)
|
||||
return torch.softmax(logpi[:, None, :] + lam * ll, dim=-1)
|
||||
|
||||
|
||||
def mse_bank_loss(mu, Y, starts, win: int):
|
||||
"""Mean MSE over the labels of the bank (H1: the optimum is the label blurred by p_δ)."""
|
||||
m = gather_windows(mu, starts, win)[:, :, None, :]
|
||||
|
||||
@@ -37,9 +37,10 @@ def zscore_patch(seis: np.ndarray, sel: np.ndarray) -> np.ndarray:
|
||||
|
||||
|
||||
def train_predict(X: np.ndarray, Xte: np.ndarray, spec: dict, cfg: dict, seed: int, budgets: list[int],
|
||||
device: str) -> dict[int, tuple[np.ndarray, np.ndarray]]:
|
||||
device: str, on_budget=None) -> dict[int, tuple[np.ndarray, np.ndarray]]:
|
||||
"""X (N, C, L), Xte (M, C, L); labels in spec are already standardised. Returns {budget: (μ, σ)} for
|
||||
Xte (M, L), on the standardised scale."""
|
||||
Xte (M, L), on the standardised scale. on_budget (optional): callback on_budget(step, model) invoked right
|
||||
after the predictions at each budget step (model in eval mode); the default None leaves the loop unchanged."""
|
||||
# Same RNG stream as torch.manual_seed, but only touches the selected device: manual_seed_all opens a CUDA
|
||||
# context on every visible GPU (shared machine).
|
||||
torch.default_generator.manual_seed(seed)
|
||||
@@ -80,4 +81,6 @@ def train_predict(X: np.ndarray, Xte: np.ndarray, spec: dict, cfg: dict, seed: i
|
||||
opt.step()
|
||||
if step in budgets:
|
||||
out[step] = predict(model, Xte, device)
|
||||
if on_budget is not None:
|
||||
on_budget(step, model)
|
||||
return out
|
||||
|
||||
27
operations/p6_s1_watcher.sh
Executable file
27
operations/p6_s1_watcher.sh
Executable file
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
# P6 S1 launcher: waits for GPU headroom on the shared H200s, then starts the S1 drivers in tmux.
|
||||
# Two disjoint regime groups (the runner does not claim jobs, so drivers must not overlap):
|
||||
# A = R10 Rm5 R0 (protocol priority), B = R0h R10tb (cut first if late).
|
||||
# A slot starts on a card only when free memory stays >= 2500 MiB + 2 workers x 1600 MiB on two
|
||||
# readings one minute apart; workers = min(4, (free - 2500) / 1600). Never touches other jobs.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
groups=("R10 Rm5 R0" "R0h R10tb"); names=(p6_s1a p6_s1b); next=0
|
||||
log() { echo "$(date -u +%FT%TZ) $*"; }
|
||||
free_mib() { nvidia-smi --query-gpu=memory.free --format=csv,noheader,nounits -i "$1" | tr -d ' '; }
|
||||
log "watcher start"
|
||||
while (( next < ${#groups[@]} )); do
|
||||
for g in 0 1; do
|
||||
(( next < ${#groups[@]} )) || break
|
||||
f1=$(free_mib $g); (( f1 >= 5700 )) || continue
|
||||
sleep 60; f2=$(free_mib $g); f=$(( f1 < f2 ? f1 : f2 )); (( f >= 5700 )) || continue
|
||||
w=$(( (f - 2500) / 1600 )); (( w > 4 )) && w=4
|
||||
n=${names[$next]}; r=${groups[$next]}
|
||||
tmux new-session -d -s "$n" -c "$PWD" \
|
||||
"env STUDIES=S1 REGIMES='$r' DEVICE=cuda:$g WORKERS=$w MEM_GB=2 scripts/run_bench.sh posterior train >> logs/bench_${n}_cuda$g.out 2>&1"
|
||||
log "launched $n regimes=[$r] cuda:$g workers=$w (free ${f1}/${f2} MiB)"
|
||||
next=$(( next + 1 )); sleep 300 # let the new workers allocate before the next reading
|
||||
done
|
||||
sleep 300
|
||||
done
|
||||
log "all S1 groups launched; watcher exits"
|
||||
176
operations/p6_supervisor.py
Normal file
176
operations/p6_supervisor.py
Normal file
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
"""P6 run supervisor (outside the protocol_bench lock; launches only scripts/run_bench.sh).
|
||||
|
||||
Every CYCLE seconds it logs a GPU snapshot and, for each driver spec:
|
||||
* a dead, unfinished driver is relaunched in the user's tmux server on the card with the most free
|
||||
memory, workers = min(target, (free - RESERVE) / PER_WORKER); it waits if neither card has room;
|
||||
* when a driver finishes, its workers go to the unfinished driver with the most remaining jobs
|
||||
(restart with more workers, at most CAP_DRIVER; in-flight jobs of that driver are lost and redone).
|
||||
Drivers resume by fingerprint, so restarts never change results. Other users' processes are never touched.
|
||||
"""
|
||||
import json, os, re, signal, subprocess, time
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
STATE = REPO / "logs" / "p6_supervisor_state.json"
|
||||
CYCLE, RESERVE, PER_WORKER = 300, 2500, 1700 # s, MiB kept free for others, MiB per SMC worker (measured 1556)
|
||||
W_TOTAL, CAP_DRIVER, CAP_CARD, MAX_RESTARTS, MIN_BOOST_JOBS = 36, 16, 24, 5, 10
|
||||
|
||||
SPECS = { # adopted drivers launched at 16:07 UTC 29/10
|
||||
"p6_s2": dict(studies="S2", regimes="", stages="posterior train", device="cuda:1", workers=6, log="logs/bench_s2_cuda1.out"),
|
||||
"p6_s1a": dict(studies="S1", regimes="R10 Rm5 R0", stages="posterior train", device="cuda:0", workers=5, log="logs/bench_s1a_cuda0.out"),
|
||||
"p6_s1b": dict(studies="S1", regimes="R0h R10tb", stages="posterior train", device="cuda:1", workers=2, log="logs/bench_s1b_cuda1.out"),
|
||||
"p6_s348": dict(studies="S3 S4 S8", regimes="", stages="train", device="cuda:0", workers=4, log="logs/bench_s348_cuda0.out"),
|
||||
# 30/10 01:05 UTC: p6_s1b split into two disjoint regime drivers to use the freed CPUs/GPUs
|
||||
"p6_s1b_r0h": dict(studies="S1", regimes="R0h", stages="posterior train", device="cuda:0", workers=14, log="logs/bench_s1b_r0h_cuda0.out"),
|
||||
"p6_s1b_r10tb": dict(studies="S1", regimes="R10tb", stages="posterior train", device="cuda:1", workers=14, log="logs/bench_s1b_r10tb_cuda1.out"),
|
||||
}
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), msg, flush=True)
|
||||
|
||||
|
||||
def sh(cmd):
|
||||
return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def gpus():
|
||||
out = sh("nvidia-smi --query-gpu=index,memory.free,memory.used,utilization.gpu --format=csv,noheader,nounits")
|
||||
return {f"cuda:{r[0]}": dict(free=int(r[1]), used=int(r[2]), util=int(r[3]))
|
||||
for r in (list(map(str.strip, l.split(","))) for l in out.splitlines())}
|
||||
|
||||
|
||||
def alive(name):
|
||||
return subprocess.run(["tmux", "has-session", "-t", name], capture_output=True).returncode == 0
|
||||
|
||||
|
||||
def tail_info(path):
|
||||
"""(last runlog line, last progress (stage, k, n)) of a driver log."""
|
||||
try:
|
||||
lines = (REPO / path).read_text(errors="replace").splitlines()[-4000:]
|
||||
except FileNotFoundError:
|
||||
return None, None
|
||||
rl = next((l for l in reversed(lines) if l.startswith("[runlog]")), None)
|
||||
pr = None
|
||||
for l in reversed(lines):
|
||||
m = re.match(r"\[(posterior|train):[^ ]+ (\d+)/(\d+)\]", l)
|
||||
if m:
|
||||
pr = (m.group(1), int(m.group(2)), int(m.group(3)))
|
||||
break
|
||||
return rl, pr
|
||||
|
||||
|
||||
def finished(name, s):
|
||||
if (REPO / "logs" / f"p6_done_{name}").exists():
|
||||
return True
|
||||
rl, _ = tail_info(s["log"])
|
||||
return bool(rl and " ok exit 0 " in rl and "_bench_train_" in rl)
|
||||
|
||||
|
||||
def remaining(s):
|
||||
_, pr = tail_info(s["log"])
|
||||
if pr is None:
|
||||
return 10 ** 6
|
||||
stage, k, n = pr
|
||||
return (n - k) + (n if stage == "posterior" and "train" in s["stages"] else 0)
|
||||
|
||||
|
||||
def descendants(pid):
|
||||
kids = sh(f"pgrep -P {pid}").split()
|
||||
return [int(k) for k in kids] + [d for k in kids for d in descendants(int(k))]
|
||||
|
||||
|
||||
def stop(name):
|
||||
pane = sh(f"tmux list-panes -t {name} -F '#{{pane_pid}}'")
|
||||
pids = descendants(int(pane)) if pane.isdigit() else []
|
||||
for p in pids:
|
||||
try:
|
||||
os.kill(p, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
time.sleep(20)
|
||||
for p in pids:
|
||||
try:
|
||||
os.kill(p, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
subprocess.run(["tmux", "kill-session", "-t", name], capture_output=True)
|
||||
|
||||
|
||||
def card_load(state, exclude=None):
|
||||
load = {"cuda:0": 0, "cuda:1": 0}
|
||||
for n, s in state.items():
|
||||
if n != exclude and s.get("status") == "running":
|
||||
load[s["device"]] += s["workers"]
|
||||
return load
|
||||
|
||||
|
||||
def launch(name, s, state, target):
|
||||
g, load = gpus(), card_load(state, exclude=name)
|
||||
best = None
|
||||
for dev in sorted(g, key=lambda d: (load[d], -g[d]["free"])):
|
||||
w = min(target, (g[dev]["free"] - RESERVE) // PER_WORKER, CAP_CARD - load[dev])
|
||||
if w >= 1:
|
||||
best = (dev, int(w))
|
||||
break
|
||||
if best is None:
|
||||
log(f"{name}: no room (free {[g[d]['free'] for d in sorted(g)]} MiB); waiting")
|
||||
s["status"] = "waiting"
|
||||
return
|
||||
dev, w = best
|
||||
s["log"] = f"logs/bench_{name.replace('p6_', '')}_{dev.replace(':', '')}.out"
|
||||
env = f"STUDIES='{s['studies']}' DEVICE={dev} WORKERS={w} MEM_GB=2" + (f" REGIMES='{s['regimes']}'" if s["regimes"] else "")
|
||||
cmd = f"env {env} scripts/run_bench.sh {s['stages']} >> {s['log']} 2>&1 && touch logs/p6_done_{name}"
|
||||
subprocess.run(["tmux", "new-session", "-d", "-s", name, "-c", str(REPO), cmd], check=True)
|
||||
s.update(device=dev, workers=w, status="running")
|
||||
log(f"{name}: launched on {dev} with {w} workers ({s['studies']} {s['regimes']}; log {s['log']})")
|
||||
|
||||
|
||||
def main():
|
||||
state = json.loads(STATE.read_text()) if STATE.exists() else {n: dict(s, status="running", restarts=0) for n, s in SPECS.items()}
|
||||
log(f"supervisor start; specs {list(state)}")
|
||||
while True:
|
||||
g = gpus()
|
||||
log("gpu " + " ".join(f"{d}: free {v['free']} used {v['used']} util {v['util']}%" for d, v in sorted(g.items()))
|
||||
+ " | " + " ".join(f"{n}={s['status']}/{s['device']}x{s['workers']}/rem {remaining(s) if s['status'] != 'done' else 0}"
|
||||
for n, s in state.items()))
|
||||
newly_done = False
|
||||
for n, s in state.items():
|
||||
if s["status"] in ("done", "failed", "replaced"):
|
||||
continue
|
||||
if alive(n):
|
||||
continue
|
||||
if finished(n, s):
|
||||
s["status"] = "done"
|
||||
newly_done = True
|
||||
log(f"{n}: finished")
|
||||
elif s["restarts"] >= MAX_RESTARTS:
|
||||
s["status"] = "failed"
|
||||
log(f"{n}: dead after {MAX_RESTARTS} restarts; giving up (see {s['log']})")
|
||||
else:
|
||||
if s["status"] == "running":
|
||||
s["restarts"] += 1
|
||||
log(f"{n}: driver dead and unfinished (last runlog: {tail_info(s['log'])[0]}); restart {s['restarts']}")
|
||||
launch(n, s, state, s["workers"] if s["status"] != "waiting" else SPECS[n]["workers"])
|
||||
if newly_done:
|
||||
running = {n: s for n, s in state.items() if s["status"] == "running" and alive(n)}
|
||||
free = W_TOTAL - sum(s["workers"] for s in running.values())
|
||||
cand = sorted(running, key=lambda n: -remaining(running[n]))
|
||||
if free >= 2 and cand and remaining(running[cand[0]]) >= MIN_BOOST_JOBS:
|
||||
n = cand[0]
|
||||
s = running[n]
|
||||
target = min(CAP_DRIVER, s["workers"] + free)
|
||||
log(f"{n}: boosting {s['workers']} -> {target} workers ({remaining(s)} jobs remaining)")
|
||||
stop(n)
|
||||
s["status"] = "restarting"
|
||||
launch(n, s, state, target)
|
||||
STATE.write_text(json.dumps(state, indent=1))
|
||||
if all(s["status"] in ("done", "failed", "replaced") for s in state.values()):
|
||||
log("all drivers finished or failed; supervisor exits")
|
||||
return
|
||||
time.sleep(CYCLE)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
BIN
outputs/d2/horizon_grid.npz
Normal file
BIN
outputs/d2/horizon_grid.npz
Normal file
Binary file not shown.
25
outputs/p2/diag/train/budgets.json
Normal file
25
outputs/p2/diag/train/budgets.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"Oracle": 500,
|
||||
"B3a": 250,
|
||||
"B3b": 125,
|
||||
"B3c": 250,
|
||||
"B3d": 250,
|
||||
"B4a": 125,
|
||||
"B4b": 125,
|
||||
"B4c": 500,
|
||||
"B4d": 250,
|
||||
"M2": 125,
|
||||
"B3c-R": 500,
|
||||
"B3d-S1": 250,
|
||||
"B3d-Sa": 250,
|
||||
"B3d-Se": 500,
|
||||
"M2-S1": 250,
|
||||
"M2-Sa": 250,
|
||||
"M2-Sa@1": 500,
|
||||
"M2-Sa@3": 250,
|
||||
"M2-Sa@inf": 250,
|
||||
"M2-Se": 125,
|
||||
"M2@1": 250,
|
||||
"M2@3": 250,
|
||||
"M2@inf": 250
|
||||
}
|
||||
241
outputs/p2/warp_prior_f3.json
Normal file
241
outputs/p2/warp_prior_f3.json
Normal file
@@ -0,0 +1,241 @@
|
||||
{
|
||||
"tau": "sonic_tdr qua marker TD đầu tiên",
|
||||
"anchors_window_ms": [
|
||||
400,
|
||||
1300
|
||||
],
|
||||
"tau_range_ms": [
|
||||
300.0,
|
||||
1400.0
|
||||
],
|
||||
"n_anchors": {
|
||||
"F02-1": 17,
|
||||
"F03-2": 14,
|
||||
"F03-4": 15,
|
||||
"F06-1": 16
|
||||
},
|
||||
"fits": {
|
||||
"matern32": {
|
||||
"hyper": {
|
||||
"m_g": 0.013743609947437552,
|
||||
"sigma_g": 0.10431761812409858,
|
||||
"ell_ms": 71.33574944718966,
|
||||
"sigma_b_ms": 19.375353469343402,
|
||||
"sigma_a_ms": 0.39249228578914613,
|
||||
"kernel": "matern32"
|
||||
},
|
||||
"log_marginal": -157.546,
|
||||
"at_bound": [],
|
||||
"loao": {
|
||||
"n": 62,
|
||||
"mean_z2": 0.874,
|
||||
"coverage_90": 0.871,
|
||||
"max_abs_z": 2.79,
|
||||
"per_well": {
|
||||
"F02-1": {
|
||||
"n": 17,
|
||||
"mean_z2": 1.795,
|
||||
"coverage_90": 0.647,
|
||||
"max_abs_z": 2.79
|
||||
},
|
||||
"F03-2": {
|
||||
"n": 14,
|
||||
"mean_z2": 0.179,
|
||||
"coverage_90": 1.0,
|
||||
"max_abs_z": 1.04
|
||||
},
|
||||
"F03-4": {
|
||||
"n": 15,
|
||||
"mean_z2": 0.294,
|
||||
"coverage_90": 1.0,
|
||||
"max_abs_z": 1.14
|
||||
},
|
||||
"F06-1": {
|
||||
"n": 16,
|
||||
"mean_z2": 1.044,
|
||||
"coverage_90": 0.875,
|
||||
"max_abs_z": 1.93
|
||||
}
|
||||
}
|
||||
},
|
||||
"lowo_folds": {
|
||||
"F02-1": {
|
||||
"hyper": {
|
||||
"m_g": 0.013501991864893523,
|
||||
"sigma_g": 0.09791304315668325,
|
||||
"ell_ms": 89.39094361692972,
|
||||
"sigma_b_ms": 20.360251216962727,
|
||||
"sigma_a_ms": 0.3682292192438849,
|
||||
"kernel": "matern32"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 17,
|
||||
"mean_z2": 2.9,
|
||||
"coverage_90": 0.588,
|
||||
"max_abs_z": 3.73
|
||||
}
|
||||
},
|
||||
"F03-2": {
|
||||
"hyper": {
|
||||
"m_g": 0.021352709263214635,
|
||||
"sigma_g": 0.1188632275851512,
|
||||
"ell_ms": 72.97822717992871,
|
||||
"sigma_b_ms": 21.69060742978543,
|
||||
"sigma_a_ms": 0.4101822020567233,
|
||||
"kernel": "matern32"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 14,
|
||||
"mean_z2": 0.152,
|
||||
"coverage_90": 1.0,
|
||||
"max_abs_z": 0.94
|
||||
}
|
||||
},
|
||||
"F03-4": {
|
||||
"hyper": {
|
||||
"m_g": 0.007537529281641634,
|
||||
"sigma_g": 0.11939896411001334,
|
||||
"ell_ms": 69.81786806890881,
|
||||
"sigma_b_ms": 0.5,
|
||||
"sigma_a_ms": 0.3978347455730106,
|
||||
"kernel": "matern32"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 15,
|
||||
"mean_z2": 0.541,
|
||||
"coverage_90": 0.933,
|
||||
"max_abs_z": 1.76
|
||||
}
|
||||
},
|
||||
"F06-1": {
|
||||
"hyper": {
|
||||
"m_g": 0.01307060629197744,
|
||||
"sigma_g": 0.07599516249066765,
|
||||
"ell_ms": 55.25151554144615,
|
||||
"sigma_b_ms": 22.086526832636057,
|
||||
"sigma_a_ms": 0.3840732626995328,
|
||||
"kernel": "matern32"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 16,
|
||||
"mean_z2": 1.371,
|
||||
"coverage_90": 0.812,
|
||||
"max_abs_z": 2.43
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"se": {
|
||||
"hyper": {
|
||||
"m_g": 0.014864102396223027,
|
||||
"sigma_g": 0.10375484739950913,
|
||||
"ell_ms": 52.366940256310436,
|
||||
"sigma_b_ms": 19.126542781739634,
|
||||
"sigma_a_ms": 0.41337726953625653,
|
||||
"kernel": "se"
|
||||
},
|
||||
"log_marginal": -157.445,
|
||||
"at_bound": [],
|
||||
"loao": {
|
||||
"n": 62,
|
||||
"mean_z2": 0.889,
|
||||
"coverage_90": 0.887,
|
||||
"max_abs_z": 2.53,
|
||||
"per_well": {
|
||||
"F02-1": {
|
||||
"n": 17,
|
||||
"mean_z2": 1.587,
|
||||
"coverage_90": 0.706,
|
||||
"max_abs_z": 2.53
|
||||
},
|
||||
"F03-2": {
|
||||
"n": 14,
|
||||
"mean_z2": 0.323,
|
||||
"coverage_90": 1.0,
|
||||
"max_abs_z": 1.21
|
||||
},
|
||||
"F03-4": {
|
||||
"n": 15,
|
||||
"mean_z2": 0.34,
|
||||
"coverage_90": 1.0,
|
||||
"max_abs_z": 1.23
|
||||
},
|
||||
"F06-1": {
|
||||
"n": 16,
|
||||
"mean_z2": 1.159,
|
||||
"coverage_90": 0.875,
|
||||
"max_abs_z": 1.89
|
||||
}
|
||||
}
|
||||
},
|
||||
"lowo_folds": {
|
||||
"F02-1": {
|
||||
"hyper": {
|
||||
"m_g": 0.012892391684723623,
|
||||
"sigma_g": 0.09528826777317104,
|
||||
"ell_ms": 71.1942628636984,
|
||||
"sigma_b_ms": 21.324903878899132,
|
||||
"sigma_a_ms": 0.4807078443040829,
|
||||
"kernel": "se"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 17,
|
||||
"mean_z2": 4.888,
|
||||
"coverage_90": 0.647,
|
||||
"max_abs_z": 4.83
|
||||
}
|
||||
},
|
||||
"F03-2": {
|
||||
"hyper": {
|
||||
"m_g": 0.022797707169227053,
|
||||
"sigma_g": 0.11891479534680668,
|
||||
"ell_ms": 53.582840730960505,
|
||||
"sigma_b_ms": 21.568036461467557,
|
||||
"sigma_a_ms": 0.42760163307883176,
|
||||
"kernel": "se"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 14,
|
||||
"mean_z2": 0.302,
|
||||
"coverage_90": 1.0,
|
||||
"max_abs_z": 1.14
|
||||
}
|
||||
},
|
||||
"F03-4": {
|
||||
"hyper": {
|
||||
"m_g": 0.008229849921930491,
|
||||
"sigma_g": 0.11938943203711964,
|
||||
"ell_ms": 51.066154478466906,
|
||||
"sigma_b_ms": 0.5,
|
||||
"sigma_a_ms": 0.41045782018438987,
|
||||
"kernel": "se"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 15,
|
||||
"mean_z2": 0.554,
|
||||
"coverage_90": 1.0,
|
||||
"max_abs_z": 1.58
|
||||
}
|
||||
},
|
||||
"F06-1": {
|
||||
"hyper": {
|
||||
"m_g": 0.013706256064916314,
|
||||
"sigma_g": 0.07523933051881347,
|
||||
"ell_ms": 44.457356553389005,
|
||||
"sigma_b_ms": 22.0597906048834,
|
||||
"sigma_a_ms": 0.39117519172099785,
|
||||
"kernel": "se"
|
||||
},
|
||||
"loao_test_well": {
|
||||
"n": 16,
|
||||
"mean_z2": 1.518,
|
||||
"coverage_90": 0.812,
|
||||
"max_abs_z": 2.26
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"selected_kernel": "matern32",
|
||||
"note": "Chọn Matérn-3/2 (chốt trước trong configs/d2_synth.yaml) — log-marginal hai kernel chênh 0.10 (cao hơn: se)."
|
||||
}
|
||||
BIN
outputs/wavelets.npz
Normal file
BIN
outputs/wavelets.npz
Normal file
Binary file not shown.
@@ -58,4 +58,4 @@ Wording must respect `docs/plan.md` §10 (forbidden claims).
|
||||
|
||||
Length: Computers & Geosciences limits a Research Article to about 5,500 words excluding abstract, keywords, highlights,
|
||||
references and captions (secondary source; the official Guide for Authors page could not be fetched on 2026-10-29).
|
||||
The main text (Secs. 1–8) is about 14,750 words (crude count), and exceeds that limit. The length pass was dropped by the user on 2026-10-29 (`docs/plan.md` §12 item 25).
|
||||
The main text (Secs. 1–8) is about 14,950 words (crude count after the 30/10 writing pass), and exceeds that limit. The length pass was dropped by the user on 2026-10-29 (`docs/plan.md` §12 item 25).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
\begin{abstract}
|
||||
Seismic reservoir-property predictors are trained on well logs that a well tie places in two-way time, and the tie is uncertain. We analyse its error as an error in the time index of the label. Under an independence assumption, misregistered labels convolve the optimal predictor with the error distribution and blur the seismic band, as a controlled experiment confirmed to within 1\%. Without time anchors, absolute timing is not identified. A tie computed as a posterior mean has the opposite, Berkson, error structure and sharpens the predictor instead. A calibrated bank of posterior labels attains the oracle's population optimum, but its population gain over a point label is of fourth order in the tie error. On a registration-aware synthetic benchmark calibrated to F3, we compared point ties, posterior-mean labels and a tempered likelihood over a posterior bank under pre-registered rules. The first comparison failed, and the second was designed after that failure. There, posterior-mean labels had 8--22\% lower seismic-band RMSE than the best point tie, but failed when the anchor uncertainty was set at half or twice its true value. The bank gained further in all eight cells with a wide posterior. This gain exceeded the registered population bound for classical tie error in seven cells, but a post hoc bound for Berkson error in only three. Detecting such gains at blind wells requires an accurate reference: with exact ties, 5--18 wells gave a power of 0.8 in most cells; with reference errors of 3\,ms or more, 40 wells did not. The F3 and Volve field tests (four and six wells) failed, and neither could have detected such gains. Teapot Dome has independent time--depth references at no more than two of its 152 wells. We make no field or calibration claim.
|
||||
Seismic reservoir-property predictors are trained on well logs that a well tie places in two-way time, and the tie is uncertain. We analyse its error as an error in the time index of the label. Under an independence assumption, misregistered labels convolve the optimal predictor with the error distribution and blur the seismic band; a controlled experiment matched the predicted transfer to within 1\% for errors of 4--16\,ms. Without time anchors, absolute timing is not identified. A tie computed as a posterior mean has the opposite, Berkson, error structure and sharpens the predictor instead. A calibrated bank of posterior labels attains the oracle's population optimum, but its population gain over a point label is of fourth order in the tie error. On a registration-aware synthetic benchmark calibrated to F3, we compared point ties, posterior-mean labels and a tempered likelihood over a posterior bank under pre-registered rules. The first comparison failed, and the second was designed after that failure. There, posterior-mean labels had 8--22\% lower seismic-band RMSE than the best point tie, most of it already without drift, but failed when the anchor uncertainty was set at half or twice its true value. With 16 training wells, the bank gained further in all eight cells with a wide posterior. This gain exceeded the registered population bound for classical tie error in seven cells, but a post hoc bound for Berkson error in only three. Detecting such gains at blind wells requires an accurate reference: with an exact reference, 5--18 wells gave a power of 0.8 in most cells; with reference errors of 3\,ms or more, 40 wells did not. The F3 and Volve field tests (four and six wells) failed, and neither could have detected such gains. Teapot Dome has independent time--depth references at no more than two of its 152 wells. We make no field or calibration claim.
|
||||
\end{abstract}
|
||||
|
||||
\noindent\textbf{Keywords:} well tie; registration error; errors-in-variables; seismic porosity prediction; synthetic benchmark; blind-well validation; statistical power
|
||||
|
||||
@@ -3,16 +3,18 @@
|
||||
|
||||
Deep networks are widely used to map seismic amplitudes to reservoir properties such as porosity. The common workflow has four steps: tie each well to the seismic, resample the depth logs to two-way time (TWT), train a regressor from seismic to the time-domain labels, and score blind wells against labels produced by the same tie \citep[e.g.][]{xu2024sts,prabowo2025f3,tao2025structural,liu2023lowfrequency}. In this workflow the well tie is a preprocessing step. Its output, a single time--depth curve per well, is treated as exact.
|
||||
|
||||
The tie is not exact. It is an inverse problem with a posterior distribution, and Bayesian treatments of it have existed for two decades and are still being developed \citep{buland2003bayesianwavelet,gunning2006waveletextractor,lim2025awsm}. In those treatments the posterior is the end product: no learning step uses it. The size of the problem is easy to underestimate. At the four public wells of the F3 block, sonic-integrated TWT differs from the interpreted time--depth markers by up to 14--66\,ms, and the difference changes by up to 46\,ms inside a 500\,ms target window (Section~\ref{sec:data}). Two time--depth models distributed with the data disagree with the markers by up to 36\,ms. The dominant period of the seismic is 17--20\,ms. Label timing errors of one to several periods are therefore realistic, and they vary with depth, so a bulk lag cannot absorb them.
|
||||
The tie is not exact. It is an inverse problem with a posterior distribution, and Bayesian treatments of it have existed for two decades and are still being developed \citep{buland2003bayesianwavelet,gunning2006waveletextractor,lim2025awsm}. In those treatments the posterior is the end product: no learning step uses it.
|
||||
|
||||
The size of the timing error is easy to underestimate. At the four public wells of the F3 block, sonic-integrated TWT differs from the interpreted time--depth markers by up to 14--66\,ms, and the difference changes by up to 46\,ms inside a 500\,ms target window (Section~\ref{sec:data}). Two time--depth models distributed with the data disagree with the markers by up to 36\,ms. The dominant period of the seismic is 17--20\,ms. Label timing errors of one to several periods are therefore realistic, and they vary with depth, so a bulk lag cannot absorb them.
|
||||
|
||||
This is a label error of a particular kind. The label values are measured, but they are placed at the wrong times. Work on noisy labels and on errors in variables mostly concerns errors in the values (Section~\ref{sec:related}). A registration error acts on the time index instead: it is correlated along the well, its effect depends on frequency, and it affects the reference against which blind wells are scored as well as the training labels. We ask what such an error does to a learned predictor, whether training on a tie posterior rather than a point tie removes its effect, and whether a field test can detect the difference. We make four contributions.
|
||||
\begin{enumerate}
|
||||
\item[C1] \textbf{Theory.} Under an independence assumption, the MSE-optimal predictor trained on misregistered labels is the correctly registered predictor convolved with the distribution of the timing error, so the seismic band is attenuated by the characteristic function of the error (Proposition~\ref{prop:blur}). A controlled experiment matches this transfer to within 1\%. Without time anchors, a shared network and its label alignment can drift together without changing the loss (Proposition~\ref{prop:ident}), so losses that learn the alignment from the network's own predictions, such as soft-DTW \citep{cuturi2017softdtw} and DILATE \citep{leguen2019dilate}, cannot fix absolute timing. The error of an estimated tie can have the classical structure, which blurs the learned predictor, or the Berkson structure, which sharpens it (Proposition~\ref{prop:tie}). A calibrated bank of posterior labels has the population minimizer of training on the true labels, but its population gain over a point label is of fourth order in the tie error (Proposition~\ref{prop:bank}). We also relate the coverage of predictive intervals to the error structure (Proposition~\ref{prop:coverage}) and give the bias of scoring against a misregistered reference (Proposition~\ref{prop:reference}).
|
||||
\item[C1] \textbf{Theory.} Under an independence assumption, the MSE-optimal predictor trained on misregistered labels is the correctly registered predictor convolved with the distribution of the timing error, so the seismic band is attenuated by the characteristic function of the error (Proposition~\ref{prop:blur}). A controlled experiment matches this transfer to within 1\% for errors of 4--16\,ms, in the band where the predictor has coherent power. Without time anchors, a shared network and its label alignment can drift together without changing the loss (Proposition~\ref{prop:ident}), so losses that learn the alignment from the network's own predictions, such as soft-DTW \citep{cuturi2017softdtw} and DILATE \citep{leguen2019dilate}, cannot fix absolute timing. The error of an estimated tie can have the classical structure, which blurs the learned predictor, or the Berkson structure, which sharpens it (Proposition~\ref{prop:tie}). A calibrated bank of posterior labels has the population minimizer of training on the true labels, but its population gain over a point label is of fourth order in the tie error (Proposition~\ref{prop:bank}). We also relate the coverage of predictive intervals to the error structure (Proposition~\ref{prop:coverage}) and give the bias of scoring against a misregistered reference (Proposition~\ref{prop:reference}).
|
||||
\item[C2] \textbf{A registration-aware benchmark.} We build synthetic data with known true warps from F3 geometry, rock physics and time--depth statistics. We vary drift, seismic signal-to-noise ratio and anchor density, and evaluate under locked, pre-registered pass rules. We report both comparisons that we registered: the first failed, and the second, designed after that failure, passed, with an explicit dependence on correctly specified anchor uncertainty. \todo{S1, S2, S3, S4 and S8 of \texttt{protocol\_bench}: grid fill, misspecification axes, B4 under the SMC posterior, second backbone, controlled cycle skipping.}
|
||||
\item[C3] \textbf{A family of baselines.} Registration-marginalized learning (RML$_\lambda$), a tempered log-likelihood over a bank of labels, contains point-tie training, hard-min and soft-min shift losses and soft-DTW as special cases (Lemmas~\ref{lem:s1}--\ref{lem:sdtw}). We use this family to define the methods compared on the benchmark, not as a proposed method that wins.
|
||||
\item[C4] \textbf{Detectability and the scope of field tests.} We derive how accurately the reference at blind wells must be tied, and how many blind wells are needed, for a comparison of tie methods to detect the effects of C1 (Corollary~\ref{cor:tolerance}, Section~\ref{sec:exp:detect}). We audit the public F3 well data: the porosity labels at three of the four wells are a linear function of the sonic log, and the time--depth markers are horizon-tie picks, not check shots. Pre-registered field tests on F3 and Volve failed, and an inventory of Teapot Dome found an independent time--depth reference at no more than two of its wells. These cases bound the scope of the paper.
|
||||
\end{enumerate}
|
||||
|
||||
On the benchmark, labels at the posterior-mean warp of a sequential Monte Carlo tie beat the best point tie by 8--22\% in seismic-band RMSE at F3-like drift in all three full-anchor regimes. With the anchor uncertainty set at half or twice its true value, this advantage no longer passed the registered rule. A bank of posterior samples gained further when the posterior was wide. In seven of eight cells this gain exceeded the population bound that we registered, which assumes classical tie error, but in only three did it exceed the bound for the Berkson error of a posterior-mean tie, which we computed post hoc. With an exact reference, a sign test at blind wells needed 5--18 wells to detect these gains in most cells, and with reference errors of 3\,ms or more, 40 wells did not suffice. Neither public field dataset that we tested meets these conditions.
|
||||
On the benchmark, labels at the posterior-mean warp of a sequential Monte Carlo tie beat the best point tie by 8--22\% in seismic-band RMSE at F3-like drift in all three full-anchor regimes. Most of this advantage was already present without drift, so part of it comes from the seismic-conditioned tie itself rather than from correcting drift. With the anchor uncertainty set at half or twice its true value, this advantage no longer passed the registered rule. A bank of posterior samples gained further when the posterior was wide, in all eight such cells with 16 training wells. In seven of these eight cells this gain exceeded the population bound that we registered, which assumes classical tie error, but in only three did it exceed the bound for the Berkson error of a posterior-mean tie, which we computed post hoc. With an exact reference, a sign test at blind wells needed 5--18 wells to detect these gains in most cells, and with reference errors of 3\,ms or more, 40 wells did not suffice. Neither public field dataset that we tested meets these conditions.
|
||||
|
||||
Section~\ref{sec:related} positions the work. Section~\ref{sec:data} describes the data and the audit, Section~\ref{sec:theory} the theory, and Section~\ref{sec:method} the tie posterior and the methods. Section~\ref{sec:experiments} reports the benchmark, the detectability analysis and the field cases. Section~\ref{sec:discussion} discusses what the results imply for field studies, and the limitations. Proofs are in Appendix~\ref{app:proofs}, and the field tests in Appendix~\ref{app:field}.
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
\section{Related work}
|
||||
\label{sec:related}
|
||||
|
||||
Three bodies of work meet in this problem, and they have so far been developed separately. Two others study uncertain labels: in statistics and machine learning in general, and in learned seismic interpretation.
|
||||
Three bodies of work meet in this problem and have so far been developed separately: well ties with uncertainty, learned property prediction from few wells, and losses that tolerate temporal misalignment. Two others study uncertain labels, in statistics and machine learning in general and in learned seismic interpretation. We review each in turn and then state what is new.
|
||||
|
||||
\paragraph{Well ties and their uncertainty.}
|
||||
\citet{buland2003bayesianwavelet} model the mistie between seismic time and log time as latent marker shifts with a triangular prior. They estimate these shifts jointly with the wavelet by MCMC and report their posterior. \citet{gunning2006waveletextractor} estimate the wavelet jointly with check-shot and marker times (Gaussian priors, monotonicity enforced), a registration shift and a lateral positioning error per well. They obtain uncertainty from a Laplace approximation and choose the wavelet length by marginal likelihood. \citet{lim2025awsm} infer time--depth transform parameters and wavelets jointly with parallel-tempering MCMC and report uncertainty estimates for a Midland Basin case study. Neither prior over time shifts nor a posterior over the time--depth relation is therefore new. In these works, however, the posterior is the end product. \citet{lim2025awsm} pass the estimated wavelets on to AVO/AVA inversion; their abstract does not describe passing the time--depth uncertainty on to a later step. \citet{wu2017multiwelltie} tie several wells at once with smooth depth-variable shifts and give no tie uncertainty. \citet{herrera2012automatedtie} use dynamic time warping for the tie. Among learning-based methods, \citet{tschannen2022partialtie} estimate the wavelet with a variational network: their uncertainty is mainly in wavelet phase, and the bulk shift is found by Bayesian optimization within user-set bounds. \citet{di2023welltie} and \citet{li2025cascadedtie} automate the tie with self-supervised learning and cascaded matching. All these methods output a tie, sometimes with wavelet or shift uncertainty, and stop there.
|
||||
Posteriors over the well tie exist, but in every method we found the tie is the end product. \citet{buland2003bayesianwavelet} model the mistie between seismic time and log time as latent marker shifts with a triangular prior. They estimate these shifts jointly with the wavelet by MCMC and report their posterior. \citet{gunning2006waveletextractor} estimate the wavelet jointly with check-shot and marker times (Gaussian priors, monotonicity enforced), a registration shift and a lateral positioning error per well. They obtain uncertainty from a Laplace approximation and choose the wavelet length by marginal likelihood. \citet{lim2025awsm} infer time--depth transform parameters and wavelets jointly with parallel-tempering MCMC and report uncertainty estimates for a Midland Basin case study. Neither prior over time shifts nor a posterior over the time--depth relation is therefore new. In these works, however, the posterior is not used further. \citet{lim2025awsm} pass the estimated wavelets on to AVO/AVA inversion; their abstract does not describe passing the time--depth uncertainty on to a later step. \citet{wu2017multiwelltie} tie several wells at once with smooth depth-variable shifts and give no tie uncertainty. \citet{herrera2012automatedtie} use dynamic time warping for the tie. Among learning-based methods, \citet{tschannen2022partialtie} estimate the wavelet with a variational network: their uncertainty is mainly in wavelet phase, and the bulk shift is found by Bayesian optimization within user-set bounds. \citet{di2023welltie} and \citet{li2025cascadedtie} automate the tie with self-supervised learning and cascaded matching. All these methods output a tie, sometimes with wavelet or shift uncertainty, and stop there.
|
||||
|
||||
\paragraph{Learning reservoir properties from seismic with few wells.}
|
||||
Recent studies predict porosity or impedance with convolutional, recurrent or transformer networks, sometimes with physics constraints or uncertainty estimates \citep{alfarraj2019semisupervised,vashisth2022rwpinn,liu2023lowfrequency,xu2024sts,chen2024multidimensional,li2024bpinn,ntibahanana2024ensemble,corrales2024seis2rock,dou2024seismae,tao2025structural,prabowo2025f3,cordoba2025porosity,rezaei2026krigingrf,sukar2026uncertainty}. In the studies we read in full, the labels are placed on the seismic time axis by a tie that is taken as given. \citet{xu2024sts} say so explicitly, and their augmentation shifts windows laterally, not in time. \citet{ali2025syntheticpseudowells} name the seismic-to-well tie discrepancy as a challenge and avoid it by training on synthetic pseudo-wells. Where uncertainty is estimated, it is the uncertainty of the network or of the data noise. It does not include the uncertainty of the label timing. \citet{cordoba2025porosity} report noise-sensitivity tests, but their abstract does not mention the tie or misregistered labels. Bayesian and variational inversions give posteriors or credible intervals for porosity or impedance \citep{thiebaud2024lfc,rizzuti2024waveletflows,rizzuti2025uhr}, and a bootstrapped network ensemble gives a spread of elastic-property predictions \citep{lim2025bootnet}. None of these abstracts names the well tie as a source of uncertainty.
|
||||
@@ -13,7 +13,9 @@ Recent studies predict porosity or impedance with convolutional, recurrent or tr
|
||||
Soft-DTW \citep{cuturi2017softdtw} and DILATE \citep{leguen2019dilate} replace the pointwise loss with a smoothed minimum over monotone alignments. Shift-tolerant losses that take the minimum over a set of bulk lags are a simpler variant. These losses use no time anchors, no physical tie model and no prior over warps. Proposition~\ref{prop:ident} shows that, without anchors, the absolute timing they learn is not identified. Learned alignment has also been applied to seismic inputs. \citet{huff2024anglestack} train a CNN on synthetic angle stacks moveout-corrected with true and perturbed velocities and use it to align field angle stacks. There the misaligned quantities are the inputs, and the synthetic targets are aligned by construction.
|
||||
|
||||
\paragraph{Label noise and errors in variables.}
|
||||
Measurement-error models distinguish classical error, which is independent of the true value, from Berkson error, which is independent of the assigned value \citep{berkson1950two,fuller1987measurement,carroll2006measurement}. In linear regression, classical error in a covariate attenuates the fitted slope, while Berkson error leaves it unbiased and adds variance. Work on noisy labels in machine learning mostly treats corrupted class labels, with robust losses, sample selection or models of the corruption process \citep{frenay2014label,song2023noisy}. Closest to our setting, \citet{mnih2012aerial} train a network to label roads in aerial images from maps whose objects are misplaced. They model the observed map as a translated crop of the true map, marginalize the likelihood over a small set of translations whose prior is set on validation data, and fit it by expectation--maximization. Without its omission term, this is a bank of shifted labels with $\lambda = 1$ and no anchors (Section~\ref{sec:method:rml}). They also score predictions with a tolerance of three pixels, because the ground truth is itself misregistered, and suggest that their noise-robust models lost precision at low recall on one test set because that set was poorly registered. Proposition~\ref{prop:reference} states the analogous effect for band MSE. The spectral effect of random timing errors has long been studied for sampling jitter \citep{balakrishnan1962jitter}. A misregistered well label differs from these cases in where the error enters. Its values are correct, but they are placed at the wrong times. The error acts on the time index, it is correlated along the well, and its effect depends on frequency: it leaves the low frequencies nearly unchanged and blurs the seismic band (Proposition~\ref{prop:blur}). The classical and Berkson structures carry over to the time index, where they bias the learned predictor in opposite directions (Proposition~\ref{prop:tie}).
|
||||
Measurement-error models distinguish classical error, which is independent of the true value, from Berkson error, which is independent of the assigned value \citep{berkson1950two,fuller1987measurement,carroll2006measurement}. In linear regression, classical error in a covariate attenuates the fitted slope, while Berkson error leaves it unbiased and adds variance. Work on noisy labels in machine learning mostly treats corrupted class labels, with robust losses, sample selection or models of the corruption process \citep{frenay2014label,song2023noisy}. Closest to our setting, \citet{mnih2012aerial} train a network to label roads in aerial images from maps whose objects are misplaced. They model the observed map as a translated crop of the true map, marginalize the likelihood over a small set of translations whose prior is set on validation data, and fit it by expectation--maximization. Without its omission term, this is a bank of shifted labels with $\lambda = 1$ and no anchors (Section~\ref{sec:method:rml}). They also score predictions with a tolerance of three pixels, because the ground truth is itself misregistered, and suggest that their noise-robust models lost precision at low recall on one test set because that set was poorly registered. Proposition~\ref{prop:reference} states the analogous effect for band MSE.
|
||||
|
||||
The spectral effect of random timing errors has long been studied for sampling jitter \citep{balakrishnan1962jitter}. A misregistered well label differs from these cases in where the error enters. Its values are correct, but they are placed at the wrong times. The error acts on the time index, it is correlated along the well, and its effect depends on frequency: it leaves the low frequencies nearly unchanged and blurs the seismic band (Proposition~\ref{prop:blur}). The classical and Berkson structures carry over to the time index, where they bias the learned predictor in opposite directions (Proposition~\ref{prop:tie}).
|
||||
|
||||
\paragraph{Label uncertainty in learned seismic interpretation.}
|
||||
\citet{quesada2024faultlabels} collected fault labels on 400 F3 images from 38 annotators with different expertise and confidence. \citet{mirza2025labelquality} assess the variability of manual salt interpretations together with seismic image quality. \citet{guillon2020gtmetrics} add a tolerance distance to fault and horizon metrics, because thin boundaries cannot be placed exactly. In these works the label is an interpretation of the seismic image itself, the task is classification or segmentation, and the uncertainty is described by annotator disagreement or a spatial tolerance. In our problem the label values come from well logs, and their position on the seismic time axis is what is uncertain. A physical tie model conditioned on anchors gives a posterior for that position.
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
\section{Theory}
|
||||
\label{sec:theory}
|
||||
|
||||
This section asks what a registration error in the training labels does to a learned predictor and to its evaluation. Section~\ref{sec:theory:blur} shows that independent timing errors blur the optimal predictor, and Section~\ref{sec:theory:ident} that without anchors absolute timing is not identified. Section~\ref{sec:theory:post} distinguishes the two error structures of an estimated tie and bounds what a bank of posterior labels can gain. Sections~\ref{sec:theory:cov} and~\ref{sec:theory:ref} relate the error to the coverage of predictive intervals and to the bias of scoring against a misregistered reference. Proofs are in Appendix~\ref{app:proofs}.
|
||||
|
||||
\paragraph{Notation.}
|
||||
$t$ is seismic two-way time, $X$ the seismic input around a well, and $y(t)$ the label under correct registration. $\delta(t)$ is the registration error, and the observed label is $\tilde y(t) = y(t + \delta(t))$. The oracle predictor is $m(t) = \E[y(t)\mid X]$, the MSE-optimal predictor under correct labels. The Fourier transform is $\hat g(f) = \int g(t)\,e^{-i2\pi f t}\dd t$, and $T_\beta h(t) = h(t-\beta)$ is a time shift. $S_a$ is the power spectrum of $a$. The seismic band is $|f| \ge f_c$ with $f_c = 6$\,Hz, and $B$ is the corresponding high-pass operator, with $a_b = Ba$. In the experiments $B$ is a zero-phase fourth-order Butterworth filter. Its response is real and non-negative, so every result below holds with $S$ replaced by $|H_B|^2 S$. Spectral statements assume second-order stationarity in $t$, which is a working assumption for well logs.
|
||||
|
||||
\subsection{Misregistered labels blur the optimal predictor}
|
||||
\label{sec:theory:blur}
|
||||
|
||||
\begin{proposition}[Blur]
|
||||
\label{prop:blur}
|
||||
@@ -74,6 +77,7 @@ $\sigma$ (ms) & $r(\sigma)$ & 95\% CI & frequencies & band RMSE & band PCC & ban
|
||||
\end{figure}
|
||||
|
||||
\subsection{Without anchors, absolute timing is not identified}
|
||||
\label{sec:theory:ident}
|
||||
|
||||
Consider $N$ training wells with seismic $X_w$, depth logs $\phi_w$ and warps $u_w = (b_w, g_w)$ (Section~\ref{sec:method:prior}). Let $y^{u}(t) = (\aaf\phi)(z_u(t))$ be the label under warp $u$, where $z_u$ inverts $t_u$ and $\aaf$ is an anti-alias filter. Let $e_b$ be the direction that adds the same $\beta$ to every $b_w$. The joint MAP objective over network parameters $\theta$ and warps $\mathbf{u}$ is
|
||||
\begin{equation}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
\section{Registration-marginalized learning}
|
||||
\label{sec:method}
|
||||
|
||||
RML has two stages. First, a posterior over the time--depth warp of each training well is computed from anchors and, optionally, from the seismic. No network is involved. Second, a network is trained on a bank of labels drawn from this posterior. At prediction time no warp is needed: the network maps seismic to a property trace on the seismic time axis.
|
||||
This section describes the tie posterior and registration-marginalized learning (RML), a loss that contains the compared methods as special cases. We use RML to define the methods on a common footing, not as a proposed method expected to win (contribution C3). RML has two stages. First, a posterior over the time--depth warp of each training well is computed from anchors and, optionally, from the seismic. No network is involved. Second, a network is trained on a bank of labels drawn from this posterior. At prediction time no warp is needed: the network maps seismic to a property trace on the seismic time axis.
|
||||
|
||||
\subsection{Warp prior and anchors}
|
||||
\label{sec:method:prior}
|
||||
@@ -27,10 +27,10 @@ where $\mathbf r_w$ is the reflectivity computed from acoustic impedance $\rho_w
|
||||
\subsection{Two tie posteriors}
|
||||
\label{sec:method:posterior}
|
||||
|
||||
\paragraph{Anchor posterior with importance weights (P2).}
|
||||
\paragraph{Anchor posterior with importance weights (Experiment~1).}
|
||||
We draw $S = 64$ warps per well from the anchor-conditioned posterior. The proposal is a Laplace (Gauss--Newton) approximation, refined by elliptical slice sampling \citep{murray2010ess}. Physical weights $\pi_s \propto p(\mathbf s_w\mid u^{(s)})^{\gamma}$ use the largest $\gamma$ that keeps the effective sample size at least $S/4$.
|
||||
|
||||
\paragraph{Sequential Monte Carlo posterior (P2r).}
|
||||
\paragraph{Sequential Monte Carlo posterior (Experiment~2).}
|
||||
Importance weights over 64 anchor-conditioned samples cannot move mass to warps that the anchor posterior rarely proposes. In development runs the weighted posterior did not contract to the true warp (Section~\ref{sec:exp:diag}). The second posterior therefore uses tempered sequential Monte Carlo. We introduced it only after the first pre-registered comparison had failed, so it is a deviation from the original protocol, and we report it as one (Section~\ref{sec:exp:diag}). It starts from $P = 1024$ anchor-posterior samples and targets $p(u\mid \text{anchors})\, p(\mathbf s_w\mid u, \psi)^{\gamma}$. The tempering exponent rises from 0 to $\gamma$ in adaptive steps that keep the effective sample size at least $P/2$. Each step uses systematic resampling followed by eight elliptical slice moves. Before the trial we registered a stability criterion: the 95th percentile over $t$ of the difference between mean warps of independent runs must not exceed 0.5\,ms. $P = 1024$ meets it at $c = 1$ on development data. At $c = 2$ the posterior is multimodal and the mean warp is unstable under every configuration we tried. We summarize posterior width by $\sigpost = w_{90}/3.29$, where $w_{90}$ is the 90\% interval width of $\tau(t)$ averaged over the main window and the training wells. No labels are used to compute it.
|
||||
|
||||
\subsection{Labels for each warp}
|
||||
@@ -128,7 +128,7 @@ B3a & sonic integration from one shallow anchor & NLL \\
|
||||
B3b & marker-calibrated sonic through the anchors & NLL \\
|
||||
B3c & B3b plus local shifts from synthetic--seismic correlation & NLL \\
|
||||
B3c-R & B3c with the SMC-estimated wavelet phase & NLL \\
|
||||
B3d & weighted mean warp of the P2 anchor posterior & NLL \\
|
||||
B3d & weighted mean warp of the Experiment~1 anchor posterior & NLL \\
|
||||
\mPM & mean warp of the SMC posterior & NLL \\
|
||||
Oracle & true warp (synthetic only; a ceiling, not a competitor) & NLL \\
|
||||
\midrule
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
\section{Experiments}
|
||||
\label{sec:experiments}
|
||||
|
||||
We ran two pre-registered synthetic experiments, in order, and then pre-registered field tests on F3 and Volve (Section~\ref{sec:exp:scope}; details in Appendix~\ref{app:field}). Before each main run, the protocol (grid, methods, iteration budgets, pass rules) was locked by a SHA-256 hash, and the scripts refuse to run if the hash does not match. The two synthetic protocols were also committed and tagged in version control before their main runs. The field protocols were committed only after their runs, so for them the record of timing is the time stamp inside the lock file (Appendix~\ref{app:field}). In the synthetic experiments, every design choice was made on two development realizations (900 and 901), which are never used for results. Test labels were never used to choose a shift, checkpoint or hyperparameter. In the synthetic experiments, a comparison \emph{improves} if the candidate's seismic-band RMSE is at most 0.90 times that of the best competitor, \emph{or} its band PCC is at least 0.05 higher. Here ``best'' means the competitor with the smallest mean band RMSE in that cell. A cell \emph{passes} if the comparison improves in at least 4 of 5 seeds (each averaged over realizations) and in more than half of the realizations (each averaged over seeds). All cells use eight test wells.
|
||||
We ran two pre-registered synthetic experiments, in order, and then pre-registered field tests on F3 and Volve (Section~\ref{sec:exp:scope}; details in Appendix~\ref{app:field}). Before each main run, the protocol (grid, methods, iteration budgets, pass rules) was locked by a SHA-256 hash, and the scripts refuse to run if the hash does not match. The two synthetic protocols were also committed and tagged in version control before their main runs. The field protocols were committed only after their runs, so for them the record of timing is the time stamp inside the lock file (Appendix~\ref{app:field}). In the synthetic experiments, every design choice was made on two development realizations (900 and 901), which are never used for results. Test labels were never used to choose a shift, checkpoint or hyperparameter.
|
||||
|
||||
Every synthetic comparison is decided by the same pre-registered rule. A comparison \emph{improves} if the candidate's seismic-band RMSE is at most 0.90 times that of the best competitor, \emph{or} its band PCC is at least 0.05 higher. Here ``best'' means the competitor with the smallest mean band RMSE in that cell. A cell \emph{passes} if the comparison improves in at least 4 of 5 seeds (each averaged over realizations) and in more than half of the realizations (each averaged over seeds). All cells use eight test wells.
|
||||
|
||||
\subsection{Experiment 1: anchor-posterior banks (gate G-B)}
|
||||
\label{sec:exp:p2}
|
||||
@@ -122,7 +124,7 @@ $\sigma_a^{\mathrm{reg}}$ (ms) & ratio $N = 4$ & ratio $N = 16$ & cells pass & $
|
||||
At $N = 16$ all three tests passed (Table~\ref{tab:h2b}, Fig.~\ref{fig:h2b}a). All 8 wide cells passed, the ratio decreased with $\sigpost$ (Spearman $\rho = -0.85$, one-sided permutation $p < 0.001$), and the mean ratio over narrow cells was 0.996. The gains in wide cells ranged from 2\% (Rm5, $c = 1$) to 11\% (R10tb, $c = 1$). At $c = 2$ they reached 33\% (R10tb), but those cells are flagged unstable. At $N = 4$, which was reported but not used for the verdict, 6 of 8 wide cells passed ($\rho = -0.77$, narrow mean 1.001).
|
||||
|
||||
\paragraph{Comparison with the population bound.}
|
||||
The column $1/B_a$ of Table~\ref{tab:h2b} is the registered bound: $\rho^\star$ of \eqref{eq:rhostar} for Gaussian classical error at $\sigpost$, computed by blurring the Oracle's predictions. It is the largest gain over the point label that removing a population blur could give (Section~\ref{sec:theory:post}). The measured ratio is below it in 7 of the 8 wide cells (Fig.~\ref{fig:h2b}b). At Rm5, $c = 1$, for example, the bound allows no gain (1.000), yet RML gained 2\%. The exception is R10tb at $c = 2$, where $\sigpost$ lies beyond the 6\,ms edge of the grid on which $B$ was computed. The tabulated value is therefore $1/B_a(6\,\mathrm{ms})$, and at $\sigpost$ itself the bound is 0.481.
|
||||
Whether this gain exceeds what removing a population distortion could give depends on the assumed structure of the tie error: it does in most wide cells under the registered classical bound, but in few under the Berkson bound. The column $1/B_a$ of Table~\ref{tab:h2b} is the registered bound: $\rho^\star$ of \eqref{eq:rhostar} for Gaussian classical error at $\sigpost$, computed by blurring the Oracle's predictions. It is the largest gain over the point label that removing a population blur could give (Section~\ref{sec:theory:post}). The measured ratio is below it in 7 of the 8 wide cells (Fig.~\ref{fig:h2b}b). At Rm5, $c = 1$, for example, the bound allows no gain (1.000), yet RML gained 2\%. The exception is R10tb at $c = 2$, where $\sigpost$ lies beyond the 6\,ms edge of the grid on which $B$ was computed. The tabulated value is therefore $1/B_a(6\,\mathrm{ms})$, and at $\sigpost$ itself the bound is 0.481.
|
||||
|
||||
The registered structure is not the one expected for \mPM{}, whose labels sit at the posterior-mean warp. The natural idealization for the error of a posterior mean is the Berkson structure (b), and under (b) the bound is lower (Section~\ref{sec:theory:post}). The column $1/B_b$ gives this bound, computed post hoc in the same way but by sharpening the Oracle's predictions, at $\sigpost$ itself. The measured ratio is below it in 3 of the 8 wide cells, all at $c = 1$ (R0, R0h and R10tb). In R0h and R10tb the margin is less than 0.004, well inside the 95\% interval of the ratio. Sharpening also amplifies the Oracle's own estimation error, which lowers $1/B_b$, most of all at $c = 2$. Two variants limit this amplification. One holds the gain at its 60\,Hz value above 60\,Hz. The other replaces the spectrum of the Oracle's predictions by their cross-spectrum with the true labels. Both select the same three cells, and with the cross-spectrum the (a) bound is exceeded in only 5 of the 8 cells.
|
||||
|
||||
|
||||
@@ -5,10 +5,14 @@
|
||||
The two experiments separate two questions that are easy to conflate. The first is whether the tie posterior is informative. The second is whether training on it helps. In Experiment~1 the posterior was not informative: 64 anchor-conditioned samples reweighted by tie likelihoods stayed as wide as the anchors allowed, and labels drawn from them were no better than a good correlation-based point tie. Once the posterior contracted (SMC, Experiment~2), labels at its mean beat every point tie in all three full-anchor regimes, and a bank of its samples gained further when the posterior was wide. Better registration of the training labels came first. Marginalizing over what remained then added a smaller, width-dependent gain. Neither result says that marginalization rescues a poor posterior, and Experiment~1 is direct evidence that it does not.
|
||||
|
||||
\paragraph{Where the bank gain comes from.}
|
||||
The theory gives a population limit, and whether the measured gains exceed it depends on the structure of the tie error. In population, a calibrated bank has the minimizer of training on the true labels (Proposition~\ref{prop:bank}), and no method improves on a point label by more than the factor $\rho^\star$ of \eqref{eq:rhostar}. Its distortion term is of fourth order in the tie error. For the Oracle predictions of Experiment~2 it sits near 70\,Hz, where a Berkson error distorts much more than a classical error of the same width (Section~\ref{sec:theory:post}). Under the registered bound for classical error, \mRML{} gained more than the limit allows in 7 of the 8 wide cells at $N = 16$. Under the bound for Berkson error, the natural idealization for labels at the posterior-mean warp, it did so in 3 cells at the posterior width and in at most 1 at the measured warp error of \mPM{} (Section~\ref{sec:exp:p2r}). In most cells the bank gain is therefore no larger than removing a population sharpening of \mPM{} could give, but this rests on an error structure that was not tested. On synthetic data the covariance test of Section~\ref{sec:theory:post} can settle it (Section~\ref{sec:exp:mech}). Finite-sample effects can add to this population effect or outweigh it: the label error itself is of first order, and its effect on the conditional variance that a network must absorb is of second order, against the fourth-order population distortion (Section~\ref{sec:theory:post}). Part of the gap to the Oracle is not caused by registration at all. At $c = 0$, with SMC warp errors of 0.2--0.7\,ms, the Oracle was still 1--3\% better than \mPM{}, and it was trained twice as long. \mRML{} closed 27--46\% of the gap between \mPM{} and the Oracle at $c = 1$, and it did not reach the Oracle in any wide cell at $N = 16$. Beyond the population correction, three mechanisms could contribute to the bank gain. The bank acts as label augmentation, and the learned variance absorbs its spread. For $\lambda > 0$ the responsibilities re-register the labels during training (Remark~\ref{rem:lambda}). A multimodal posterior gives the mean warp a non-Gaussian error, against which a bank can gain more than the Gaussian bound allows (Corollary~\ref{cor:twomode}). Until the exploratory analysis of Section~\ref{sec:exp:mech} is done, the bank gain is an empirical regularity of this benchmark whose source is not identified.
|
||||
The theory gives a population limit, and whether the measured gains exceed it depends on the structure of the tie error. In population, a calibrated bank has the minimizer of training on the true labels (Proposition~\ref{prop:bank}), and no method improves on a point label by more than the factor $\rho^\star$ of \eqref{eq:rhostar}. Its distortion term is of fourth order in the tie error. For the Oracle predictions of Experiment~2 it sits near 70\,Hz, where a Berkson error distorts much more than a classical error of the same width (Section~\ref{sec:theory:post}). Under the registered bound for classical error, \mRML{} gained more than the limit allows in 7 of the 8 wide cells at $N = 16$. Under the bound for Berkson error, the natural idealization for labels at the posterior-mean warp, it did so in 3 cells at the posterior width and in at most 1 at the measured warp error of \mPM{} (Section~\ref{sec:exp:p2r}). In most cells the bank gain is therefore no larger than removing a population sharpening of \mPM{} could give, but this rests on an error structure that was not tested. On synthetic data the covariance test of Section~\ref{sec:theory:post} can settle it (Section~\ref{sec:exp:mech}).
|
||||
|
||||
Finite-sample effects can add to this population effect or outweigh it: the label error itself is of first order, and its effect on the conditional variance that a network must absorb is of second order, against the fourth-order population distortion (Section~\ref{sec:theory:post}). Part of the gap to the Oracle is not caused by registration at all. At $c = 0$, with SMC warp errors of 0.2--0.7\,ms, the Oracle was still 1--3\% better than \mPM{}, and it was trained twice as long. \mRML{} closed 27--46\% of the gap between \mPM{} and the Oracle at $c = 1$, and it did not reach the Oracle in any wide cell at $N = 16$.
|
||||
|
||||
Beyond the population correction, three mechanisms could contribute to the bank gain. The bank acts as label augmentation, and the learned variance absorbs its spread. For $\lambda > 0$ the responsibilities re-register the labels during training (Remark~\ref{rem:lambda}). A multimodal posterior gives the mean warp a non-Gaussian error, against which a bank can gain more than the Gaussian bound allows (Corollary~\ref{cor:twomode}). Until the exploratory analysis of Section~\ref{sec:exp:mech} is done, the bank gain is an empirical regularity of this benchmark whose source is not identified.
|
||||
|
||||
\paragraph{When to use a bank rather than the posterior mean.}
|
||||
Within this benchmark the answer depends on the posterior width. When the posterior is narrow ($\sigpost < 1.5$\,ms), \mRML{} and \mPM{} are equivalent within 1\% on average, so the bank costs little and brings nothing. When the posterior is wide, because of low SNR, sparse anchors or strong drift, \mRML{} passed in all eight wide cells at $N = 16$, and over all cells at $N = 16$ the gain grew with the width (Spearman $\rho = -0.85$). The bank is cheap: 64 labels per window add little to the cost of training. A practical rule is therefore to train with the bank whenever the tie posterior is wider than about 1.5\,ms. The largest gain at $c = 1$ came with sparse anchors (R10tb), where the posterior was overconfident and the bank was narrower than the error it was meant to represent, so in that regime the bank helped without being calibrated. On real data the width cannot be checked against a true warp, and it depends on $\sigma_a$.
|
||||
Within this benchmark the answer depends on the posterior width. When the posterior is narrow ($\sigpost < 1.5$\,ms), \mRML{} and \mPM{} are equivalent within 1\% on average, so the bank costs little and brings nothing. When the posterior is wide, because of low SNR, sparse anchors or strong drift, \mRML{} passed in all eight wide cells at $N = 16$, and over all cells at $N = 16$ the gain grew with the width (Spearman $\rho = -0.85$). The bank adds little to training once the posterior has been computed: the network is evaluated once per window, and only the likelihood is evaluated for each of the 64 labels. A practical rule for this benchmark is therefore to train with the bank whenever the tie posterior is wider than about 1.5\,ms. The largest gain at $c = 1$ came with sparse anchors (R10tb), where the posterior was overconfident and the bank was narrower than the error it was meant to represent, so in that regime the bank helped without being calibrated. On real data the width cannot be checked against a true warp, and it depends on $\sigma_a$.
|
||||
|
||||
\paragraph{The anchor uncertainty is the main risk.}
|
||||
Every positive result of Experiment~2 assumes that $\sigma_a$ is known. Halving or doubling it removed the H2a advantage in every cell and miscalibrated the posterior in both directions (Table~\ref{tab:sigmaa}). On F3 the time--depth markers are horizon-tie picks on the same seismic. A type-II estimate treats them as exact (0.4\,ms), while the spread between markers and horizons suggests 7\,ms. The two values place F3 at opposite ends of the $\sigpost$ axis, at about 0.6\,ms (narrow, like R10) or 2.5--3.4\,ms (wide, close to Rm5), and the arms at 3.5 and 14\,ms did not change the F3 outcome (Appendix~\ref{sec:exp:f3}). The width that decides between \mPM{} and \mRML{} inherits this dependence. An estimate of $\sigma_a$ from independent time--depth data at wells outside the test set is therefore a precondition for using the tie posterior, not a refinement of it.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
A well tie is an uncertain estimate, yet learning workflows treat it as exact. Its error is an error in the time index of the label. Under an independence assumption, the error convolves the optimal predictor with its distribution and blurs the seismic band, and without time anchors the absolute timing of a network and its label alignment is not identified. An estimated tie can have the classical error structure, which blurs the learned predictor, or the Berkson structure, which sharpens it. A calibrated bank of posterior labels removes both biases in population, but its population gain over a point label is of fourth order in the tie error.
|
||||
|
||||
On a registration-aware synthetic benchmark calibrated to F3, the first pre-registered comparison failed because the anchor-only posterior was not informative. In the second, designed after that failure, labels at the mean of a sequential Monte Carlo tie posterior beat the best point tie by 8--22\% in seismic-band RMSE, provided that the anchor uncertainty was correctly specified. Training on the posterior bank gained further when the posterior was wide. Under the Berkson error structure that is natural for a posterior-mean tie, the gain stayed within the population limit in most cells. That structure was not tested, and the experiments do not separate the population effect from finite-sample effects of the bank.
|
||||
On a registration-aware synthetic benchmark calibrated to F3, the first pre-registered comparison failed because the anchor-only posterior was not informative. In the second, designed after that failure, labels at the mean of a sequential Monte Carlo tie posterior beat the best point tie by 8--22\% in seismic-band RMSE, mostly already without drift, provided that the anchor uncertainty was correctly specified. Training on the posterior bank gained further when the posterior was wide. Under the Berkson error structure that is natural for a posterior-mean tie, the gain stayed within the population limit in most cells. That structure was not tested, and the experiments do not separate the population effect from finite-sample effects of the bank.
|
||||
|
||||
Whether such gains hold on field data is a question that the public datasets we examined cannot answer. A blind-well comparison of tie methods needs a reference that is independent of the seismic and accurate to about 1\,ms, enough blind wells for a test with adequate power, an anchor uncertainty estimated outside the test set, and networks with skill in the seismic band. The F3 and Volve tests met none of these conditions and failed, and Teapot Dome has independent time--depth references at no more than two of its 152 wells. We claim no improvement on field data and no calibrated uncertainty. The benchmark, the locked protocols and the detectability analysis are the means to test such claims once a dataset that meets these conditions is available.
|
||||
|
||||
|
||||
72
paper/self_review.md
Normal file
72
paper/self_review.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# Self-review of the draft (30/10/2026)
|
||||
|
||||
Pass made with the `research-paper-writing` skill (Master-cai/Research-Paper-Writing-Skills).
|
||||
Red TODO notes (`\todo`, `\todoblock`, `\figplaceholder`) were left byte-identical; no registered number or citation changed.
|
||||
|
||||
## Story (one line per element)
|
||||
|
||||
- **Thesis.** A well-tie error is an error in the time index of the label; we say what it does to a learned predictor, what a tie posterior can recover, and what a field test would need to detect the difference.
|
||||
- **Theory.** Classical tie error blurs the optimal predictor; Berkson error sharpens it; anchors identify absolute time; a calibrated bank recovers the oracle optimum but its population gain is fourth order; a misregistered reference biases blind-well scores.
|
||||
- **Benchmark.** Posterior-mean (SMC) labels beat point ties only with a correct σ_a, and mostly already at c = 0; a bank adds a width-dependent gain that mostly stays within the Berkson bound.
|
||||
- **Detectability and field.** Blind-well comparisons need a reference accurate to about 1 ms and a power-based number of wells; F3, Volve and Teapot do not meet these conditions.
|
||||
|
||||
## Edits made
|
||||
|
||||
| Section | Edit | Skill rule |
|
||||
|---|---|---|
|
||||
| Abstract | H1 "within 1%" limited to σ = 4–16 ms; "most of it already without drift"; bank 8/8 limited to N = 16; "exact ties" → "an exact reference" | claim–evidence alignment |
|
||||
| 1 | Paragraph 2 split (tie posteriors unused / size of the error); same three claim limits as the abstract | one message per paragraph; claim–evidence |
|
||||
| 2 | Opening names the five strands; topic sentence for the well-tie paragraph; label-noise paragraph split | topic sentence first; one message per paragraph |
|
||||
| 4 | Roadmap paragraph; labels `sec:theory:blur`, `sec:theory:ident` | self-contained structure |
|
||||
| 5 | Opening says RML defines the compared methods, not a proposed winner (C3); repo codes P2/P2r → Experiment 1/2 | stable terminology |
|
||||
| 6 | Opening split (protocol / pass rule); bound comparison opens with its conclusion | first sentence states the message |
|
||||
| 7 | "Where the bank gain comes from" split into three paragraphs; "the bank is cheap" replaced by the cost argument from the loss definition; practical rule scoped to the benchmark | one message per paragraph; unsupported claim |
|
||||
| 8 | "mostly already without drift" | claim–evidence |
|
||||
|
||||
## Claim–evidence map (Abstract, Introduction, Conclusions)
|
||||
|
||||
| Claim | Evidence | Status |
|
||||
|---|---|---|
|
||||
| Misregistered labels convolve the optimum with the error distribution | Prop. 1, App. A | supported (analytic, under A1) |
|
||||
| Controlled experiment matches the transfer to within 1% for 4–16 ms | Table `tab:h1` (r = 1.007–1.009); only 6.8–22.5 Hz tested; 32 ms is 9% off | supported as worded |
|
||||
| Without anchors absolute timing is not identified | Prop. 2; H4 (warp RMSE 3.15 → 31.1 ms) | supported |
|
||||
| Berkson tie error sharpens the predictor | Prop. 3 | supported (analytic); **not tested empirically in the text** (Sec. 6.4 is a TODO) |
|
||||
| Calibrated bank attains the oracle optimum; gain is fourth order | Prop. 4, Eq. `eq:rhostar` | supported (analytic) |
|
||||
| PM labels 8–22% lower band RMSE than the best point tie | Table `tab:h2a` (ratios 0.782–0.923) | supported |
|
||||
| Most of the PM advantage is present without drift | Table `tab:h2a` zero-drift column (0.81–0.88) | supported |
|
||||
| PM advantage fails at σ_a halved or doubled | Table `tab:sigmaa` | supported **at R10 only**; the arm ran in one regime |
|
||||
| Bank gains in all 8 wide cells at N = 16 | Table `tab:h2b`; N = 4: 6/8 | supported |
|
||||
| Gain exceeds classical bound in 7/8, Berkson bound in 3/8 | Table `tab:h2b`, `outputs/p2r/posthoc/` | supported (Berkson bound post hoc) |
|
||||
| 5–18 blind wells for power 0.8 with an exact reference; none within 40 at ≥ 3 ms | Table `tab:t3` | supported (exploratory, one simulator) |
|
||||
| F3 and Volve tests failed and could not have detected the effect | Sec. 6.6, App. B, conditions C1–C4 | supported (C1–C4 post hoc) |
|
||||
| Teapot has independent time–depth references at ≤ 2 of 152 wells | Sec. 6.6 | supported |
|
||||
|
||||
## Five-dimension adversarial review
|
||||
|
||||
**Contribution.** *Is anything new beyond assembling known pieces?* The paper says plainly that the ingredients are known (Sec. 2, last paragraph). The new parts are the analysis applied to the time index, the bound on what a bank can gain, and the detectability result. A reviewer may still see C3 (RML family) as a relabelling exercise; the text now frames it as a common language, which is the defensible position. **Open:** "to our knowledge" depends on the TODO novelty rescan.
|
||||
|
||||
**Writing clarity.** *Can an outsider follow it?* The main risks:
|
||||
- Method names are repository codes (`B3d-Sa`, `M2-Sa`, `B3c-R`). The macros `\mPM` and `\mRML` allow a rename in one place; descriptive names (e.g. *SMC-mean* and *SMC-bank*) would help readers. Not changed: this is a naming decision for the authors.
|
||||
- Section 4 (~3,900 words, 6 propositions, 4 corollaries) is dense for *Computers & Geosciences*.
|
||||
- There is no overview/pipeline figure (tie posterior → label bank → network, plus scoring against a reference). The skill treats this as first-impression content. Recommended.
|
||||
- Table `tab:t3` has 13 columns; consider moving the N* block to its own table.
|
||||
|
||||
**Experimental strength.** *Would the results survive a skeptical reader?*
|
||||
- One simulator, one backbone, σ_b never varied: all disclosed (Sec. 7), pending S2/S4 TODOs.
|
||||
- The σ_a arm ran only at R10. The abstract's "failed when the anchor uncertainty was set at half or twice its true value" is literally true but generalises from one regime; consider adding "(tested at high SNR)".
|
||||
- H1 verifies Prop. 1 only below about 23 Hz, while the bank-gain distortion sits at 67–72 Hz (Sec. 4.3). A reviewer will connect these. Worth one sentence in Sec. 4.3 or 6.3.
|
||||
|
||||
**Evaluation completeness.** *Is anything a reviewer would ask for missing?*
|
||||
- **Stale-text risk once T2 is written.** T2 is done (`docs/research/t2-results.md`: Berkson at c = 1; GP-noise bank gets most of the c = 1 gain; about a third of the PM–Oracle gap is training length). Sec. 6.4 is still a todoblock, so these passages now say the structure "was not tested" and must change together when 6.4 is written: abstract (bank sentence), Sec. 1 findings, Sec. 6.3 (end of the bound paragraphs and the gap paragraph), Sec. 7 "Where the bank gain comes from", Sec. 8 second paragraph.
|
||||
- No wall-clock cost of the SMC posterior is reported, although the discussion recommends the bank.
|
||||
|
||||
**Method design soundness.** *Is the design defensible?*
|
||||
- Experiment 2 was designed after Experiment 1 failed. It is disclosed as a deviation in Secs. 5, 6.2, 7 and 8, which is the right handling.
|
||||
- λ = 1/τ_c is a fixed heuristic and is disclosed as such.
|
||||
- Field gates use k-of-n rules that the paper itself shows are not tests. This is disclosed and turned into a finding, which is a strength.
|
||||
|
||||
## Not changed on purpose
|
||||
|
||||
- Every red TODO, including the title note and the S1–S8/T2 placeholders.
|
||||
- Length (about 14,950 words against about 5,500): the user dropped the length pass on 29/10 (`docs/plan.md` §12 item 25).
|
||||
- Appendices A and B: checked for terminology only, no edits.
|
||||
25
report.html
25
report.html
@@ -308,13 +308,13 @@ const PHASES = [
|
||||
{id:"P6", name:"P6 Benchmark mức B", start:"2026-11-01", end:"2026-11-10", weeks:"CN 1/11 – T3 10/11",
|
||||
out:"protocol_bench khoá trước khi chạy; lưới đầy; trục misspec; phân tích cơ chế; gói benchmark", gate:null,
|
||||
tasks:[
|
||||
{id:"p6-t2", t:"T2 cơ chế của lợi ích bank (exploratory, realization 8–15)", s:"todo", n:"CN 1/11. Khai báo trước ở docs/research/t2-mechanism.md. Câu hỏi (đổi ngày 29/10): còn lợi ích nào vượt hiệu chỉnh quần thể của cấu trúc Berkson không. Năm phép kiểm theo todoblock bài mục 6.4: (i) warp error có trọng số responsibility so với warp trung bình; (ii) bank nhiễu GP đối chứng; (iii) tách ô posterior đa mode; (iv) kiểm Berkson hay classical bằng hiệp phương sai của offset (quyết định cận nào áp dụng); (v) B3d-Sa huấn luyện lại với số vòng lặp của Oracle. Phải khai rằng tỉ số post hoc và cả hai cận (tại σ_post, tại sai số warp, biến thể 60 Hz và phổ chéo) đã được xem ngày 29/10. Không confirmatory (D-8)."},
|
||||
{id:"p6-gen", t:"Sửa generator cho S2 (misspec rock physics, wavelet, σ_b/drift); dev trên realization 902–905", s:"todo", n:"T2 2/11 – T3 3/11. Đường mặc định của D2 phải tái lập đúng P2r."},
|
||||
{id:"p6-lock", t:"Viết và khoá configs/protocol_bench.yaml (S1, S2, S3, S4, S8)", s:"todo", n:"T3 3/11, trước lần chạy chính đầu tiên; kèm .sha256 và .lock.json. Ghi rõ là thiết kế sau khi đã thấy P2r."},
|
||||
{id:"p6-s1", t:"S1: lấp lưới c ∈ {0.5, 1.5}, N ∈ {2, 8}", s:"todo", n:"T4 4/11 – T5 5/11, hai GPU."},
|
||||
{id:"p6-s3s4", t:"S3: B4 dưới posterior SMC; S4: backbone thứ hai", s:"todo", n:"T4 4/11 – T5 5/11."},
|
||||
{id:"p6-s2", t:"S2: ba trục misspec ở R10, Rm5, c = 1, N ∈ {4, 16}", s:"todo", n:"T6 6/11 – T7 7/11. Bắt buộc (D-7): thiếu S2 thì bài gọi là controlled synthetic study, không gọi là benchmark."},
|
||||
{id:"p6-s8", t:"S8/T8: regime cycle-skip có kiểm soát", s:"todo", n:"T7 7/11."},
|
||||
{id:"p6-t2", t:"T2 cơ chế của lợi ích bank (exploratory, realization 8–15)", s:"done", n:"Xong 29/10 (12:39–13:27 UTC; exploratory, realization 8–15). Khai báo băm trước mọi tính toán (f04e6607…), không sai lệch. Kiểm tái lập: huấn luyện lại khớp RMSE đã đăng ký, max |dev| = 0 trên 10.560 dòng. (i) warp trọng số responsibility thấp hơn warp trung bình ở 8/8 ô rộng (giảm 13–40 %): tái định vị ngầm có thật trên giếng train. (ii) bank nhiễu GP cùng hiệp phương sai đạt phần lớn lợi ích ở c = 1 (4/8 'phù hợp (a)', 3/8 'một phần', 1/8 'ngược'); thông tin của bank SMC cần ở c = 2. (iii) không có bằng chứng cho cơ chế đa mode theo luật chính. (iv) sai số nhãn của B3d-Sa là Berkson ở c = 1 (4/4 ô rộng) nên cận 1/B_b áp dụng; lợi ích H2b không vượt hiệu chỉnh quần thể. (v) khoảng một phần ba khoảng cách PM–Oracle ở c = 1 là do độ dài huấn luyện. Chi tiết: docs/research/t2-results.md, outputs/t2/summary.md. Không đổi H2a/H2b; không dùng để chọn lại budget."},
|
||||
{id:"p6-gen", t:"Sửa generator cho S2 (misspec rock physics, wavelet, σ_b/drift); dev trên realization 902–905", s:"done", n:"Xong sớm 29/10: tham số misspec trong synth_d2.py (rock_physics, wavelet, drift; misspec=None tái lập fingerprint P2r từng bit; 15 test mới), configs/d2_synth_bench.yaml (preset còn PLACEHOLDER), script 33 QC, docs/research/bench-generator.md. QC rid 902: rp_C bị likelihood α-profile hấp thụ hoàn toàn (chỉ làm đối chứng); wv_L1/L2 quá mạnh (model error 0.6 so với nhiễu R10 0.32). QC SMC rid 902 (cuda:1, 32 phút): đối chứng rp_C và wv_C đúng dự đoán; pha wavelet phụ thuộc tần số (minphase 1.0) là kiểu hỏng mạnh nhất và quá tự tin ở R10 (warp RMSE 4.2 ms, cov90 0.04, kém hơn tie chỉ anchor); rock physics phân tán theo đơn vị chỉ thấy ở R10; hai preset drift nhân đôi sai số ở R10 nhưng vẫn gần hiệu chỉnh. Mức chính chốt ở bước dev của p6-lock. T2 2/11 – T3 3/11. Đường mặc định của D2 phải tái lập đúng P2r."},
|
||||
{id:"p6-lock", t:"Viết và khoá configs/protocol_bench.yaml (S1, S2, S3, S4, S8)", s:"done", n:"Khoá 29/10 lúc 14:39 UTC (sha256 aa763f0a…; code_sha256 5ea2eb17…; 8 input, 102 artifact tham chiếu P2r, fingerprint danh nghĩa rid 8 và 902 khớp). Runner ml_porosity/benchmark/, scripts 34–35, scripts/run_bench.sh; 216 test pass. Tái lập ô P2r (R10, rid 8, c = 1, N = 4) qua runner: khớp từng bit. Mức S2 chốt trên dev 902–905: rock physics sd 0.10/0.15 theo đơn vị; wavelet minphase 0.5/1.0 và ô Q 80 riêng; drift hai cơ chế (siêu tham số sai; bước 8 ms + jitter 1 ms). rp_L1 (×1.24 nhiễu R10) và wv_L1 (×1.08) vượt dải L1 khai báo 0.5–1.0×, đã công bố trong protocol. Ở Rm5 khai báo trước kết quả null. Budget TCN chọn trên dev bằng luật protocol_p2: 125 vòng cho mọi phương pháp (nằm ở biên danh sách ứng viên, ghi rõ). Ô: S1 560 job SMC, S2 224, S3 240, S4 48, S8 96; thêm có công bố Ctl-GP và nhánh cùng budget 500. 9 claim khai báo trước, 11 verdict, không hiệu chỉnh family-wise, báo cáo mọi verdict. Thiết kế sau khi đã thấy P2r."},
|
||||
{id:"p6-s1", t:"S1: lấp lưới c ∈ {0.5, 1.5}, N ∈ {2, 8}", s:"doing", n:"Chạy 14:43–15:27 UTC 29/10 rồi bị SIGTERM khi phiên agent kết thúc (setsid nohup không đủ). Khi GPU trống lại, chạy lại 16:07 UTC trong tmux: p6_s1a (R10, Rm5, R0; cuda:0, 5 worker) và p6_s1b (R0h, R10tb; cuda:1, 2 worker); posterior rồi train; job đã xong được bỏ qua theo fingerprint."},
|
||||
{id:"p6-s3s4", t:"S3: B4 dưới posterior SMC; S4: backbone thứ hai", s:"doing", n:"Chạy từ 14:43 UTC 29/10; bị SIGTERM lúc 15:27 khi phiên agent kết thúc. Chạy lại trong tmux (p6_s348) trên cuda:0: 2 worker từ 15:41, tăng lên 4 worker lúc 16:07 UTC (26/384 job xong); chung job với S8; resume theo fingerprint. S4 dùng TCN, budget 125."},
|
||||
{id:"p6-s2", t:"S2: ba trục misspec ở R10, Rm5, c = 1, N ∈ {4, 16}", s:"doing", n:"Chạy từ 14:43 UTC 29/10; bị SIGTERM lúc 15:27 khi phiên agent kết thúc. Chạy lại trong tmux (p6_s2): cuda:0 2 worker từ 15:41, chuyển sang cuda:1 với 6 worker lúc 16:07 UTC khi GPU trống (17/224 job SMC xong). Bắt buộc (D-7): thiếu S2 thì bài gọi là controlled synthetic study, không gọi là benchmark."},
|
||||
{id:"p6-s8", t:"S8/T8: regime cycle-skip có kiểm soát", s:"doing", n:"Chạy lại trên cuda:0, chung job với S3, S4 (tmux p6_s348, 4 worker từ 16:07 UTC)."},
|
||||
{id:"p6-s7", t:"S7: đóng gói benchmark (một lệnh sinh, một lệnh chấm, bảng tham chiếu, README, hash, Zenodo)", s:"todo", n:"CN 8/11 – T3 10/11."},
|
||||
{id:"p6-write", t:"Viết lại các mục kết quả theo số liệu mới", s:"todo", n:"CN 8/11 – T3 10/11."}
|
||||
]},
|
||||
@@ -394,7 +394,8 @@ const FINDS = [
|
||||
{h:"Coverage: độ dài huấn luyện lẫn với nguồn nhãn (T4, post hoc)", p:"Mọi ensemble quá hẹp: tỉ số ξ = E s²/E(y − μ)² chỉ <b>0,19</b> ở Oracle và tối đa 0,66 (B5) ở R10, c = 1, N = 16. B3c-R học 500 vòng lặp như Oracle và đạt cùng ξ với B3d-Sa ở 250 vòng. Trên dev, coverage90 của Oracle đơn lẻ giảm 0,47 → 0,23 → 0,10 sau 125/500/2000 vòng. Phần (b), (c) của Mệnh đề 5 chưa kiểm; không claim hiệu chỉnh."},
|
||||
{h:"Reference ở giếng blind phải chính xác cỡ 1 ms (T3, exploratory)", p:"Chấm lại dự đoán P2r với reference lệch σ_ref: tỉ số band RMSE trung vị cắt 1 ở <b>3,6–4,3 ms</b> (Hệ quả 4 dự báo σ/√2 = 3,0/4,1/5,1 ms). Sign test α = 0,05 cần 5–18 giếng blind nếu reference chính xác (5/6 ô), 11–30 giếng ở 1 ms (4 ô); ở 2 ms chỉ R0 còn trong 40 giếng; từ 3 ms không ô nào. Luật k-of-n của G-C, G-D không phải phép kiểm: đạt ngẫu nhiên với xác suất 0,31 (n = 4) và 0,11 (n = 6)."},
|
||||
{h:"F3 và Volve trượt điều kiện C1; Teapot không có reference TD độc lập", p:"Hồi cứu (scripts/26): band PCC ở giếng blind 0,15 (F3) và 0,13/0,04 (Volve), dưới ngưỡng 0,47 suy từ D2; cả hai đạt C2 (σ_post trung vị 2,8 và 4,3 ms). Teapot Dome: 152 giếng có density trong survey 3-D nhưng tối đa <b>2</b> giếng có TD độc lập; knot horizon–top cho σ̂_knot <b>6,75 ms</b> (CI 90% 4,1–9,4) so với dung sai 1,5 ms (D-11)."},
|
||||
{h:"Bản thảo dài gấp khoảng 2,7 lần giới hạn của venue", p:"Thân bài (mục 1–8) khoảng <b>14.750</b> từ (đếm thô sau A6); giới hạn Research Article của Computers & Geosciences khoảng 5.500 từ theo nguồn thứ cấp, chưa kiểm trên trang chính thức. Người dùng bỏ lượt rút gọn (D-12); rủi ro vẫn mở."}
|
||||
{h:"Bản thảo dài gấp khoảng 2,7 lần giới hạn của venue", p:"Thân bài (mục 1–8) khoảng <b>14.750</b> từ (đếm thô sau A6); giới hạn Research Article của Computers & Geosciences khoảng 5.500 từ theo nguồn thứ cấp, chưa kiểm trên trang chính thức. Người dùng bỏ lượt rút gọn (D-12); rủi ro vẫn mở."},
|
||||
{h:"T2: lợi ích bank ở c = 1 chủ yếu là tăng cường nhãn, không phải thông tin của posterior", p:"Exploratory, khai báo trước. Sai số nhãn của B3d-Sa là <b>Berkson</b> ở c = 1, nên cận áp dụng là 1/B_b và lợi ích H2b không vượt hiệu chỉnh quần thể. Một bank nhiễu GP có cùng trung bình và hiệp phương sai với posterior (không thêm thông tin) đạt phần lớn lợi ích ở c = 1; bank SMC chỉ hơn rõ ở c = 2. RML có tái định vị ngầm (warp trọng số responsibility tốt hơn 13–40 % ở 8/8 ô rộng). Khoảng một phần ba khoảng cách PM–Oracle là độ dài huấn luyện."}
|
||||
];
|
||||
|
||||
const DATA = [
|
||||
@@ -541,6 +542,14 @@ const LOG = [
|
||||
["2026-10-29","Tự sửa hai nhận định của chính mình (plan §12 ý 24). (1) Câu \"hai cấu trúc sai số gần như cho cùng cận (hệ số < 1,17)\" sai: méo nằm ở 67–72 Hz, nơi tích phân Berkson gấp 1,5–4,6 lần ở σ = 1,5–2,5 ms. (2) Câu \"lợi ích của bank vượt cận quần thể\" chỉ đúng với cận classical đã đăng ký (7/8 ô). Với cận Berkson tính post hoc, chỉ 3/8 ô vượt (cả ba ở c = 1) và tối đa 1/8 tại sai số warp. scripts/31 viết lại để tính cận (a), (b), b60 và phổ chéo (đọc npz của Oracle, khoảng 6 phút; tái lập đúng số đã đăng ký). Đã sửa bài mục 4.3, 6.3 (cột 1/B_b ở Bảng tab:h2b), 6.4, 7, tóm tắt, mở bài, kết luận, cùng tài liệu. Câu hỏi của T2 đổi thành: còn lợi ích nào vượt hiệu chỉnh Berkson không. Bài build sạch, 55 trang; thân bài khoảng 14.750 từ (đếm thô), tóm tắt 292 từ. Chưa commit."],
|
||||
["2026-10-29","Người dùng bỏ lượt rút gọn độ dài cho venue (D-12, plan §12 ý 25). Thẻ p5-len thay bằng p5-cite (trích dẫn dataset F3, Volve; 30–31/10). Rủi ro độ dài (R9) vẫn ghi lại, chưa có biện pháp."],
|
||||
["2026-10-29","Commit và push lên main mọi thay đổi từ P4 đến A6 (code P4, configs/protocol_volve.*, scripts 26–31, docs/research, bản ghi P4x, bài và tài liệu), kèm tag protocol-volve. Hash code tính lại từ cây commit khớp configs/protocol_volve.lock.json. 190 test pass, 1 skip. logs/*.out vẫn không theo dõi như trước (plan §12 ý 25)."]
|
||||
["2026-10-29","P6 bắt đầu sớm. p6-gen xong (misspec cho generator D2, đường mặc định tái lập P2r từng bit, 15 test mới). T2 đã khai báo trước và đang chạy trên hai GPU. Bắt đầu dựng runner benchmark và nháp protocol_bench (chưa khoá). Từ 13:00 UTC một project khác giữ khoảng 125–128 GB mỗi H200, nên chỉ còn vài GB trống; không mở thêm worker."],
|
||||
["2026-10-29","T2 xong (exploratory, 12:39–13:27 UTC, hai GPU, không OOM): Berkson ở c = 1, cận 1/B_b áp dụng; bank nhiễu GP đạt phần lớn lợi ích c = 1; tái định vị ngầm có thật; không có bằng chứng cho cơ chế đa mode; một phần ba khoảng PM–Oracle là độ dài huấn luyện. Kết quả T2 không dùng để chọn lại budget."],
|
||||
["2026-10-29","Runner benchmark xong; tái lập ô P2r qua runner mới khớp từng bit. Mức misspec S2 chốt trên dev 902–905. Nháp protocol_bench đã rà soát; sửa các chỗ không nhất quán rồi khoá sau khi chọn budget TCN trên dev."],
|
||||
["2026-10-29","protocol_bench khoá lúc 14:39 UTC (sha256 aa763f0a…) sau 7 sửa theo rà soát; budget TCN 125 chọn trên dev. Chạy chính S1, S2, S3, S4, S8 khởi động 14:43 UTC trên cả hai GPU với ít worker (cuda:0 3, cuda:1 6) vì project khác giữ phần lớn bộ nhớ."],
|
||||
["2026-10-29","15:27 UTC: cả bốn driver chạy chính bị SIGTERM khi phiên agent kết thúc, dù đã tách bằng setsid nohup (đã xong 17 posterior S1, 11 posterior S2, 12 job train). 15:41 UTC: chạy lại S2 (2 worker) và S3+S4+S8 (2 worker) trên cuda:0 trong tmux server của người dùng; job đã xong được bỏ qua theo fingerprint. S1 chờ bộ nhớ: project khác giữ khoảng 136 GB ở cuda:0 và 142 GB ở cuda:1."],
|
||||
["2026-10-29","16:07 UTC: project khác đã trả GPU (cả hai card trống khoảng 138–143 GB). Bỏ watcher; chạy lại với 17 worker trong tmux: S2 cuda:1 6 worker, S1 nhóm A (R10, Rm5, R0) cuda:0 5 worker, S1 nhóm B (R0h, R10tb) cuda:1 2 worker, S3+S4+S8 cuda:0 4 worker. Giới hạn bởi 40 CPU (2 thread mỗi worker)."],
|
||||
["2026-10-29","16:22 UTC: thêm operations/p6_supervisor.py (tmux p6_supervisor) kiểm tra GPU mỗi 5 phút, tự chạy lại driver chết và dồn worker khi một study xong; tổng 17 worker. Job dùng chung GPU là job vinhnt của chính người dùng (khoảng 80 GB mỗi card)."],
|
||||
["2026-10-30","Lượt viết theo skill research-paper-writing (Master-cai/Research-Paper-Writing-Skills, cài ở ~/.claude/skills): câu chủ đề, tách đoạn nhiều ý, thuật ngữ (P2/P2r → Experiment 1/2 trong Sec. 5), hạ claim chưa đủ bằng chứng (H1 chỉ khớp 1% ở 4–16 ms; phần lớn lợi ích H2a có sẵn ở c = 0; H2b 8/8 chỉ ở N = 16). Không đổi số đăng ký, trích dẫn hay TODO đỏ nào; main.pdf 56 trang. Tự review: paper/self_review.md."]
|
||||
];
|
||||
/* ===================== HẾT DATA ===================== */
|
||||
|
||||
|
||||
846
scripts/32_t2_mechanism.py
Normal file
846
scripts/32_t2_mechanism.py
Normal file
@@ -0,0 +1,846 @@
|
||||
"""T2 (exploratory): mechanism of the bank gain on the P2r SMC bank (realizations 8–15).
|
||||
|
||||
Declared before any computation in docs/research/t2-mechanism.md (SHA-256 in docs/research/t2-mechanism.sha256; byte
|
||||
copy outputs/t2/declaration_v1.md). Everything under outputs/p2r/ is read-only here; nothing changes a registered
|
||||
number and no locked protocol is touched. Five tests (declaration §3):
|
||||
i responsibility-weighted warp error of M2-Sa at the end of training (λ of the protocol; λ ∈ {1, 3} as a declared
|
||||
diagnostic) against the uniform mean warp of the same 64-member bank (primary) and of all 1024 particles;
|
||||
ii control bank: 64 Gaussian-process warps with the particles' mean and covariance on the warp grid (no other
|
||||
information), trained like M2-Sa (RML, λ = 1/τ_c, uniform π, 250 iterations), scored on the test wells;
|
||||
iii posterior multimodality (2- vs 1-component Gaussian mixture of the per-particle window offset) and the
|
||||
M2-Sa/B3d-Sa ratio of multimodal vs unimodal (regime, c, rid) units, from the saved predictions;
|
||||
iv Berkson-vs-classical covariance test of the window offset of B3d-Sa and B3c-R (raw, and anchored to B3b);
|
||||
v B3d-Sa, M2-Sa and Oracle retrained with budgets [250, 500] on one trajectory.
|
||||
Stages (--tests): "i", "ii", "v" run the training stage (one job per cell-realization; 6 networks × 5 seeds on the
|
||||
GPU, with the training set rebuilt exactly as scripts/15 run_cell); "iii", "iv" run the particle stage (CPU, all 30
|
||||
cells); "summary" aggregates (tables, figures, reproduction check). A job is skipped when its output CSV exists.
|
||||
|
||||
scripts/runlog.sh -n t2_train -- scripts/32_t2_mechanism.py --tests i ii v --device cuda:0 --workers 4
|
||||
scripts/runlog.sh -n t2_particles -- scripts/32_t2_mechanism.py --tests iii iv --workers 4
|
||||
scripts/runlog.sh -n t2_summary -- scripts/32_t2_mechanism.py --tests summary
|
||||
→ outputs/t2/
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
|
||||
def load_script(name: str):
|
||||
spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
run_d2 = load_script("11_run_d2.py")
|
||||
sp13 = load_script("13_summarize_p2.py")
|
||||
|
||||
RIDS = list(range(8, 16))
|
||||
SEEDS = [0, 1, 2, 3, 4]
|
||||
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
|
||||
WIDE16 = [("R0", 1.0), ("R0h", 1.0), ("R10tb", 1.0), ("Rm5", 1.0), ("R0", 2.0), ("Rm5", 2.0), ("R0h", 2.0), ("R10tb", 2.0)]
|
||||
NARROW16 = [("R10", 0.0), ("R0", 0.0), ("Rm5", 0.0)]
|
||||
TRAIN_CELLS = [(r, c, 16) for r, c in WIDE16 + NARROW16]
|
||||
ALL_CELLS = [(r, c, n) for r in REGIMES for c in (0.0, 1.0, 2.0) for n in (4, 16)]
|
||||
LAM_DIAG = {"1": 1.0, "3": 3.0}
|
||||
B_PM, B_O = 250, 500
|
||||
MIN_SLOPE_MS, MAX_ATTEMPTS = 0.05, 1280
|
||||
MAIN_MS = (600.0, 1100.0)
|
||||
P2R = outputs_dir() / "p2r"
|
||||
N_BOOT = 2000
|
||||
TRAIN_METHODS = ["Oracle", "B3d-Sa", "M2-Sa", "M2-Sa@1", "M2-Sa@3", "Control"]
|
||||
REG_BUDGET = {"Oracle": 500, "B3d-Sa": 250, "M2-Sa": 250}
|
||||
|
||||
|
||||
def tag(regime: str, rid: int, c: float, N: int) -> str:
|
||||
return f"{regime}_r{rid}_c{c:g}_n{N}"
|
||||
|
||||
|
||||
def regime_settings() -> dict:
|
||||
reg = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_p2r.yaml").read_text())["regimes"]
|
||||
return {k: (v["snr_db"], v["anchor_density"]) for k, v in reg.items()}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# cell construction (as scripts/15 run_cell)
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def build_cell(regime: str, rid: int, c: float, N: int, P: dict, with_register: bool) -> dict:
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.models.bank_train import zscore_patch
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.smc import phase_basis, phase_wavelet
|
||||
from ml_porosity.registration.tie_likelihood import synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_mean
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
snr, dens = regime_settings()[regime]
|
||||
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
|
||||
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
|
||||
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
|
||||
sa = cfg["anchors"]["sigma_a_ms"]
|
||||
obs = [R.observe(w, c, snr, sa, dens) for w in R.pool[:N]]
|
||||
test = [R.observe(w, c, snr, sa) for w in R.test]
|
||||
reg = run_d2.reg_settings(P)
|
||||
post = P2R / "posterior" / regime
|
||||
t = f"r{rid}_c{c:g}_n{N}_s0"
|
||||
ph = json.loads((post / f"{t}_phase.json").read_text())
|
||||
smc = np.load(post / f"{t}_particles.npz")
|
||||
f, fac = cfg["fine_dt_ms"], int(round(R.dt / cfg["fine_dt_ms"]))
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"])
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
wells = []
|
||||
for i, o in enumerate(obs):
|
||||
y_aa = antialias(o["phi_log"], f, R.dt)
|
||||
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wR)[0]
|
||||
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
|
||||
Tg = R.grid.t_of_tau(U[:, 0], U[:, 1:]) # (P, n_grid), warp-grid nodes
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine) # (P, n_fine)
|
||||
tm = warp_mean(Tf, np.zeros(len(Tf))) # the B3d-Sa warp
|
||||
sub = np.random.default_rng([0, i, 29]).choice(len(Tf), reg["S"], replace=False)
|
||||
Y = lab(y_aa, Tf[sub])
|
||||
ok = np.all(np.isfinite(Y), 1)
|
||||
Y[~ok] = Y[ok][0]
|
||||
logpi = np.where(ok, 0.0, -np.inf) - np.log(ok.sum())
|
||||
tb_nodes = np.interp(R.grid.tau, R.tau_fine, t_b3b)
|
||||
K = np.flatnonzero((tb_nodes >= MAIN_MS[0]) & (tb_nodes <= MAIN_MS[1]))
|
||||
wells.append(dict(i=i, name=o["name"], o=o, y_aa=y_aa, t_b3b=t_b3b, t3c=t3c, U=U, Tg=Tg, Tf=Tf, tm=tm,
|
||||
sub=sub, Y=Y, ok=ok, logpi=logpi, K=K))
|
||||
cell = dict(R=R, obs=obs, test=test, reg=reg, ph=ph, wells=wells, lab=lab, snr=snr, dens=dens,
|
||||
X=np.stack([zscore_patch(o["seis"], R.main) for o in obs]),
|
||||
Xte=np.stack([zscore_patch(o["seis"], R.main) for o in test]),
|
||||
yt=100 * np.stack([o["y_true"] for o in test]))
|
||||
if with_register:
|
||||
from ml_porosity.registration.pipeline import register
|
||||
out = register(R, obs, reg, 0)
|
||||
if ph["phase0"] != out["phase"]:
|
||||
raise RuntimeError(f"{tag(regime, rid, c, N)}: register phase {out['phase']} differs from scripts/14 {ph['phase0']}")
|
||||
cell["out"] = out
|
||||
return cell
|
||||
|
||||
|
||||
def window_offsets(w: dict, R) -> dict:
|
||||
"""Window-mean offsets (ms) over the nodes K of the well: per particle (a_s) and per method; the node-wise
|
||||
offsets d_m(τ_k) = t_m(τ_k) − τ_k for the per-sample sensitivity of test iv."""
|
||||
K = w["K"]
|
||||
tau_k = R.grid.tau[K]
|
||||
at = lambda t: np.interp(tau_k, R.tau_fine, t) - tau_k
|
||||
d = {"true": at(w["o"]["t_of_tau_true"]), "B3b": at(w["t_b3b"]), "B3d-Sa": at(w["tm"]), "B3c-R": at(w["t3c"])}
|
||||
a_s = (w["Tg"][:, K] - tau_k[None, :]).mean(1)
|
||||
return {"nodes": d, "a_particles": a_s, "b_particles": w["U"][:, 0], "n_K": len(K),
|
||||
"a": {m: float(v.mean()) for m, v in d.items()}}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# training stage (tests i, ii, v)
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def control_bank(w: dict, R, S: int) -> tuple[np.ndarray, dict]:
|
||||
"""64 warps T̄ + η_s, η_s ~ GP with the particles' covariance on the warp grid (declaration §3 ii)."""
|
||||
Tg = w["Tg"]
|
||||
Tbar = Tg.mean(0)
|
||||
lam, V = np.linalg.eigh(np.cov(Tg.T, ddof=0))
|
||||
Lm = V * np.sqrt(np.clip(lam, 0.0, None))[None, :]
|
||||
rng = np.random.default_rng([0, w["i"], 2029])
|
||||
members, n_rej, attempts = [], 0, 0
|
||||
while len(members) < S and attempts < MAX_ATTEMPTS:
|
||||
t = Tbar + Lm @ rng.standard_normal(len(Tbar))
|
||||
attempts += 1
|
||||
if np.all(np.diff(t) > MIN_SLOPE_MS):
|
||||
members.append(t)
|
||||
else:
|
||||
n_rej += 1
|
||||
fallback = len(members) < S
|
||||
if fallback: # u-space Gaussian draw (monotone by construction)
|
||||
U = w["U"]
|
||||
lu, Vu = np.linalg.eigh(np.cov(U.T, ddof=0))
|
||||
Lu = Vu * np.sqrt(np.clip(lu, 0.0, None))[None, :]
|
||||
ubar = U.mean(0)
|
||||
while len(members) < S:
|
||||
u = ubar + Lu @ rng.standard_normal(len(ubar))
|
||||
members.append(R.grid.t_of_tau(u[0], u[1:])[0])
|
||||
Tc_grid = np.stack(members)
|
||||
Tc = np.stack([np.interp(R.tau_fine, R.grid.tau, t) for t in Tc_grid])
|
||||
K = w["K"]
|
||||
info = {"ctl_n_rejected": n_rej, "ctl_attempts": attempts, "ctl_fallback_u": bool(fallback),
|
||||
"ctl_sd_ratio": float(Tc_grid[:, K].std(0).mean() / Tg[:, K].std(0).mean()),
|
||||
"ctl_sd_mean_ms": float(Tc_grid[:, K].std(0).mean()), "post_sd_mean_ms": float(Tg[:, K].std(0).mean())}
|
||||
return Tc, info
|
||||
|
||||
|
||||
def member_errors(T: np.ndarray, R, o: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""τ_s(t) on t_main for every warp of T (NaN outside the domain), τ_true(t) and the per-member RMSE (ms)."""
|
||||
from ml_porosity.registration.labels import invert_warps
|
||||
|
||||
tau_s = invert_warps(T, R.tau_fine, R.t_main)
|
||||
tau_true = invert_warps(o["t_of_tau_true"][None], R.tau_fine, R.t_main)[0]
|
||||
e = np.sqrt(np.nanmean((tau_s - tau_true[None]) ** 2, 1))
|
||||
return tau_s, tau_true, e
|
||||
|
||||
|
||||
def train_job(job) -> tuple[str, float]:
|
||||
regime, rid, c, N, seeds, device, out_dir, P = job
|
||||
import torch
|
||||
|
||||
torch.set_num_threads(2)
|
||||
from ml_porosity.losses.rml import responsibilities
|
||||
from ml_porosity.models.bank_train import WIN, train_predict, window_starts_fixed
|
||||
from ml_porosity.registration.ties import warp_errors, warp_mean
|
||||
|
||||
t0 = time.time()
|
||||
cell = build_cell(regime, rid, c, N, P, with_register=True)
|
||||
R, out, wells = cell["R"], cell["out"], cell["wells"]
|
||||
stem = tag(regime, rid, c, N)
|
||||
key = dict(regime=regime, rid=rid, c=c, n_train=N)
|
||||
m0, s0 = out["norm"]
|
||||
lam = out["lam"]
|
||||
tcfg = P["training"]["model"] | P["training"]["optimizer"]
|
||||
f_c = P["metrics"]["bands"]["f_c_hz"]
|
||||
nb = lambda a: ((np.asarray(a) - m0) / s0).astype(np.float32)
|
||||
err = lambda t, o: warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
|
||||
# banks: Oracle (register), B3d-Sa, M2-Sa (SMC), Control (GP)
|
||||
spec_oracle = run_d2.method_specs(out, P, ["Oracle"])["Oracle"]
|
||||
Y_pm = nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells]))
|
||||
Y_rml = nb(np.stack([w["Y"] for w in wells]))
|
||||
logpi = np.stack([w["logpi"] for w in wells]).astype(np.float32)
|
||||
ctl_rows, Yc = [], []
|
||||
for w in wells:
|
||||
Tc, info = control_bank(w, R, cell["reg"]["S"])
|
||||
Y = cell["lab"](w["y_aa"], Tc)
|
||||
ok = np.all(np.isfinite(Y), 1)
|
||||
Y[~ok] = Y[ok][0]
|
||||
Yc.append(Y)
|
||||
_, _, e_ctl = member_errors(Tc, R, w["o"])
|
||||
_, _, e_smc = member_errors(w["Tf"][w["sub"]], R, w["o"])
|
||||
ctl_rows.append(key | {"well": w["name"], "lam": lam} | info | {
|
||||
"ctl_n_valid": int(ok.sum()), "ctl_mean_warp_rmse_ms": err(warp_mean(Tc, np.zeros(len(Tc))), w["o"]),
|
||||
"ctl_member_err_mean_ms": float(np.nanmean(e_ctl[ok])), "smc_member_err_mean_ms": float(np.nanmean(e_smc[w["ok"]])),
|
||||
"B3d-Sa_warp_rmse_ms": err(w["tm"], w["o"]), "M2-Sa_n_valid": int(w["ok"].sum())})
|
||||
w["ctl_logpi"] = np.where(ok, 0.0, -np.inf) - np.log(ok.sum())
|
||||
Y_ctl = nb(np.stack(Yc))
|
||||
logpi_ctl = np.stack([w["ctl_logpi"] for w in wells]).astype(np.float32)
|
||||
bank = lambda Y, lp, lam_: {"kind": "bank", "Y": Y, "logpi": lp, "lam": lam_}
|
||||
specs = {"Oracle": (spec_oracle, [B_PM, B_O]),
|
||||
"B3d-Sa": (bank(Y_pm, np.zeros((N, 1), np.float32), lam), [B_PM, B_O]),
|
||||
"M2-Sa": (bank(Y_rml, logpi, lam), [B_PM, B_O]),
|
||||
**{f"M2-Sa@{k}": (bank(Y_rml, logpi, v), [B_PM]) for k, v in LAM_DIAG.items()},
|
||||
"Control": (bank(Y_ctl, logpi_ctl, lam), [B_PM])}
|
||||
|
||||
# per-well warp quantities of test i (independent of the network)
|
||||
starts_np = window_starts_fixed(R.t_main.size)
|
||||
M = np.zeros((len(starts_np), R.t_main.size))
|
||||
for j, s in enumerate(starts_np):
|
||||
M[j, s: s + WIN] = 1.0
|
||||
cnt = M.sum(0)
|
||||
geo = []
|
||||
for w in wells:
|
||||
tau_s, tau_true, e_s = member_errors(w["Tf"][w["sub"]], R, w["o"])
|
||||
geo.append(dict(tau_s=np.nan_to_num(tau_s), tau_true=tau_true, e_s=e_s,
|
||||
E_64=err(warp_mean(w["Tf"][w["sub"]], w["logpi"]), w["o"]), E_1024=err(w["tm"], w["o"]),
|
||||
ebar_u=float(np.nanmean(e_s[w["ok"]]))))
|
||||
|
||||
T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
|
||||
X_t, starts_t = T(cell["X"]), torch.as_tensor(np.tile(starts_np, (N, 1)), device=device)
|
||||
rows, resp_rows = [], []
|
||||
for seed in seeds:
|
||||
for m, (sp, bud) in specs.items():
|
||||
store = {}
|
||||
cb = None
|
||||
if m.startswith("M2-Sa"):
|
||||
Y_t, lp_t = T(sp["Y"]), T(sp["logpi"])
|
||||
|
||||
def cb(step, model, Y_t=Y_t, lp_t=lp_t, lam_=sp["lam"], store=store):
|
||||
with torch.no_grad():
|
||||
mu, s = model(X_t)
|
||||
r = responsibilities(mu[:, 0], s[:, 0], Y_t, lp_t, starts_t, WIN, lam_)
|
||||
store[step] = r.cpu().numpy().astype(np.float64)
|
||||
preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, bud, device, on_budget=cb)
|
||||
for b, (mu, sg) in preds.items():
|
||||
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
|
||||
for wt, r in zip(R.test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)):
|
||||
rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": wt.name} | r)
|
||||
for b, r in store.items(): # (N, J, S)
|
||||
rbar = r.mean(1) # (N, S)
|
||||
r_i = np.einsum("ji,njs->nis", M, r) / cnt[None, :, None] # (N, L, S)
|
||||
for w, g in zip(wells, geo):
|
||||
rb, rs = rbar[w["i"]], r_i[w["i"]]
|
||||
with np.errstate(divide="ignore"):
|
||||
logw = np.log(rb)
|
||||
E_r = err(warp_mean(w["Tf"][w["sub"]], logw), w["o"])
|
||||
tau_r = np.einsum("is,si->i", rs, g["tau_s"])
|
||||
E_r_win = float(np.sqrt(np.mean((tau_r - g["tau_true"]) ** 2)))
|
||||
rj = r[w["i"]]
|
||||
resp_rows.append(key | {
|
||||
"seed": seed, "method": m, "lam": sp["lam"], "budget": b, "well": w["name"],
|
||||
"E_r": E_r, "E_r_win": E_r_win, "E_64": g["E_64"], "E_1024": g["E_1024"],
|
||||
"ebar_r": float(np.nansum(rb * np.nan_to_num(g["e_s"]))), "ebar_u": g["ebar_u"],
|
||||
"S_eff": float(1.0 / np.sum(rb ** 2)), "entropy": float(-np.sum(rb[rb > 0] * np.log(rb[rb > 0]))),
|
||||
"S_eff_win": float(np.mean(1.0 / np.sum(rj ** 2, 1))), "rmax_win": float(np.mean(rj.max(1))),
|
||||
"n_valid": int(w["ok"].sum())})
|
||||
pd.DataFrame(ctl_rows).to_csv(out_dir / f"{stem}_ctl.csv", index=False)
|
||||
pd.DataFrame(resp_rows).to_csv(out_dir / f"{stem}_resp.csv", index=False)
|
||||
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the job as complete
|
||||
return stem, time.time() - t0
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# particle stage (tests iii, iv)
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def gmm_stats(x: np.ndarray) -> dict:
|
||||
from sklearn.mixture import GaussianMixture
|
||||
|
||||
x = x[:, None]
|
||||
fit = lambda k: GaussianMixture(k, covariance_type="full", n_init=5, random_state=0, reg_covar=1e-6).fit(x)
|
||||
g1, g2 = fit(1), fit(2)
|
||||
mu = g2.means_.ravel()
|
||||
w = g2.weights_
|
||||
dbic = float(g1.bic(x) - g2.bic(x))
|
||||
sep = float(abs(mu[0] - mu[1]))
|
||||
return {"dbic": dbic, "sep_ms": sep, "w_min": float(w.min()), "sd_ms": float(x.std()),
|
||||
"multimodal": bool(dbic > 10 and sep > 4.0 and w.min() >= 0.1)}
|
||||
|
||||
|
||||
def particle_job(job) -> tuple[str, float]:
|
||||
regime, rid, c, N, out_dir, P = job
|
||||
t0 = time.time()
|
||||
cell = build_cell(regime, rid, c, N, P, with_register=False)
|
||||
R = cell["R"]
|
||||
stem = tag(regime, rid, c, N)
|
||||
key = dict(regime=regime, rid=rid, c=c, n_train=N)
|
||||
rows3, rows4, nodes = [], [], {}
|
||||
for w in cell["wells"]:
|
||||
off = window_offsets(w, R)
|
||||
ga, gb = gmm_stats(off["a_particles"]), gmm_stats(off["b_particles"])
|
||||
rows3.append(key | {"well": w["name"], "n_K": off["n_K"]} | {f"a_{k}": v for k, v in ga.items()}
|
||||
| {f"b_{k}": v for k, v in gb.items()})
|
||||
rows4.append(key | {"well": w["name"], "n_K": off["n_K"]} | {f"a_{m}": v for m, v in off["a"].items()})
|
||||
for m, v in off["nodes"].items():
|
||||
nodes[f"{w['name']}/{m}"] = v.astype(np.float32)
|
||||
np.savez_compressed(out_dir / "iv" / f"{stem}.npz", **nodes)
|
||||
pd.DataFrame(rows3).to_csv(out_dir / "iii" / f"{stem}.csv", index=False)
|
||||
pd.DataFrame(rows4).to_csv(out_dir / "iv" / f"{stem}.csv", index=False)
|
||||
return stem, time.time() - t0
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# summary
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def ci(rng, num: np.ndarray, den: np.ndarray | None = None) -> list[float]:
|
||||
return sp13.boot(np.asarray(num, float), None if den is None else np.asarray(den, float), N_BOOT, rng)
|
||||
|
||||
|
||||
def per_rid(df: pd.DataFrame, col: str = "band_rmse") -> pd.Series:
|
||||
"""Mean over seeds and test wells per realization (index: rid)."""
|
||||
return df.groupby("rid")[col].mean()
|
||||
|
||||
|
||||
def registered_cells(cells: list[tuple[str, float, int]]) -> pd.DataFrame:
|
||||
rows = []
|
||||
for regime, c, N in cells:
|
||||
for rid in RIDS:
|
||||
f = P2R / "train" / regime / "cells" / f"r{rid}_c{c:g}_n{N}.csv"
|
||||
d = pd.read_csv(f)
|
||||
d = d[d.budget == d.method.map(REG_BUDGET).fillna(-1)]
|
||||
rows.append(d.assign(regime=regime))
|
||||
return pd.concat(rows, ignore_index=True)
|
||||
|
||||
|
||||
def ratio_row(rng, num: pd.DataFrame, den: pd.DataFrame, col: str = "band_rmse") -> dict:
|
||||
a, b = per_rid(num, col), per_rid(den, col)
|
||||
a, b = a.align(b, join="inner")
|
||||
lo, hi = ci(rng, a.to_numpy(), b.to_numpy())
|
||||
return {"ratio": float(a.mean() / b.mean()), "lo": lo, "hi": hi, "n_rid": int(len(a))}
|
||||
|
||||
|
||||
def diff_row(rng, num: pd.DataFrame, den: pd.DataFrame, col: str = "band_rmse") -> dict:
|
||||
a, b = per_rid(num, col), per_rid(den, col)
|
||||
a, b = a.align(b, join="inner")
|
||||
d = (a - b).to_numpy()
|
||||
lo, hi = ci(rng, d)
|
||||
return {"diff": float(d.mean()), "diff_lo": lo, "diff_hi": hi}
|
||||
|
||||
|
||||
def cluster_corr(rng, df: pd.DataFrame, x: str, y: str) -> dict:
|
||||
"""Pearson correlation with a cluster bootstrap over realizations (declaration §3 iv)."""
|
||||
r = float(np.corrcoef(df[x], df[y])[0, 1]) if len(df) > 2 else np.nan
|
||||
rids = df.rid.unique()
|
||||
groups = {k: g[[x, y]].to_numpy() for k, g in df.groupby("rid")}
|
||||
boots = []
|
||||
for _ in range(N_BOOT):
|
||||
pick = rng.choice(rids, len(rids), replace=True)
|
||||
v = np.concatenate([groups[k] for k in pick])
|
||||
boots.append(np.corrcoef(v[:, 0], v[:, 1])[0, 1] if v[:, 0].std() > 0 and v[:, 1].std() > 0 else np.nan)
|
||||
lo, hi = np.nanpercentile(boots, [2.5, 97.5])
|
||||
return {"r": r, "lo": float(lo), "hi": float(hi), "n": int(len(df))}
|
||||
|
||||
|
||||
def verdict_iv(rB: dict, rC: dict) -> str:
|
||||
b0, c0 = rB["lo"] <= 0 <= rB["hi"], rC["lo"] <= 0 <= rC["hi"]
|
||||
if b0 and not c0:
|
||||
return "Berkson"
|
||||
if c0 and not b0:
|
||||
return "classical"
|
||||
return "neither (no power)" if b0 and c0 else "neither (no structure)"
|
||||
|
||||
|
||||
def summarize(out: Path, device_note: str) -> None:
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
from ml_porosity.eval import figstyle
|
||||
|
||||
figstyle.apply()
|
||||
fig_dir = out / "figures"
|
||||
fig_dir.mkdir(exist_ok=True)
|
||||
rng = np.random.default_rng(0)
|
||||
meta = {"declaration_sha256": (REPO_ROOT / "docs/research/t2-mechanism.sha256").read_text().strip().splitlines(),
|
||||
"n_boot": N_BOOT, "device": device_note}
|
||||
md = ["# T2 (exploratory): summary of outputs/t2\n",
|
||||
"Declared in docs/research/t2-mechanism.md before any computation; nothing here changes a registered number.\n"]
|
||||
|
||||
# ---------------------------------------------------------------- training outputs and reproduction check
|
||||
cell_files = sorted(f for f in (out / "cells").glob("*_n16.csv") if not f.name.endswith(("_ctl.csv", "_resp.csv")))
|
||||
have_train = len(cell_files) > 0
|
||||
if have_train:
|
||||
tr = pd.concat([pd.read_csv(f) for f in cell_files], ignore_index=True)
|
||||
done = sorted({(r, c, 16) for r, c in tr[["regime", "c"]].drop_duplicates().itertuples(index=False)})
|
||||
reg = registered_cells(done)
|
||||
# reproduction: retrained at the registered budget vs registered, per (cell, rid, seed, test_well)
|
||||
rep = tr[tr.method.isin(REG_BUDGET) & (tr.budget == tr.method.map(REG_BUDGET))]
|
||||
keys = ["regime", "c", "rid", "seed", "method", "test_well"]
|
||||
mg = rep.merge(reg[keys + ["band_rmse", "rmse"]], on=keys, suffixes=("", "_reg"))
|
||||
mg["dev"] = (mg.band_rmse - mg.band_rmse_reg).abs()
|
||||
sc = {"n_rows": int(len(mg)), "band_rmse_abs_dev_max": float(mg.dev.max()), "band_rmse_abs_dev_mean": float(mg.dev.mean()),
|
||||
"band_rmse_abs_dev_median": float(mg.dev.median()),
|
||||
"by_method": {m: {"max": float(d.dev.max()), "mean": float(d.dev.mean())} for m, d in mg.groupby("method")}}
|
||||
one = mg[(mg.regime == "R0") & (mg.c == 1.0) & (mg.rid == 8) & (mg.seed == 0)]
|
||||
sc["R0_r8_c1_n16_seed0"] = {m: {"max_abs_dev": float(d.dev.max()), "band_rmse_retrained": float(d.band_rmse.mean()),
|
||||
"band_rmse_registered": float(d.band_rmse_reg.mean())} for m, d in one.groupby("method")}
|
||||
# cell-level: retrained vs registered cell means
|
||||
cm = mg.groupby(["regime", "c", "method"])[["band_rmse", "band_rmse_reg"]].mean()
|
||||
sc["cell_mean_rel_dev_max"] = float(((cm.band_rmse - cm.band_rmse_reg) / cm.band_rmse_reg).abs().max())
|
||||
# warp diagnostics vs registered _diag.csv
|
||||
ctl = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_ctl.csv"))], ignore_index=True)
|
||||
dg = []
|
||||
for regime, c, N in done:
|
||||
for rid in RIDS:
|
||||
d = pd.read_csv(P2R / "train" / regime / "cells" / f"r{rid}_c{c:g}_n{N}_diag.csv")
|
||||
dg.append(d.assign(regime=regime))
|
||||
dg = pd.concat(dg, ignore_index=True)
|
||||
wd = ctl.merge(dg[["regime", "c", "rid", "well", "B3d-Sa_warp_rmse_ms", "M2-Sa_n_valid", "lam"]],
|
||||
on=["regime", "c", "rid", "well"], suffixes=("", "_diag"))
|
||||
sc["warp_rmse_abs_dev_max"] = float((wd["B3d-Sa_warp_rmse_ms"] - wd["B3d-Sa_warp_rmse_ms_diag"]).abs().max())
|
||||
sc["n_valid_mismatch"] = int((wd["M2-Sa_n_valid"] != wd["M2-Sa_n_valid_diag"]).sum())
|
||||
sc["lam_abs_dev_max"] = float((wd["lam"] - wd["lam_diag"]).abs().max())
|
||||
(out / "selfcheck.json").write_text(json.dumps(sc, indent=1))
|
||||
meta["selfcheck"] = sc
|
||||
md.append("## Reproduction check (retrained vs registered band RMSE per seed and test well)\n")
|
||||
md.append(f"rows {sc['n_rows']}; max |dev| {sc['band_rmse_abs_dev_max']:.3e}, mean {sc['band_rmse_abs_dev_mean']:.3e}, "
|
||||
f"median {sc['band_rmse_abs_dev_median']:.3e}; cell-mean relative dev max {sc['cell_mean_rel_dev_max']:.3e}; "
|
||||
f"warp RMSE max dev {sc['warp_rmse_abs_dev_max']:.1e} ms; n_valid mismatches {sc['n_valid_mismatch']}; "
|
||||
f"lambda max dev {sc['lam_abs_dev_max']:.1e}\n")
|
||||
md.append("R0 r8 c1 n16 seed 0: " + "; ".join(f"{m}: max |dev| {v['max_abs_dev']:.3e}" for m, v in sc["R0_r8_c1_n16_seed0"].items()) + "\n")
|
||||
|
||||
# ---------------------------------------------------------------- test ii
|
||||
rows = []
|
||||
for regime, c, N in done:
|
||||
cell = dict(regime=regime, c=c, n_train=N, wide=(regime, c) in WIDE16)
|
||||
sel = lambda df, m, b: df[(df.regime == regime) & (df.c == c) & (df.method == m) & (df.budget == b)]
|
||||
ctl_df, pm_reg, rml_reg = sel(tr, "Control", B_PM), sel(reg, "B3d-Sa", B_PM), sel(reg, "M2-Sa", B_PM)
|
||||
pm_new, rml_new = sel(tr, "B3d-Sa", B_PM), sel(tr, "M2-Sa", B_PM)
|
||||
r = cell | {f"ctl_pm_{k}": v for k, v in ratio_row(rng, ctl_df, pm_reg).items()}
|
||||
r |= {f"rml_pm_{k}": v for k, v in ratio_row(rng, rml_reg, pm_reg).items()}
|
||||
r |= {f"ctl_rml_{k}": v for k, v in ratio_row(rng, ctl_df, rml_reg).items()}
|
||||
r |= {f"ctl_pm_new_{k}": v for k, v in ratio_row(rng, ctl_df, pm_new).items()}
|
||||
r |= {f"rml_pm_new_{k}": v for k, v in ratio_row(rng, rml_new, pm_new).items()}
|
||||
r |= {f"ctl_rml_new_{k}": v for k, v in ratio_row(rng, ctl_df, rml_new).items()}
|
||||
r |= {f"D_ctl_rml_{k}": v for k, v in diff_row(rng, ctl_df, rml_reg).items()}
|
||||
r |= {f"ctl_pm_pcc_{k}": v for k, v in ratio_row(rng, ctl_df, pm_reg, "band_pcc").items()}
|
||||
cd = ctl[(ctl.regime == regime) & (ctl.c == c)]
|
||||
r |= {"ctl_sd_ratio": float(cd.ctl_sd_ratio.mean()), "ctl_rejected_total": int(cd.ctl_n_rejected.sum()),
|
||||
"ctl_fallback_wells": int(cd.ctl_fallback_u.sum()), "ctl_member_err_ms": float(cd.ctl_member_err_mean_ms.mean()),
|
||||
"smc_member_err_ms": float(cd.smc_member_err_mean_ms.mean()), "ctl_mean_warp_rmse_ms": float(cd.ctl_mean_warp_rmse_ms.mean()),
|
||||
"pm_warp_rmse_ms": float(cd["B3d-Sa_warp_rmse_ms"].mean())}
|
||||
ctl_gain, ctl_null = r["ctl_pm_hi"] < 1, r["ctl_pm_lo"] <= 1 <= r["ctl_pm_hi"]
|
||||
rml_gain = r["rml_pm_hi"] < 1
|
||||
d0, dpos = r["D_ctl_rml_diff_lo"] <= 0 <= r["D_ctl_rml_diff_hi"], r["D_ctl_rml_diff_lo"] > 0
|
||||
if ctl_gain and d0:
|
||||
v = "A: consistent with (a)"
|
||||
elif ctl_null and rml_gain:
|
||||
v = "B: against (a)"
|
||||
elif ctl_gain and dpos:
|
||||
v = "C: partial (a)"
|
||||
else:
|
||||
v = "D: undetermined"
|
||||
r["verdict"] = v
|
||||
rows.append(r)
|
||||
t2 = pd.DataFrame(rows)
|
||||
t2.to_csv(out / "test_ii.csv", index=False)
|
||||
wide = t2[t2.wide]
|
||||
meta["test_ii"] = {"verdict_counts_wide": wide.verdict.value_counts().to_dict(),
|
||||
"narrow_ctl_pm": t2[~t2.wide][["regime", "ctl_pm_ratio", "ctl_pm_lo", "ctl_pm_hi"]].to_dict("records")}
|
||||
md.append("## Test ii: control bank (GP noise with the posterior covariance) vs B3d-Sa and M2-Sa\n")
|
||||
md.append(sp13.md(t2[["regime", "c", "wide", "ctl_pm_ratio", "ctl_pm_lo", "ctl_pm_hi", "rml_pm_ratio", "rml_pm_lo", "rml_pm_hi",
|
||||
"ctl_rml_ratio", "ctl_rml_lo", "ctl_rml_hi", "D_ctl_rml_diff", "D_ctl_rml_diff_lo", "D_ctl_rml_diff_hi",
|
||||
"ctl_pm_new_ratio", "ctl_sd_ratio", "ctl_member_err_ms", "smc_member_err_ms", "ctl_fallback_wells", "verdict"]]) + "\n")
|
||||
md.append(f"Wide-cell verdicts: {meta['test_ii']['verdict_counts_wide']}\n")
|
||||
|
||||
# ---------------------------------------------------------------- test v
|
||||
rows = []
|
||||
for regime, c, N in done:
|
||||
cell = dict(regime=regime, c=c, n_train=N, wide=(regime, c) in WIDE16)
|
||||
sel = lambda df, m, b: df[(df.regime == regime) & (df.c == c) & (df.method == m) & (df.budget == b)]
|
||||
pairs = {"o500_pm500": (sel(tr, "Oracle", B_O), sel(tr, "B3d-Sa", B_O)),
|
||||
"pm500_pm250": (sel(tr, "B3d-Sa", B_O), sel(tr, "B3d-Sa", B_PM)),
|
||||
"pm500_pm250reg": (sel(tr, "B3d-Sa", B_O), sel(reg, "B3d-Sa", B_PM)),
|
||||
"rml500_pm500": (sel(tr, "M2-Sa", B_O), sel(tr, "B3d-Sa", B_O)),
|
||||
"rml500_rml250": (sel(tr, "M2-Sa", B_O), sel(tr, "M2-Sa", B_PM)),
|
||||
"o250_pm250": (sel(tr, "Oracle", B_PM), sel(tr, "B3d-Sa", B_PM)),
|
||||
"o500_o250": (sel(tr, "Oracle", B_O), sel(tr, "Oracle", B_PM)),
|
||||
"rml250_pm250": (sel(tr, "M2-Sa", B_PM), sel(tr, "B3d-Sa", B_PM)),
|
||||
"o500_pm250": (sel(tr, "Oracle", B_O), sel(tr, "B3d-Sa", B_PM)),
|
||||
"o500_pm250reg": (sel(reg, "Oracle", B_O), sel(reg, "B3d-Sa", B_PM)),
|
||||
"rml250_pm250reg": (sel(reg, "M2-Sa", B_PM), sel(reg, "B3d-Sa", B_PM))}
|
||||
r = dict(cell)
|
||||
for k, (a, b) in pairs.items():
|
||||
r |= {f"{k}_{kk}": v for kk, v in ratio_row(rng, a, b).items() if kk != "n_rid"}
|
||||
r[f"{k}_pcc"] = ratio_row(rng, a, b, "band_pcc")["ratio"]
|
||||
g500, g250 = 1 - r["o500_pm500_ratio"], 1 - r["o500_pm250_ratio"]
|
||||
r["gap_share_training_length"] = float(1 - g500 / g250) if g250 > 0 and g500 > 0 else np.nan
|
||||
rows.append(r)
|
||||
t5 = pd.DataFrame(rows)
|
||||
t5.to_csv(out / "test_v.csv", index=False)
|
||||
md.append("## Test v: retrained with budgets [250, 500] (ratios of cell-mean band RMSE; CI over realizations)\n")
|
||||
md.append(sp13.md(t5[["regime", "c", "wide", "o500_pm500_ratio", "o500_pm500_lo", "o500_pm500_hi", "pm500_pm250_ratio", "pm500_pm250_lo",
|
||||
"pm500_pm250_hi", "rml500_pm500_ratio", "rml500_pm500_lo", "rml500_pm500_hi", "o250_pm250_ratio", "o250_pm250_lo",
|
||||
"o250_pm250_hi", "rml250_pm250_ratio", "rml250_pm250reg_ratio", "o500_pm250_ratio", "o500_pm250reg_ratio",
|
||||
"gap_share_training_length"]]) + "\n")
|
||||
|
||||
# ---------------------------------------------------------------- test i
|
||||
rs = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_resp.csv"))], ignore_index=True)
|
||||
rs["d_r"] = rs.E_r - rs.E_64
|
||||
rs["d_r1024"] = rs.E_r - rs.E_1024
|
||||
rs["d_win"] = rs.E_r_win - rs.E_64
|
||||
rs["d_e"] = rs.ebar_r - rs.ebar_u
|
||||
rows = []
|
||||
for (regime, c, m, b), d in rs.groupby(["regime", "c", "method", "budget"]):
|
||||
r = dict(regime=regime, c=c, n_train=16, wide=(regime, c) in WIDE16, method=m, lam=float(d.lam.iloc[0]), budget=b,
|
||||
n_units=int(len(d)))
|
||||
for q in ["d_r", "d_r1024", "d_win", "d_e"]:
|
||||
pr = d.groupby("rid")[q].mean().to_numpy()
|
||||
lo, hi = ci(rng, pr)
|
||||
r |= {q: float(pr.mean()), f"{q}_lo": lo, f"{q}_hi": hi, f"share_{q}_neg": float((d[q] < 0).mean())}
|
||||
r |= {k: float(d[k].mean()) for k in ["E_r", "E_r_win", "E_64", "E_1024", "ebar_r", "ebar_u", "S_eff", "entropy", "S_eff_win", "rmax_win"]}
|
||||
r["cell_c"] = bool(r["share_d_r_neg"] > 0.5 and r["d_r_hi"] < 0)
|
||||
rows.append(r)
|
||||
t1 = pd.DataFrame(rows)
|
||||
t1.to_csv(out / "test_i.csv", index=False)
|
||||
v1 = {}
|
||||
for m, d in t1[t1.wide & (t1.budget == B_PM)].groupby("method"):
|
||||
v1[m] = {"cells_with_c": int(d.cell_c.sum()), "n_wide_cells": int(len(d)), "evidence_for_c": bool(d.cell_c.sum() >= 5)}
|
||||
meta["test_i"] = v1
|
||||
md.append("## Test i: responsibility-weighted warp error (ms) vs the uniform mean warp of the same 64 members\n")
|
||||
md.append(sp13.md(t1[t1.budget == B_PM][["regime", "c", "wide", "method", "lam", "E_r", "E_64", "E_1024", "E_r_win", "d_r", "d_r_lo", "d_r_hi",
|
||||
"share_d_r_neg", "d_r1024", "d_win", "d_e", "d_e_lo", "d_e_hi", "S_eff", "entropy", "S_eff_win",
|
||||
"rmax_win", "cell_c"]]) + "\n")
|
||||
md.append(f"Wide cells with (c) at budget 250: {v1}\n")
|
||||
if (t1.budget == B_O).any():
|
||||
md.append("M2-Sa at 500 iterations (descriptive):\n" + sp13.md(t1[t1.budget == B_O][["regime", "c", "d_r", "d_r_lo", "d_r_hi", "S_eff", "entropy"]]) + "\n")
|
||||
|
||||
# figures i, ii, v
|
||||
fig, axes = plt.subplots(1, 3, figsize=(11, 3.4))
|
||||
lab_cells = [f"{r} c={c:g}" for r, c in WIDE16 + NARROW16]
|
||||
for ax, (m, title) in zip(axes, [("M2-Sa", "λ = 1/τ_c (protocol)"), ("M2-Sa@1", "λ = 1"), ("M2-Sa@3", "λ = 3")]):
|
||||
d = t1[(t1.method == m) & (t1.budget == B_PM)].set_index(t1[(t1.method == m) & (t1.budget == B_PM)].apply(lambda r: f"{r.regime} c={r.c:g}", axis=1))
|
||||
d = d.reindex([k for k in lab_cells if k in d.index])
|
||||
y = np.arange(len(d))
|
||||
ax.errorbar(d.d_r, y, xerr=[d.d_r - d.d_r_lo, d.d_r_hi - d.d_r], fmt="o", color=figstyle.BLUE, label="E_r − E_64")
|
||||
ax.errorbar(d.d_r1024, y + 0.25, xerr=0, fmt="s", color=figstyle.ORANGE, ms=3, label="E_r − E_1024")
|
||||
ax.axvline(0, color=figstyle.AXIS, lw=0.8)
|
||||
ax.set_yticks(y)
|
||||
ax.set_yticklabels(d.index, fontsize=7)
|
||||
ax.set_title(title)
|
||||
ax.set_xlabel("warp error difference (ms)")
|
||||
axes[0].legend(loc="lower left")
|
||||
fig.suptitle("Test i: responsibility-weighted warp vs uniform mean warp (95% CI over realizations)", fontsize=9)
|
||||
fig.tight_layout()
|
||||
fig.savefig(fig_dir / "t2_i_responsibility.pdf")
|
||||
plt.close(fig)
|
||||
|
||||
fig, ax = plt.subplots(figsize=(6.5, 3.6))
|
||||
d = t2.set_index(t2.apply(lambda r: f"{r.regime} c={r.c:g}", axis=1)).reindex(lab_cells)
|
||||
x = np.arange(len(d))
|
||||
ax.errorbar(x - 0.15, d.rml_pm_ratio, yerr=[d.rml_pm_ratio - d.rml_pm_lo, d.rml_pm_hi - d.rml_pm_ratio], fmt="o", color=figstyle.BLUE, label="M2-Sa / B3d-Sa (registered)")
|
||||
ax.errorbar(x + 0.15, d.ctl_pm_ratio, yerr=[d.ctl_pm_ratio - d.ctl_pm_lo, d.ctl_pm_hi - d.ctl_pm_ratio], fmt="s", color=figstyle.ORANGE, label="Control bank / B3d-Sa")
|
||||
ax.axhline(1, color=figstyle.AXIS, lw=0.8)
|
||||
ax.set_xticks(x)
|
||||
ax.set_xticklabels(d.index, rotation=45, ha="right", fontsize=7)
|
||||
ax.set_ylabel("band RMSE ratio")
|
||||
ax.set_title("Test ii: GP-noise control bank (N = 16; 95% CI over realizations)")
|
||||
ax.legend()
|
||||
fig.tight_layout()
|
||||
fig.savefig(fig_dir / "t2_ii_control.pdf")
|
||||
plt.close(fig)
|
||||
|
||||
fig, ax = plt.subplots(figsize=(6.5, 3.6))
|
||||
d = t5.set_index(t5.apply(lambda r: f"{r.regime} c={r.c:g}", axis=1)).reindex(lab_cells)
|
||||
for k, off, col, lab, mk in [("o500_pm250", -0.2, figstyle.BLUE, "Oracle(500) / B3d-Sa(250)", "o"), ("o500_pm500", 0.0, figstyle.ORANGE, "Oracle(500) / B3d-Sa(500)", "s"),
|
||||
("rml500_pm500", 0.2, figstyle.AQUA, "M2-Sa(500) / B3d-Sa(500)", "^")]:
|
||||
ax.errorbar(x + off, d[f"{k}_ratio"], yerr=[d[f"{k}_ratio"] - d[f"{k}_lo"], d[f"{k}_hi"] - d[f"{k}_ratio"]], fmt=mk, color=col, label=lab, ms=4)
|
||||
ax.axhline(1, color=figstyle.AXIS, lw=0.8)
|
||||
ax.set_xticks(x)
|
||||
ax.set_xticklabels(d.index, rotation=45, ha="right", fontsize=7)
|
||||
ax.set_ylabel("band RMSE ratio")
|
||||
ax.set_title("Test v: training length vs label error (retrained; 95% CI over realizations)")
|
||||
ax.legend(fontsize=7)
|
||||
fig.tight_layout()
|
||||
fig.savefig(fig_dir / "t2_v_budget.pdf")
|
||||
plt.close(fig)
|
||||
|
||||
# ---------------------------------------------------------------- test iii
|
||||
f3 = sorted((out / "iii").glob("*.csv"))
|
||||
if f3:
|
||||
m3 = pd.concat([pd.read_csv(f) for f in f3], ignore_index=True)
|
||||
share = m3.groupby(["regime", "c", "n_train", "rid"]).agg(m_u=("a_multimodal", "mean"), m_u_b=("b_multimodal", "mean"),
|
||||
sd_a_ms=("a_sd_ms", "mean"), n_wells=("well", "size")).reset_index()
|
||||
share.to_csv(out / "test_iii_units.csv", index=False)
|
||||
cell_share = share.groupby(["regime", "c", "n_train"]).agg(m_u=("m_u", "mean"), m_u_b=("m_u_b", "mean"), units_multimodal=("m_u", lambda s: int((s >= 0.25).sum())),
|
||||
units_any=("m_u", lambda s: int((s > 0).sum())), sd_a_ms=("sd_a_ms", "mean")).reset_index()
|
||||
rows, groups = [], None
|
||||
if have_train:
|
||||
reg_w = registered_cells([(r, c, 16) for r, c in WIDE16])
|
||||
u = reg_w[reg_w.method.isin(["M2-Sa", "B3d-Sa"])].groupby(["regime", "c", "rid", "method"]).band_rmse.mean().unstack("method")
|
||||
u["log_ratio"] = np.log(u["M2-Sa"] / u["B3d-Sa"])
|
||||
u = u.reset_index().merge(share[share.n_train == 16], on=["regime", "c", "rid"])
|
||||
u.to_csv(out / "test_iii_wide_units.csv", index=False)
|
||||
|
||||
def D_stats(u, thr):
|
||||
u = u.assign(grp=(u.m_u >= thr) if thr > 0 else (u.m_u > 0))
|
||||
g1, g0 = u[u.grp], u[~u.grp]
|
||||
res = {"n_multi": int(len(g1)), "n_uni": int(len(g0)),
|
||||
"D_unadj": float(g1.log_ratio.mean() - g0.log_ratio.mean()) if len(g1) and len(g0) else np.nan}
|
||||
both = [k for k, d in u.groupby(["regime", "c"]) if d.grp.any() and (~d.grp).any()]
|
||||
res["cells_with_both_groups"] = len(both)
|
||||
|
||||
def adj(u):
|
||||
num = den = 0.0
|
||||
for k, d in u.groupby(["regime", "c"]):
|
||||
a, b = d[d.grp], d[~d.grp]
|
||||
if len(a) and len(b):
|
||||
w = len(a) * len(b) / (len(a) + len(b))
|
||||
num += w * (a.log_ratio.mean() - b.log_ratio.mean())
|
||||
den += w
|
||||
return num / den if den > 0 else np.nan
|
||||
|
||||
res["D_adj"] = float(adj(u))
|
||||
boots_u, boots_a = [], []
|
||||
for _ in range(N_BOOT):
|
||||
ub = pd.concat([d.iloc[rng.integers(0, len(d), len(d))] for _, d in u.groupby(["regime", "c"])])
|
||||
a1, a0 = ub[ub.grp], ub[~ub.grp]
|
||||
boots_u.append(a1.log_ratio.mean() - a0.log_ratio.mean() if len(a1) and len(a0) else np.nan)
|
||||
boots_a.append(adj(ub))
|
||||
res["D_unadj_lo"], res["D_unadj_hi"] = [float(v) for v in np.nanpercentile(boots_u, [2.5, 97.5])] if np.isfinite(boots_u).any() else (np.nan, np.nan)
|
||||
res["D_adj_lo"], res["D_adj_hi"] = [float(v) for v in np.nanpercentile(boots_a, [2.5, 97.5])] if np.isfinite(boots_a).any() else (np.nan, np.nan)
|
||||
from scipy import stats
|
||||
res["spearman_mu_logratio"] = float(stats.spearmanr(u.m_u, u.log_ratio)[0]) if u.m_u.std() > 0 else np.nan
|
||||
if np.isnan(res["D_adj"]):
|
||||
res["verdict"] = "confounded with cell (no cell has both groups)" if res["n_multi"] else "no multimodal unit: (b) not testable"
|
||||
elif res["D_adj_hi"] < 0:
|
||||
res["verdict"] = "evidence for (b)"
|
||||
else:
|
||||
res["verdict"] = "no evidence for (b)"
|
||||
return res
|
||||
|
||||
groups = {"thr0.25": D_stats(u, 0.25), "any": D_stats(u, 0.0)}
|
||||
within = [{"regime": k[0], "c": k[1], "spearman": float(__import__("scipy").stats.spearmanr(d.m_u, d.log_ratio)[0]) if d.m_u.std() > 0 else np.nan,
|
||||
"n_multi_0.25": int((d.m_u >= 0.25).sum()), "n_any": int((d.m_u > 0).sum())} for k, d in u.groupby(["regime", "c"])]
|
||||
pd.DataFrame(within).to_csv(out / "test_iii_within_cells.csv", index=False)
|
||||
meta["test_iii"] = groups
|
||||
cell_share.to_csv(out / "test_iii.csv", index=False)
|
||||
md.append("## Test iii: posterior multimodality (GMM on the window offset; ΔBIC > 10, separation > 4 ms, min weight ≥ 0.1)\n")
|
||||
md.append(sp13.md(cell_share) + "\n")
|
||||
if groups:
|
||||
md.append("Wide cells, N = 16, M2-Sa/B3d-Sa log-ratio of multimodal minus unimodal units:\n")
|
||||
md.append(sp13.md(pd.DataFrame(groups).T.reset_index().rename(columns={"index": "grouping"})) + "\n")
|
||||
fig, ax = plt.subplots(figsize=(5.5, 3.4))
|
||||
if have_train and groups:
|
||||
for (regime, c), d in u.groupby(["regime", "c"]):
|
||||
ax.scatter(d.m_u + rng.normal(0, 0.005, len(d)), d.log_ratio, s=14, label=f"{regime} c={c:g}")
|
||||
ax.axhline(0, color=figstyle.AXIS, lw=0.8)
|
||||
ax.set_xlabel("share of multimodal training wells in the unit")
|
||||
ax.set_ylabel("log(band RMSE M2-Sa / B3d-Sa)")
|
||||
ax.set_title("Test iii: gain vs posterior multimodality (wide cells, N = 16)")
|
||||
ax.legend(fontsize=6, ncol=2)
|
||||
fig.tight_layout()
|
||||
fig.savefig(fig_dir / "t2_iii_multimodal.pdf")
|
||||
plt.close(fig)
|
||||
|
||||
# ---------------------------------------------------------------- test iv
|
||||
f4 = sorted((out / "iv").glob("*.csv"))
|
||||
if f4:
|
||||
m4 = pd.concat([pd.read_csv(f) for f in f4], ignore_index=True)
|
||||
for m in ["B3d-Sa", "B3c-R"]:
|
||||
m4[f"e_{m}"] = m4[f"a_{m}"] - m4["a_true"]
|
||||
m4[f"ah_{m}"] = m4[f"a_{m}"] - m4["a_B3b"]
|
||||
m4["at_anch"] = m4["a_true"] - m4["a_B3b"]
|
||||
rows = []
|
||||
cells = [(r, c, n) for (r, c, n), _ in m4.groupby(["regime", "c", "n_train"])] + [("all", 1.0, 0), ("wide16", 1.0, 16)]
|
||||
for regime, c, N in cells:
|
||||
if regime == "all":
|
||||
d = m4[m4.c == c]
|
||||
elif regime == "wide16":
|
||||
d = m4[(m4.n_train == 16) & (m4.c == 1.0) & m4.regime.isin([r for r, cc in WIDE16 if cc == 1.0])]
|
||||
else:
|
||||
d = m4[(m4.regime == regime) & (m4.c == c) & (m4.n_train == N)]
|
||||
for m in ["B3d-Sa", "B3c-R"]:
|
||||
r = dict(regime=regime, c=c, n_train=N, method=m, n_wells=int(len(d)),
|
||||
sd_e_ms=float(d[f"e_{m}"].std()), sd_atrue_ms=float(d.a_true.std()), sd_atrue_anch_ms=float(d.at_anch.std()),
|
||||
rmse_e_ms=float(np.sqrt((d[f"e_{m}"] ** 2).mean())))
|
||||
rC, rB = cluster_corr(rng, d, f"e_{m}", "a_true"), cluster_corr(rng, d, f"e_{m}", f"a_{m}")
|
||||
rCa, rBa = cluster_corr(rng, d, f"e_{m}", "at_anch"), cluster_corr(rng, d, f"e_{m}", f"ah_{m}")
|
||||
r |= {f"raw_rC_{k}": v for k, v in rC.items() if k != "n"} | {f"raw_rB_{k}": v for k, v in rB.items() if k != "n"}
|
||||
r |= {f"anch_rC_{k}": v for k, v in rCa.items() if k != "n"} | {f"anch_rB_{k}": v for k, v in rBa.items() if k != "n"}
|
||||
r["raw_var_ratio"] = float(d[f"a_{m}"].var() / d.a_true.var()) if d.a_true.var() > 0 else np.nan
|
||||
r["anch_var_ratio"] = float(d[f"ah_{m}"].var() / d.at_anch.var()) if d.at_anch.var() > 0 else np.nan
|
||||
r["verdict_anch"] = verdict_iv(rBa, rCa) if c > 0 else "not used (c = 0)"
|
||||
r["verdict_raw"] = verdict_iv(rB, rC) if c > 0 else "not used (c = 0)"
|
||||
rows.append(r)
|
||||
t4 = pd.DataFrame(rows)
|
||||
# per-sample sensitivity (node-wise offsets) for the N = 16 cells and the pooled c = 1 set
|
||||
srows = []
|
||||
for regime, c, N in [(r, c, n) for r, c, n in ALL_CELLS if n == 16]:
|
||||
parts = []
|
||||
for rid in RIDS:
|
||||
f = out / "iv" / f"{tag(regime, rid, c, N)}.npz"
|
||||
if not f.exists():
|
||||
continue
|
||||
with np.load(f) as z:
|
||||
wells = sorted({k.split("/")[0] for k in z.files})
|
||||
for w in wells:
|
||||
parts.append(pd.DataFrame({"rid": rid, "true": z[f"{w}/true"], "B3b": z[f"{w}/B3b"], "B3d-Sa": z[f"{w}/B3d-Sa"], "B3c-R": z[f"{w}/B3c-R"]}))
|
||||
if not parts:
|
||||
continue
|
||||
d = pd.concat(parts, ignore_index=True)
|
||||
for m in ["B3d-Sa", "B3c-R"]:
|
||||
d["e"], d["ah"], d["at"] = d[m] - d["true"], d[m] - d["B3b"], d["true"] - d["B3b"]
|
||||
rC, rB = cluster_corr(rng, d, "e", "true"), cluster_corr(rng, d, "e", m)
|
||||
rCa, rBa = cluster_corr(rng, d, "e", "at"), cluster_corr(rng, d, "e", "ah")
|
||||
srows.append(dict(regime=regime, c=c, n_train=N, method=m, n_samples=int(len(d)),
|
||||
**{f"raw_rC_{k}": v for k, v in rC.items() if k != "n"}, **{f"raw_rB_{k}": v for k, v in rB.items() if k != "n"},
|
||||
**{f"anch_rC_{k}": v for k, v in rCa.items() if k != "n"}, **{f"anch_rB_{k}": v for k, v in rBa.items() if k != "n"},
|
||||
verdict_anch=verdict_iv(rBa, rCa) if c > 0 else "not used (c = 0)",
|
||||
verdict_raw=verdict_iv(rB, rC) if c > 0 else "not used (c = 0)"))
|
||||
t4s = pd.DataFrame(srows)
|
||||
t4.to_csv(out / "test_iv.csv", index=False)
|
||||
t4s.to_csv(out / "test_iv_persample.csv", index=False)
|
||||
key_cells = t4[(t4.c == 1.0) & (t4.n_train == 16) | (t4.regime == "all") | (t4.regime == "wide16")]
|
||||
meta["test_iv"] = {f"{r.regime} c={r.c:g} N={r.n_train} {r.method}": {"anchored": r.verdict_anch, "raw": r.verdict_raw}
|
||||
for r in key_cells.itertuples()}
|
||||
md.append("## Test iv: Berkson vs classical (window offset; cluster bootstrap over realizations). anch = anchored to B3b (primary)\n")
|
||||
md.append(sp13.md(t4[["regime", "c", "n_train", "method", "n_wells", "sd_e_ms", "sd_atrue_ms", "sd_atrue_anch_ms", "anch_rB_r", "anch_rB_lo", "anch_rB_hi",
|
||||
"anch_rC_r", "anch_rC_lo", "anch_rC_hi", "anch_var_ratio", "verdict_anch", "raw_rB_r", "raw_rB_lo", "raw_rB_hi", "raw_rC_r",
|
||||
"raw_rC_lo", "raw_rC_hi", "raw_var_ratio", "verdict_raw"]]) + "\n")
|
||||
md.append("Per-sample sensitivity (node-wise offsets, N = 16):\n")
|
||||
md.append(sp13.md(t4s[["regime", "c", "method", "n_samples", "anch_rB_r", "anch_rB_lo", "anch_rB_hi", "anch_rC_r", "anch_rC_lo", "anch_rC_hi", "verdict_anch",
|
||||
"raw_rB_r", "raw_rC_r", "verdict_raw"]]) + "\n")
|
||||
fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), sharey=True)
|
||||
d16 = t4[(t4.n_train == 16) & (t4.c > 0) & ~t4.regime.isin(["all", "wide16"])]
|
||||
for ax, m in zip(axes, ["B3d-Sa", "B3c-R"]):
|
||||
d = d16[d16.method == m]
|
||||
labels = [f"{r} c={c:g}" for r, c in zip(d.regime, d.c)]
|
||||
y = np.arange(len(d))
|
||||
ax.errorbar(d.anch_rB_r, y - 0.15, xerr=[d.anch_rB_r - d.anch_rB_lo, d.anch_rB_hi - d.anch_rB_r], fmt="o", color=figstyle.BLUE, label="corr(e, â′): 0 under Berkson")
|
||||
ax.errorbar(d.anch_rC_r, y + 0.15, xerr=[d.anch_rC_r - d.anch_rC_lo, d.anch_rC_hi - d.anch_rC_r], fmt="s", color=figstyle.ORANGE, label="corr(e, a*′): 0 under classical")
|
||||
ax.axvline(0, color=figstyle.AXIS, lw=0.8)
|
||||
ax.set_yticks(y)
|
||||
ax.set_yticklabels(labels, fontsize=7)
|
||||
ax.set_title(m)
|
||||
ax.set_xlabel("correlation (anchored offsets)")
|
||||
axes[0].legend(fontsize=7, loc="lower left")
|
||||
fig.suptitle("Test iv: error structure of the window offset (N = 16; 95% cluster-bootstrap CI)", fontsize=9)
|
||||
fig.tight_layout()
|
||||
fig.savefig(fig_dir / "t2_iv_covariance.pdf")
|
||||
plt.close(fig)
|
||||
|
||||
(out / "meta.json").write_text(json.dumps(meta, indent=1, default=float))
|
||||
(out / "summary.md").write_text("\n".join(md))
|
||||
print("\n".join(md))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--tests", nargs="+", default=["i", "ii", "iii", "iv", "v", "summary"],
|
||||
choices=["i", "ii", "iii", "iv", "v", "summary"])
|
||||
ap.add_argument("--device", default="cuda:0")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/t2")
|
||||
ap.add_argument("--seeds", type=int, nargs="+", default=SEEDS)
|
||||
ap.add_argument("--cells", nargs="+", default=None, help="restrict the training stage to these cell tags (regime_c), e.g. R0_1")
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=RIDS)
|
||||
args = ap.parse_args()
|
||||
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "2",
|
||||
"NUMEXPR_NUM_THREADS": "2"}.items():
|
||||
os.environ.setdefault(k, v)
|
||||
out = args.out_dir or outputs_dir() / "t2"
|
||||
for sub in ("cells", "iii", "iv", "figures"):
|
||||
(out / sub).mkdir(parents=True, exist_ok=True)
|
||||
P = run_d2.load_protocol(check=True)
|
||||
if run_d2.check_rids(RIDS, P) is None:
|
||||
raise SystemExit("protocol_p2r main grid expected")
|
||||
print("protocol_p2 and protocol_p2r (with inputs) match their locked SHA-256", flush=True)
|
||||
|
||||
jobs, fn, workers = [], None, args.workers
|
||||
if {"i", "ii", "v"} & set(args.tests):
|
||||
cells = TRAIN_CELLS if args.cells is None else [(r, c, n) for r, c, n in TRAIN_CELLS if f"{r}_{c:g}" in args.cells]
|
||||
for regime, c, N in cells:
|
||||
for rid in args.rids:
|
||||
if not (out / "cells" / f"{tag(regime, rid, c, N)}.csv").exists():
|
||||
jobs.append((regime, rid, c, N, args.seeds, args.device, out / "cells", P))
|
||||
fn = train_job
|
||||
elif {"iii", "iv"} & set(args.tests):
|
||||
for regime, c, N in ALL_CELLS:
|
||||
for rid in args.rids:
|
||||
if not ((out / "iii" / f"{tag(regime, rid, c, N)}.csv").exists() and (out / "iv" / f"{tag(regime, rid, c, N)}.csv").exists()):
|
||||
jobs.append((regime, rid, c, N, out, P))
|
||||
fn = particle_job
|
||||
if fn is not None:
|
||||
print(f"{len(jobs)} jobs, {workers} workers, device {args.device}", flush=True)
|
||||
t0 = time.time()
|
||||
if jobs:
|
||||
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
|
||||
futs = {ex.submit(fn, j): j[:4] for j in jobs}
|
||||
for i, f in enumerate(as_completed(futs), 1):
|
||||
stem, dt = f.result()
|
||||
print(f"[{i}/{len(jobs)}] {stem} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
|
||||
if "summary" in args.tests:
|
||||
summarize(out, args.device)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("PYTHONHASHSEED", "0")
|
||||
main()
|
||||
496
scripts/33_bench_generator_qc.py
Normal file
496
scripts/33_bench_generator_qc.py
Normal file
@@ -0,0 +1,496 @@
|
||||
"""Generator QC for the S2 misspecification presets (phase P6, item p6-gen; CPU only, about one minute).
|
||||
|
||||
For one dev realization (default 902) and every preset of configs/d2_synth_bench.yaml, quantify what the preset changes
|
||||
relative to the nominal generator (common random numbers, so every difference is the misspecification itself):
|
||||
|
||||
rock physics relative RMS change of the clean seismic and of the true AI log (main window), per-unit shifts;
|
||||
wavelet stationary true wavelet vs nominal: best constant-phase fit (1° grid) and its correlation, peak
|
||||
frequency, 90 % power band; for constant Q the effective wavelet at 600 / 850 / 1100 ms;
|
||||
drift RMS and maximum of t_true,misspec − t_true,nominal over the main window, achieved jump at the step
|
||||
horizon, jitter RMS, monotone repairs; anchor-only Laplace tie (MAP-II hyperparameters as in
|
||||
protocol_p2, N = 4, c = 1, σ_a = 7 ms) warp RMSE against the truth;
|
||||
all axes model error seen by the registration at the TRUE warp: RMS of (seismic predicted by the nominal
|
||||
forward model − actual clean seismic) relative to the signal RMS, after the profiled amplitude α,
|
||||
(i) with the nominal F3 wavelet and (ii) with the best member of the registration's wavelet family
|
||||
(statistical wavelet from the clean train traces + constant phase on the 15° grid), as SNR-equivalent
|
||||
dB next to the regime noise levels (R10: 10 dB, Rm5: −5 dB).
|
||||
|
||||
Outputs: <out>/generator_qc.json and <out>/generator_qc.png (default outputs/bench/dev/). Dev realizations only.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=4 .venv/bin/python scripts/33_bench_generator_qc.py --rid 902 [--sweep]
|
||||
|
||||
--smc (GPU, or --device cpu as a fallback when the GPUs are full): the registration itself for every preset, as in protocol_p2r (pipeline.register → statistical wavelet,
|
||||
MAP-II hyperparameters, B3c/B3d ties; SMC tie posterior with the phase_R wavelet, γ = 1/κ, P particles) on the first
|
||||
N train wells at the given regimes, c = 1. Reports phase_R, SMC warp RMSE / 90 % coverage / width, posterior residual
|
||||
correlation and the B3c/B3d warp RMSE per preset → <out>/smc_qc_rid<rid>.json. One worker; about 1–3 min per cell.
|
||||
|
||||
OMP_NUM_THREADS=4 .venv/bin/python scripts/33_bench_generator_qc.py --rid 902 --skip-qc --smc --device cuda:1 \
|
||||
--regimes R10 Rm5 --n-train 4 --particles 1024
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import platform
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import scipy
|
||||
import yaml
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid, preset_misspec # noqa: E402
|
||||
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet # noqa: E402
|
||||
from ml_porosity.registration.pipeline import PHASES, fit_cell_hyper # noqa: E402
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, synth_for_warps # noqa: E402
|
||||
from ml_porosity.registration.ties import warp_errors # noqa: E402
|
||||
from ml_porosity.registration.warp_prior import WarpHyper, laplace_posterior # noqa: E402
|
||||
|
||||
DEV_RIDS = (902, 903, 904, 905)
|
||||
C, SIGMA_A, N_LAPLACE = 1.0, 7.0, 4
|
||||
NOISE_REL = {"R10": 10 ** (-10 / 20), "Rm5": 10 ** (5 / 20)} # noise RMS / signal RMS at the regime SNR
|
||||
PALETTE = {"nominal": "#52514e", "rp": "#2a78d6", "wv": "#eb6834", "dr": "#1baf7a"}
|
||||
SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
|
||||
|
||||
|
||||
def sha256(p: Path) -> str:
|
||||
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def rel_rms(a: np.ndarray, ref: np.ndarray) -> float:
|
||||
return float(np.sqrt(np.mean((a - ref) ** 2)) / np.sqrt(np.mean(ref ** 2)))
|
||||
|
||||
|
||||
def snr_db(rel: float) -> float:
|
||||
return float(-20.0 * np.log10(max(rel, 1e-12)))
|
||||
|
||||
|
||||
def wavelet_stats(w: np.ndarray, dt_ms: float, w_ref: np.ndarray) -> dict:
|
||||
"""Peak frequency, 90 % power band and the best constant-phase fit of w_ref to w (1° grid)."""
|
||||
f = np.fft.rfftfreq(8192, dt_ms / 1000.0)
|
||||
p = np.abs(np.fft.rfft(w, 8192)) ** 2
|
||||
cum = np.cumsum(p) / p.sum()
|
||||
if len(w_ref) != len(w): # centre-pad the shorter one (Q kernels are longer than the wavelet)
|
||||
n = max(len(w), len(w_ref))
|
||||
pad = lambda v: np.pad(v, ((n - len(v)) // 2, (n - len(v)) // 2))
|
||||
w, w_ref = pad(w), pad(w_ref)
|
||||
phases = np.arange(-180.0, 180.0, 1.0)
|
||||
cc = np.array([np.corrcoef(rotate_phase(w_ref, ph), w)[0, 1] for ph in phases])
|
||||
k = int(np.argmax(cc))
|
||||
return {"peak_hz": float(f[np.argmax(p)]), "f05_hz": float(f[np.searchsorted(cum, 0.05)]),
|
||||
"f95_hz": float(f[np.searchsorted(cum, 0.95)]), "best_const_phase_deg": float(phases[k]),
|
||||
"corr_at_best_phase": float(cc[k]), "resid_after_best_phase": float(np.sqrt(max(0.0, 1 - cc[k] ** 2)))}
|
||||
|
||||
|
||||
def model_errors(R, obs: list[dict], w_fine: np.ndarray) -> np.ndarray:
|
||||
"""Per well: relative RMS of (clean centre trace − α·synthetic) at the true warp, α ≥ 0 profiled."""
|
||||
out = []
|
||||
for o in obs:
|
||||
s = o["seis"][o["seis"].shape[0] // 2].astype(float)
|
||||
syn = synth_for_warps(R.tau_fine, o["ai_log"], o["t_of_tau_true"], R.t_fine, R.t_ext, w_fine)[0]
|
||||
a = max(float(syn @ s / max(syn @ syn, 1e-30)), 0.0)
|
||||
out.append(rel_rms(a * syn, s))
|
||||
return np.array(out)
|
||||
|
||||
|
||||
def in_family_error(R, obs: list[dict], wavelet_ms: float) -> dict:
|
||||
"""Best member of the registration's wavelet family at the true warp: statistical wavelet from the clean train
|
||||
traces, constant phase on the 15° grid chosen as in pipeline.register (maximal profiled likelihood summed over
|
||||
wells), then the per-well model error."""
|
||||
fac = int(round(R.dt / R.cfg["fine_dt_ms"]))
|
||||
seis = np.stack([o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs])
|
||||
w0 = statistical_wavelet(seis, R.dt, wavelet_ms)
|
||||
errs = {float(ph): model_errors(R, obs, fine_wavelet(rotate_phase(w0, ph), fac)) for ph in PHASES}
|
||||
score = {ph: -0.5 * len(R.t_ext) * np.sum(np.log(e ** 2)) for ph, e in errs.items()}
|
||||
best = max(score, key=score.get)
|
||||
e = errs[best]
|
||||
return {"phase_deg": best, "err_mean": float(e.mean()), "err_min": float(e.min()), "err_max": float(e.max()),
|
||||
"snr_equiv_db": snr_db(float(e.mean())), "statistical_wavelet": wavelet_stats(w0, R.dt, R.wavelet_nominal)}
|
||||
|
||||
|
||||
def laplace_tie(R, obs: list[dict], reg: dict) -> dict:
|
||||
"""Anchor-only tie under the registration's prior (MAP-II for m_g, σ_g, ℓ; σ_a, σ_b fixed): Laplace mean warp
|
||||
RMSE against the truth over the main window, per well."""
|
||||
h, info = fit_cell_hyper(R, obs, reg, seed=0)
|
||||
rmse, z = [], []
|
||||
for o in obs:
|
||||
mu, S, _, _ = laplace_posterior(R.grid, h, o["tau_k"], o["t_k"] - o["tau_k"])
|
||||
T = R.grid.t_of_tau(mu[0], mu[1:], tau=R.tau_fine)
|
||||
rmse.append(warp_errors(T, R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"])
|
||||
# standardised error of the warp on the grid nodes inside the main window (posterior sd from S)
|
||||
sel = (R.grid.tau >= R.t_main[0]) & (R.grid.tau <= R.t_main[-1])
|
||||
A = np.hstack([np.ones((R.grid.n, 1)), R.grid.Q]) # linearised t(τ) − τ ≈ A u on the grid
|
||||
sd = np.sqrt(np.maximum(np.einsum("ij,jk,ik->i", A, S, A), 1e-12))
|
||||
t_true = R.true_warp_grid(next(w for w in R.wells if w.name == o["name"]), C)
|
||||
z.append(float(np.sqrt(np.mean(((R.grid.t_of_tau(mu[0], mu[1:])[0] - t_true) / sd)[sel] ** 2))))
|
||||
return {"hyper_fit": h.as_dict(), "log_marginal": float(info["log_marginal"]), "at_bound": info["at_bound"],
|
||||
"warp_rmse_ms_mean": float(np.mean(rmse)), "warp_rmse_ms_max": float(np.max(rmse)),
|
||||
"z_rms_mean": float(np.mean(z))}
|
||||
|
||||
|
||||
def qc_preset(R, R0, reg: dict, wavelet_ms: float) -> dict:
|
||||
obs = [R.observe(w, C, None, SIGMA_A) for w in R.pool]
|
||||
obs0 = [R0.observe(w, C, None, SIGMA_A) for w in R0.pool]
|
||||
main_tau = (R.tau_fine >= R.t_main[0]) & (R.tau_fine <= R.t_main[-1])
|
||||
out = {"active": R.misspec_active, "misspec_info": R.misspec_info}
|
||||
# seismic and model error (all axes)
|
||||
out["seis_rel_change_main"] = float(np.mean([rel_rms(o["seis"][4][R.main], o0["seis"][4][R.main])
|
||||
for o, o0 in zip(obs, obs0)]))
|
||||
e_nom = model_errors(R, obs, R.w_fine_nominal)
|
||||
out["model_err_nominal_wavelet"] = {"err_mean": float(e_nom.mean()), "err_max": float(e_nom.max()),
|
||||
"snr_equiv_db": snr_db(float(e_nom.mean()))}
|
||||
out["model_err_in_family"] = in_family_error(R, obs, wavelet_ms)
|
||||
# rock physics
|
||||
if "rock_physics" in R.misspec_active:
|
||||
ai_rel, lnai = [], []
|
||||
for w, o in zip(R.pool, obs):
|
||||
ai_t = R.ai_log_true(w, o)
|
||||
ai_rel.append(rel_rms(ai_t[main_tau], o["ai_log"][main_tau]))
|
||||
lnai.append(float(np.sqrt(np.mean((np.log(ai_t) - np.log(o["ai_log"]))[main_tau] ** 2))))
|
||||
out["rock_physics"] = {"ai_rel_rms_change_main": float(np.mean(ai_rel)), "ln_ai_rms_change_main": float(np.mean(lnai)),
|
||||
"unit_dt_intercept_shift": None if R.unit_dt_shift is None else
|
||||
[float(v) for v in R.unit_dt_shift]}
|
||||
# wavelet
|
||||
if "wavelet" in R.misspec_active:
|
||||
d = R.cfg["fine_dt_ms"]
|
||||
wv = {"stationary": wavelet_stats(R.w_fine, d, R.w_fine_nominal)}
|
||||
if R.misspec["wavelet"]["Q"] is not None:
|
||||
wv["Q_at_t"] = {str(int(t)): wavelet_stats(R.true_wavelet_at(t), d, R.w_fine_nominal) for t in (600, 850, 1100)}
|
||||
out["wavelet"] = wv
|
||||
# drift
|
||||
if "drift" in R.misspec_active:
|
||||
dr = R.misspec["drift"]
|
||||
diff = np.array([o["t_of_tau_true"] - o0["t_of_tau_true"] for o, o0 in zip(obs, obs0)])
|
||||
tau_main = (R.tau_fine >= 600) & (R.tau_fine <= 1100)
|
||||
d = {"warp_diff_rms_main_ms": float(np.sqrt(np.mean(diff[:, tau_main] ** 2))),
|
||||
"warp_diff_max_ms": float(np.abs(diff).max()),
|
||||
"true_hyper": R.drift_true.as_dict(), "nominal_hyper": R.drift.as_dict()}
|
||||
if dr["step_ms"] != 0.0:
|
||||
k = R.cfg["horizons"].index(dr["step_horizon"])
|
||||
jumps, tau_hs = [], []
|
||||
for w, o, o0, df in zip(R.pool, obs, obs0, diff):
|
||||
t_h = R.hg.at(w.il, w.xl)[k]
|
||||
tau_h = np.interp(t_h, o0["t_of_tau_true"], R.tau_fine)
|
||||
jumps.append(float(np.interp(tau_h + dr["step_width_ms"] + 12, R.tau_fine, df) - np.interp(tau_h - 8, R.tau_fine, df)))
|
||||
tau_hs.append(float(tau_h))
|
||||
d["step"] = {"jump_ms_mean": float(np.mean(jumps)), "jump_ms_min": float(np.min(jumps)), "jump_ms_max": float(np.max(jumps)),
|
||||
"tau_h_ms_range": [float(np.min(tau_hs)), float(np.max(tau_hs))],
|
||||
"g_anomaly_mean": float(np.mean([np.max(o["g"] - o0["g"]) for o, o0 in zip(obs, obs0)]))}
|
||||
if dr["jitter_sd_ms"] > 0:
|
||||
jit = np.array([o["t_of_tau_true"] - np.interp(R.tau_fine, R.grid.tau, R.grid.t_of_tau(o["b"], o["g"])[0]) for o in obs])
|
||||
d["jitter_rms_ms"] = float(np.sqrt(np.mean(jit ** 2)))
|
||||
d["laplace_tie_N4"] = laplace_tie(R, obs[:N_LAPLACE], reg)
|
||||
out["drift"] = d
|
||||
return out
|
||||
|
||||
|
||||
SWEEP = { # single-knob settings for the level choice on dev (--sweep)
|
||||
"rock_physics.unit_dt_intercept_sd": [0.025, 0.05, 0.1, 0.15],
|
||||
"rock_physics.dt_slope_factor": [0.85, 1.3],
|
||||
"wavelet.minphase_frac": [0.25, 0.5, 0.75, 1.0],
|
||||
"wavelet.Q": [40.0, 80.0, 160.0],
|
||||
"wavelet.peak_freq_factor": [0.8, 1.2],
|
||||
"wavelet.delay_ms": [2.0, 4.0],
|
||||
"drift.step_ms": [4.0, 8.0, 16.0],
|
||||
"drift.jitter_sd_ms": [0.5, 1.0, 2.0],
|
||||
"drift.sigma_b_factor": [2.0, 3.0, 5.0],
|
||||
"drift.sigma_g_factor": [1.5, 2.0],
|
||||
"drift.ell_factor": [0.5, 0.25],
|
||||
}
|
||||
|
||||
|
||||
def run_sweep(build, R0, reg: dict, out: Path) -> None:
|
||||
"""Model error and (for drift) the anchor-only tie for each single-knob setting of SWEEP; one line per setting."""
|
||||
rows = []
|
||||
for key, values in SWEEP.items():
|
||||
axis, k = key.split(".")
|
||||
for v in values:
|
||||
t1 = time.time()
|
||||
R = build({axis: {k: v}})
|
||||
r = qc_preset(R, R0, reg, reg["wavelet_ms"])
|
||||
row = {"axis": axis, "key": k, "value": v, "seis_rel_change_main": r["seis_rel_change_main"],
|
||||
"model_err_nominal_wavelet": r["model_err_nominal_wavelet"]["err_mean"],
|
||||
"model_err_in_family": r["model_err_in_family"]["err_mean"],
|
||||
"snr_equiv_db": r["model_err_in_family"]["snr_equiv_db"], "phase_deg": r["model_err_in_family"]["phase_deg"]}
|
||||
if axis == "drift":
|
||||
d = r["drift"]
|
||||
row |= {"warp_diff_rms_main_ms": d["warp_diff_rms_main_ms"], "laplace_warp_rmse_ms": d["laplace_tie_N4"]["warp_rmse_ms_mean"],
|
||||
"laplace_z_rms": d["laplace_tie_N4"]["z_rms_mean"], "monotone_repairs": r["misspec_info"]["monotone_repairs"]}
|
||||
if axis == "wavelet":
|
||||
row |= {"corr_best_const_phase": r["wavelet"]["stationary"]["corr_at_best_phase"]}
|
||||
rows.append(row)
|
||||
extra = (f" warp diff {row['warp_diff_rms_main_ms']:.2f} ms, Laplace RMSE {row['laplace_warp_rmse_ms']:.2f} ms, z {row['laplace_z_rms']:.2f}"
|
||||
if axis == "drift" else "")
|
||||
print(f"sweep {key} = {v:<6g} in-family error {row['model_err_in_family']:.3f} ({row['snr_equiv_db']:.1f} dB, phase {row['phase_deg']:.0f}°)"
|
||||
f"{extra} | {time.time() - t1:.1f} s", flush=True)
|
||||
(out / "generator_sweep.json").write_text(json.dumps({"rid": R0.rid, "c": C, "sigma_a_ms": SIGMA_A, "rows": rows}, indent=1) + "\n")
|
||||
|
||||
|
||||
def smc_cell(R, reg: dict, st: dict, N: int, n_part: int, device: str, mem_gb: float, seed: int = 0) -> dict:
|
||||
"""Registration of one cell (first N train wells, c = 1) as in protocol_p2r: pipeline.register (CPU), then the SMC
|
||||
tie posterior on `device` with the phase_R wavelet and γ = 1/κ (g_acf). Returns per-well diagnostics."""
|
||||
from ml_porosity.registration.pipeline import register
|
||||
from ml_porosity.registration.sampler import sample_warps
|
||||
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet, residual_kappa
|
||||
|
||||
if device == "cpu": # numpy SMC (as scripts/14 with --device cpu)
|
||||
from ml_porosity.registration.smc import smc_fit_phase, smc_tie_posterior
|
||||
wrap = lambda T: T
|
||||
else:
|
||||
import torch
|
||||
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
|
||||
|
||||
dev = torch.device(device)
|
||||
if dev.type == "cuda": # cap: exceeding it makes this job OOM rather than others
|
||||
total = torch.cuda.get_device_properties(dev).total_memory
|
||||
torch.cuda.set_per_process_memory_fraction(min(1.0, mem_gb * 2**30 / total), dev)
|
||||
wrap = lambda T: TiePosteriorTorch(T, device)
|
||||
obs = [R.observe(w, C, st["snr_db"], SIGMA_A, st["anchor_density"]) for w in R.pool[:N]]
|
||||
t0 = time.time()
|
||||
out = register(R, obs, reg, seed)
|
||||
t_reg = time.time() - t0
|
||||
h = WarpHyper(**out["hyper"])
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
mm = (R.t_ext >= R.t_main[0]) & (R.t_ext <= R.t_main[-1])
|
||||
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
|
||||
B = phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), int(round(R.dt / R.cfg["fine_dt_ms"])))
|
||||
Ts, Z0s = [], []
|
||||
for i, o in enumerate(obs):
|
||||
smp = sample_warps(R.grid, h, o["tau_k"], o["t_k"], n_part, reg["g_max"], np.random.default_rng([seed, i, 13]))
|
||||
Ts.append(wrap(TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine,
|
||||
R.t_ext, phase_wavelet(B, out["phase"]), seis[i], (R.t_main[0], R.t_main[-1]))))
|
||||
Z0s.append(Ts[-1].z(smp["u"]))
|
||||
t0 = time.time()
|
||||
phase_r, ph = smc_fit_phase(Ts, Z0s, B, out["phase"], [seed, 19])
|
||||
t_phase = time.time() - t0
|
||||
rows = []
|
||||
t0 = time.time()
|
||||
for i, o in enumerate(obs):
|
||||
T = Ts[i].with_wavelet(phase_wavelet(B, phase_r))
|
||||
_, l0 = T.parts(Z0s[i])
|
||||
gk = gamma_acf(T, Z0s[i], l0)
|
||||
res = smc_tie_posterior(T, Z0s[i], [gk], np.random.default_rng([seed, i, 17]))
|
||||
U = T.u(res["Z"][float(gk)])
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
|
||||
e = warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)
|
||||
syn_m = T.synth(U.mean(0)[None])[0]
|
||||
d = out["diag"][i]
|
||||
rows.append({"well": o["name"], "gamma": float(gk), "kappa0": float(1.0 / gk), "logZ": float(res["logZ"][float(gk)]),
|
||||
"n_stages": len(res["stages"]), "r_post": ncc(syn_m, seis[i]), "kappa_post": float(residual_kappa(syn_m, seis[i])),
|
||||
"B3c_warp_rmse_ms": d["B3c_warp_rmse_ms"], "B3d_warp_rmse_ms": d["B3d_warp_rmse_ms"],
|
||||
"M2old_warp_rmse_ms": d["M2_warp_rmse_ms"]} | {f"SMC_{k}": float(v) for k, v in e.items()})
|
||||
keys = ["SMC_warp_rmse_ms", "SMC_warp_cov90", "SMC_warp_width90_ms", "r_post", "kappa_post", "B3c_warp_rmse_ms", "B3d_warp_rmse_ms"]
|
||||
return {"phase0": out["phase"], "phase_R": phase_r, "phase_edge": ph["edge"], "hyper": out["hyper"], "lam": out["lam"],
|
||||
"tau_c": out["tau_c"], "wells": rows, "mean": {k: float(np.mean([r[k] for r in rows])) for k in keys},
|
||||
"time_s": {"register": t_reg, "phase": t_phase, "smc": time.time() - t0}}
|
||||
|
||||
|
||||
def run_smc(build, cfg: dict, reg: dict, names: list[str], regimes: list[str], N: int, n_part: int, device: str,
|
||||
mem_gb: float, out: Path, rid: int) -> None:
|
||||
path = out / f"smc_qc_rid{rid}.json"
|
||||
results = json.loads(path.read_text()) if path.exists() else {}
|
||||
results["meta"] = {"rid": rid, "c": C, "sigma_a_ms": SIGMA_A, "n_train": N, "particles": n_part, "device": device,
|
||||
"arm": "estR (statistical wavelet, phase_R), gamma = 1/kappa (g_acf)", "updated": dt.datetime.now().isoformat(timespec="seconds")}
|
||||
for regime in regimes:
|
||||
st = cfg["regimes"][regime]
|
||||
results.setdefault(regime, {})
|
||||
for name in ["nominal"] + names:
|
||||
if name in results[regime]:
|
||||
continue # resume
|
||||
t1 = time.time()
|
||||
R = build(preset_misspec(cfg, name))
|
||||
r = smc_cell(R, reg, st, N, n_part, device, mem_gb)
|
||||
r["active"] = R.misspec_active
|
||||
results[regime][name] = r
|
||||
path.write_text(json.dumps(results, indent=1) + "\n")
|
||||
m = r["mean"]
|
||||
print(f"smc {regime} {name:8s} phase0 {r['phase0']:5.0f}° phase_R {r['phase_R']:5.0f}° | SMC warp RMSE {m['SMC_warp_rmse_ms']:.2f} ms "
|
||||
f"cov90 {m['SMC_warp_cov90']:.2f} width90 {m['SMC_warp_width90_ms']:.1f} ms r_post {m['r_post']:.3f} | B3c {m['B3c_warp_rmse_ms']:.2f} "
|
||||
f"B3d {m['B3d_warp_rmse_ms']:.2f} ms | {time.time() - t1:.0f} s", flush=True)
|
||||
|
||||
|
||||
def make_figure(R0, builds: dict, results: dict, out_png: Path) -> None:
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
plt.rcParams.update({"font.size": 8.5, "axes.titlesize": 9, "axes.labelsize": 8.5, "legend.fontsize": 7.5,
|
||||
"axes.edgecolor": "#c3c2b7", "axes.spines.top": False, "axes.spines.right": False,
|
||||
"text.color": "#0b0b0b", "axes.labelcolor": "#0b0b0b", "xtick.color": "#52514e", "ytick.color": "#52514e"})
|
||||
fig, axes = plt.subplots(2, 3, figsize=(13, 7.4), constrained_layout=True)
|
||||
names = list(results["presets"])
|
||||
by_axis = {ax: [n for n in names if n.startswith(ax)] for ax in ("rp", "wv", "dr")}
|
||||
w0 = R0.pool[0]
|
||||
o0 = R0.observe(w0, C, None, SIGMA_A)
|
||||
main_tau = (R0.tau_fine >= 600) & (R0.tau_fine <= 1100)
|
||||
|
||||
# (a) rock physics: ln(AI_true / AI_nominal) along the log (pool well 0)
|
||||
ax = axes[0, 0]
|
||||
for col, n in zip(SERIES, by_axis["rp"]):
|
||||
R = builds[n]
|
||||
o = R.observe(R.pool[0], C, None, SIGMA_A)
|
||||
ax.plot(R.tau_fine[main_tau], np.log(R.ai_log_true(R.pool[0], o) / o["ai_log"])[main_tau], color=col, lw=1.2, label=n)
|
||||
ax.axhline(0, color="#c3c2b7", lw=0.8)
|
||||
ax.set(xlabel="τ (ms)", ylabel="ln(AI_true / AI_nominal)", title=f"(a) Rock physics: true vs nominal AI along the log ({w0.name})")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (b) wavelets in time
|
||||
ax = axes[0, 1]
|
||||
tf = (np.arange(len(R0.w_fine)) - len(R0.w_fine) // 2) * R0.cfg["fine_dt_ms"]
|
||||
ax.plot(tf, R0.w_fine, color=PALETTE["nominal"], lw=1.6, label="nominal (zero phase)")
|
||||
for col, n in zip(SERIES, by_axis["wv"]):
|
||||
R = builds[n]
|
||||
if R.misspec["wavelet"]["Q"] is not None:
|
||||
k = R.true_wavelet_at(1100.0)
|
||||
tk = (np.arange(len(k)) - len(k) // 2) * R.cfg["fine_dt_ms"]
|
||||
ax.plot(tk, k / np.abs(k).max(), color=col, lw=1.2, ls="--", label=f"{n} at 1100 ms")
|
||||
else:
|
||||
ax.plot(tf, R.w_fine, color=col, lw=1.2, label=n)
|
||||
ax.set(xlim=(-70, 70), xlabel="time (ms)", ylabel="amplitude (unit peak)", title="(b) Stationary true wavelets (and Q kernel)")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (c) amplitude spectra
|
||||
ax = axes[0, 2]
|
||||
f = np.fft.rfftfreq(8192, R0.cfg["fine_dt_ms"] / 1000.0)
|
||||
spec = lambda w: np.abs(np.fft.rfft(w, 8192)) / np.abs(np.fft.rfft(w, 8192)).max()
|
||||
ax.plot(f, spec(R0.w_fine), color=PALETTE["nominal"], lw=1.6, label="nominal")
|
||||
for col, n in zip(SERIES, by_axis["wv"]):
|
||||
R = builds[n]
|
||||
if R.misspec["wavelet"]["Q"] is not None:
|
||||
for t, ls in ((600.0, ":"), (1100.0, "--")):
|
||||
ax.plot(f, spec(R.true_wavelet_at(t)), color=col, lw=1.2, ls=ls, label=f"{n} at {int(t)} ms")
|
||||
else:
|
||||
ax.plot(f, spec(R.w_fine), color=col, lw=1.2, label=n)
|
||||
ax.set(xlim=(0, 125), xlabel="frequency (Hz)", ylabel="normalised amplitude", title="(c) Amplitude spectra")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (d) drift: warp change
|
||||
ax = axes[1, 0]
|
||||
for col, n in zip(SERIES, by_axis["dr"]):
|
||||
R = builds[n]
|
||||
o = R.observe(R.pool[0], C, None, SIGMA_A)
|
||||
ax.plot(R.tau_fine, o["t_of_tau_true"] - o0["t_of_tau_true"], color=col, lw=1.2, label=n)
|
||||
ax.axvspan(600, 1100, color="#f0efec", zorder=0)
|
||||
ax.set(xlabel="τ (ms)", ylabel="t_true,misspec − t_true,nominal (ms)", title=f"(d) Drift: change of the true warp ({w0.name}, c = 1)")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (e) model error at the true warp, in-family best (SNR-equivalent dB)
|
||||
ax = axes[1, 1]
|
||||
labels = ["nominal"] + names
|
||||
vals = [results["nominal"]["model_err_in_family"]["snr_equiv_db"]] + [results["presets"][n]["model_err_in_family"]["snr_equiv_db"] for n in names]
|
||||
cols = [PALETTE["nominal"]] + [SERIES[0]] * len(names)
|
||||
x = np.arange(len(labels))
|
||||
ax.bar(x, vals, color=cols, width=0.7)
|
||||
for xi, v in zip(x, vals):
|
||||
ax.text(xi, v + 0.6, f"{v:.1f}", ha="center", va="bottom", fontsize=7, color="#0b0b0b")
|
||||
for reg, ls in (("R10", "--"), ("Rm5", ":")):
|
||||
ax.axhline(snr_db(NOISE_REL[reg]), color="#52514e", lw=0.9, ls=ls)
|
||||
ax.text(len(labels) - 0.5, snr_db(NOISE_REL[reg]) + 0.4, f"{reg} noise", ha="right", fontsize=7, color="#52514e")
|
||||
ax.set(xticks=x, xticklabels=labels, ylabel="SNR-equivalent of the model error (dB)",
|
||||
title="(e) Model error at the true warp, best in-family wavelet")
|
||||
ax.tick_params(axis="x", rotation=45)
|
||||
|
||||
# (f) anchor-only Laplace tie (N = 4)
|
||||
ax = axes[1, 2]
|
||||
lab = ["nominal"] + by_axis["dr"]
|
||||
rm = [results["nominal"]["laplace_tie_N4"]["warp_rmse_ms_mean"]] + [results["presets"][n]["drift"]["laplace_tie_N4"]["warp_rmse_ms_mean"] for n in by_axis["dr"]]
|
||||
zr = [results["nominal"]["laplace_tie_N4"]["z_rms_mean"]] + [results["presets"][n]["drift"]["laplace_tie_N4"]["z_rms_mean"] for n in by_axis["dr"]]
|
||||
x = np.arange(len(lab))
|
||||
ax.bar(x, rm, color=[PALETTE["nominal"]] + [SERIES[0]] * len(by_axis["dr"]), width=0.6)
|
||||
for xi, v, z in zip(x, rm, zr):
|
||||
ax.text(xi, v + 0.05, f"{v:.2f} ms\nz RMS {z:.1f}", ha="center", va="bottom", fontsize=7, color="#0b0b0b")
|
||||
ax.set(xticks=x, xticklabels=lab, ylabel="warp RMSE of the Laplace mean (ms)", ylim=(0, max(rm) * 1.35),
|
||||
title="(f) Anchor-only tie under the registration prior (N = 4)")
|
||||
fig.suptitle(f"D2 generator QC, dev realization {R0.rid}: misspecification presets vs nominal (common random numbers)", fontsize=10)
|
||||
fig.savefig(out_png, dpi=160)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--rid", type=int, default=902, help="dev realization (902–905)")
|
||||
ap.add_argument("--config", default="configs/d2_synth_bench.yaml")
|
||||
ap.add_argument("--inputs-from", default="configs/protocol_p2r.yaml", help="protocol whose inputs (warp prior, wavelet) are used")
|
||||
ap.add_argument("--reg-from", default="configs/protocol_p2.yaml", help="protocol whose registration block is used for the anchor-only tie")
|
||||
ap.add_argument("--out", default="outputs/bench/dev")
|
||||
ap.add_argument("--presets", nargs="*", default=None, help="subset of preset names (default: all)")
|
||||
ap.add_argument("--sweep", action="store_true", help="also evaluate the single-knob settings of SWEEP → generator_sweep.json")
|
||||
ap.add_argument("--skip-qc", action="store_true", help="skip the light QC and the figure")
|
||||
ap.add_argument("--smc", action="store_true", help="run the registration + SMC tie posterior per preset (GPU) → smc_qc_rid<rid>.json")
|
||||
ap.add_argument("--device", default="cuda:1")
|
||||
ap.add_argument("--regimes", nargs="*", default=["R10", "Rm5"])
|
||||
ap.add_argument("--n-train", type=int, default=4)
|
||||
ap.add_argument("--particles", type=int, default=1024)
|
||||
ap.add_argument("--gpu-mem-gb", type=float, default=2.0, help="per-process GPU memory cap (GiB)")
|
||||
a = ap.parse_args()
|
||||
if a.rid not in DEV_RIDS:
|
||||
raise SystemExit(f"generator QC runs on dev realizations {DEV_RIDS} only (got {a.rid})")
|
||||
|
||||
cfg = yaml.safe_load((REPO_ROOT / a.config).read_text())
|
||||
P = yaml.safe_load((REPO_ROOT / a.inputs_from).read_text())
|
||||
spec = importlib.util.spec_from_file_location("run_d2", REPO_ROOT / "scripts" / "11_run_d2.py")
|
||||
run_d2 = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(run_d2)
|
||||
reg = run_d2.reg_settings(yaml.safe_load((REPO_ROOT / a.reg_from).read_text()))
|
||||
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
|
||||
build = lambda ms: D2Realization(cfg, a.rid, hg, WarpHyper(**prior["hyper"]), wav, misspec=ms)
|
||||
|
||||
out = REPO_ROOT / a.out
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
names = a.presets or list(cfg["misspec_presets"])
|
||||
if a.smc:
|
||||
run_smc(build, cfg, reg, names, a.regimes, a.n_train, a.particles, a.device, a.gpu_mem_gb, out, a.rid)
|
||||
if a.skip_qc:
|
||||
return
|
||||
t0 = time.time()
|
||||
R0 = build(None)
|
||||
obs0 = [R0.observe(w, C, None, SIGMA_A) for w in R0.pool]
|
||||
e_nom = model_errors(R0, obs0, R0.w_fine_nominal)
|
||||
results = {"nominal": {"model_err_nominal_wavelet": {"err_mean": float(e_nom.mean()), "err_max": float(e_nom.max()),
|
||||
"snr_equiv_db": snr_db(float(e_nom.mean()))},
|
||||
"model_err_in_family": in_family_error(R0, obs0, reg["wavelet_ms"]),
|
||||
"laplace_tie_N4": laplace_tie(R0, obs0[:N_LAPLACE], reg),
|
||||
"wavelet": wavelet_stats(R0.w_fine, cfg["fine_dt_ms"], R0.w_fine_nominal)},
|
||||
"presets": {}}
|
||||
builds = {}
|
||||
for name in names:
|
||||
t1 = time.time()
|
||||
R = build(preset_misspec(cfg, name))
|
||||
builds[name] = R
|
||||
results["presets"][name] = {"spec": cfg["misspec_presets"][name]} | qc_preset(R, R0, reg, reg["wavelet_ms"])
|
||||
results["presets"][name]["time_s"] = time.time() - t1
|
||||
r = results["presets"][name]
|
||||
print(f"{name:6s} seis change {r['seis_rel_change_main']:.3f} | model error nominal-wavelet {r['model_err_nominal_wavelet']['err_mean']:.3f} "
|
||||
f"({r['model_err_nominal_wavelet']['snr_equiv_db']:.1f} dB), in-family {r['model_err_in_family']['err_mean']:.3f} "
|
||||
f"({r['model_err_in_family']['snr_equiv_db']:.1f} dB, phase {r['model_err_in_family']['phase_deg']:.0f}°) | {r['time_s']:.1f} s", flush=True)
|
||||
results["meta"] = {
|
||||
"created": dt.datetime.now().isoformat(timespec="seconds"), "rid": a.rid, "c": C, "sigma_a_ms": SIGMA_A,
|
||||
"wells": "16 pool wells (train pool); Laplace tie on the first 4", "snr": "clean seismic (snr_db = None)",
|
||||
"config": {"path": a.config, "sha256": sha256(REPO_ROOT / a.config)},
|
||||
"inputs": {k: {"path": P["inputs"][k]["path"], "sha256": sha256(REPO_ROOT / P["inputs"][k]["path"])} for k in ("warp_prior", "wavelet")},
|
||||
"registration": {"from": a.reg_from, **{k: reg[k] for k in ("sigma_a_ms", "sigma_b_ms", "hyperprior", "wavelet_ms", "g_max")}},
|
||||
"noise_rel_rms": NOISE_REL, "noise_snr_equiv_db": {k: snr_db(v) for k, v in NOISE_REL.items()},
|
||||
"env": {"numpy": np.__version__, "scipy": scipy.__version__, "python": platform.python_version()},
|
||||
"time_s": time.time() - t0,
|
||||
}
|
||||
(out / "generator_qc.json").write_text(json.dumps(results, indent=1) + "\n")
|
||||
make_figure(R0, builds, results, out / "generator_qc.png")
|
||||
if a.sweep:
|
||||
run_sweep(build, R0, reg, out)
|
||||
print(f"nominal: model error nominal-wavelet {e_nom.mean():.3f}, in-family {results['nominal']['model_err_in_family']['err_mean']:.3f} "
|
||||
f"({results['nominal']['model_err_in_family']['snr_equiv_db']:.1f} dB); Laplace N=4 warp RMSE "
|
||||
f"{results['nominal']['laplace_tie_N4']['warp_rmse_ms_mean']:.2f} ms; total {time.time() - t0:.0f} s → {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
86
scripts/34_run_bench.py
Normal file
86
scripts/34_run_bench.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""protocol_bench runner (configs/protocol_bench.yaml): status | lock | posterior | train | summarize | repro | dev-budgets.
|
||||
|
||||
python scripts/34_run_bench.py lock # first lock (refuses if results exist)
|
||||
python scripts/34_run_bench.py posterior --studies S1 S2 --device cuda:0 --workers 4 --gpu-mem-gb 6
|
||||
python scripts/34_run_bench.py train --studies S1 S2 S3 S4 S8 --device cuda:1 --workers 4
|
||||
python scripts/34_run_bench.py summarize # outputs/bench/summary/
|
||||
python scripts/34_run_bench.py repro --device cuda:0 # P2r reproduction cell → outputs/bench/repro/
|
||||
python scripts/34_run_bench.py posterior train --dev --rids 902 903 --studies S2 --presets rp_L1 ... # dev only
|
||||
python scripts/34_run_bench.py dev-budgets --device cuda:0 # TCN budgets on dev 902–905 (R10, c = 1)
|
||||
|
||||
Main realizations 8–15 run only after the lock; --dev restricts to realizations 900–905 and writes under
|
||||
outputs/bench/dev; repro writes under outputs/bench/repro. --regimes / --presets / --rids filter the planned cells
|
||||
(a partial run is resumed, never a different design). Threads default to 2 per worker (OMP/MKL/OPENBLAS).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
for _k, _v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMEXPR_NUM_THREADS": "2",
|
||||
"NUMBA_NUM_THREADS": "2", "PYTHONHASHSEED": "0", "PYTHONUTF8": "1", "CUBLAS_WORKSPACE_CONFIG": ":4096:8"}.items():
|
||||
os.environ.setdefault(_k, _v)
|
||||
|
||||
STAGES = ["status", "lock", "posterior", "train", "summarize", "repro", "dev-budgets", "all"]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from ml_porosity.benchmark.cells import bench_root
|
||||
from ml_porosity.benchmark.protocol import freeze, load_protocol
|
||||
from ml_porosity.benchmark.runner import run, status
|
||||
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("stages", nargs="+", choices=STAGES)
|
||||
ap.add_argument("--studies", nargs="+", default=["S1", "S2", "S3", "S4", "S8"], choices=["S1", "S2", "S3", "S4", "S8"])
|
||||
ap.add_argument("--device", default="cuda:0")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--threads", type=int, default=int(os.environ.get("THREADS", "2")))
|
||||
ap.add_argument("--gpu-mem-gb", type=float, default=6.0, help="per-worker CUDA allocation cap for the SMC (GiB)")
|
||||
ap.add_argument("--dev", action="store_true", help="dev realizations only → outputs/bench/dev")
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=None)
|
||||
ap.add_argument("--regimes", nargs="+", default=None)
|
||||
ap.add_argument("--presets", nargs="+", default=None, help="S2 presets to run (default: all main presets)")
|
||||
ap.add_argument("--controls", action="store_true", help="S2: also the control presets rp_C, wv_C")
|
||||
ap.add_argument("--seeds", type=int, nargs="+", default=None, help="dev only: network seeds (default: protocol)")
|
||||
ap.add_argument("--drift", type=float, nargs="+", default=None, help="dev only: drift factors c (overrides the study grid)")
|
||||
ap.add_argument("--n-train", type=int, nargs="+", default=None, help="dev only: N (overrides the study grid)")
|
||||
ap.add_argument("--n-boot", type=int, default=2000)
|
||||
args = ap.parse_args()
|
||||
if args.workers < 1:
|
||||
ap.error("--workers must be positive")
|
||||
if (args.seeds or args.drift or args.n_train) and not args.dev:
|
||||
ap.error("--seeds, --drift and --n-train are dev options")
|
||||
grid = {"drift_factors": args.drift, "n_train": args.n_train} if (args.drift or args.n_train) else None
|
||||
p = load_protocol()
|
||||
mode = "dev" if args.dev else "main"
|
||||
stages = ["posterior", "train", "summarize"] if args.stages == ["all"] else args.stages
|
||||
try:
|
||||
for stage in stages:
|
||||
if stage == "status":
|
||||
print(status(bench_root(dev=args.dev)))
|
||||
elif stage == "lock":
|
||||
print(freeze())
|
||||
elif stage in ("posterior", "train"):
|
||||
run(stage, p, args.studies, args.device, args.workers, args.gpu_mem_gb, args.threads, mode, rids=args.rids,
|
||||
regimes=args.regimes, presets=args.presets, controls=args.controls, seeds=args.seeds, grid=grid)
|
||||
elif stage == "repro":
|
||||
from ml_porosity.benchmark.repro import compare
|
||||
for st in ("posterior", "train"):
|
||||
run(st, p, [], args.device, 1, args.gpu_mem_gb, args.threads, "repro")
|
||||
print(compare(p))
|
||||
elif stage == "summarize":
|
||||
from ml_porosity.benchmark.summary import summarize
|
||||
summarize(p, bench_root(dev=args.dev), args.n_boot, dev=args.dev)
|
||||
elif stage == "dev-budgets":
|
||||
from ml_porosity.benchmark.devbudgets import dev_budgets
|
||||
print(dev_budgets(p, args.device, args.workers, args.gpu_mem_gb, args.threads, rids=args.rids))
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
135
scripts/35_bench_calibration.py
Normal file
135
scripts/35_bench_calibration.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""S2 level calibration table (phase P6, protocol_bench): tabulate the dev SMC diagnostics of every candidate preset.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/35_bench_calibration.py [--rids 902 903 904 905] [--out outputs/bench/dev]
|
||||
|
||||
Reads outputs/bench/dev/smc_qc_rid<rid>.json (scripts/33 --smc: N = 4, c = 1, R10 and Rm5, P = 1024, estR, γ = 1/κ,
|
||||
single-checkpoint SMC) and outputs/bench/dev/generator_qc.json / generator_sweep.json (in-family model error), and
|
||||
writes calibration.csv (one row per preset × regime, mean over the listed realizations and wells) and calibration.md.
|
||||
Columns: in-family model error (relative RMS; ratio to the regime noise), SMC warp RMSE, coverage90, σ_post
|
||||
(width90/3.29), overconfidence (warp RMSE / σ_post), phase_R, |phase_R − phase0|, B3c and B3d warp RMSE, r_post,
|
||||
and the declared L1/L2 targets of configs/protocol_bench.yaml calibration.procedure. Dev only; no main realization.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
|
||||
NOISE = {"R10": 10 ** (-10 / 20), "Rm5": 10 ** (5 / 20), "R0": 1.0} # relative noise RMS of the regimes
|
||||
Z90 = 3.29
|
||||
|
||||
|
||||
def in_family_errors(out: Path) -> dict[str, float]:
|
||||
"""Best in-family model error keyed by the json of the active knobs (generator_qc.json presets, the nominal entry
|
||||
and the single-knob rows of generator_sweep.json when they carry a spec/active block)."""
|
||||
from ml_porosity.data.synth_d2 import active_axes, normalize_misspec
|
||||
|
||||
err = {}
|
||||
f = out / "generator_qc.json"
|
||||
if f.exists():
|
||||
q = json.loads(f.read_text())
|
||||
err["{}"] = float(q["nominal"]["model_err_in_family"]["err_mean"])
|
||||
for d in q.get("presets", {}).values():
|
||||
if "active" in d and "model_err_in_family" in d:
|
||||
err[json.dumps(d["active"], sort_keys=True)] = float(d["model_err_in_family"]["err_mean"])
|
||||
f = out / "generator_sweep.json"
|
||||
if f.exists():
|
||||
for r in json.loads(f.read_text()).get("rows", []):
|
||||
if "model_err_in_family" not in r:
|
||||
continue
|
||||
act = r.get("active")
|
||||
if act is None and "spec" in r:
|
||||
act = active_axes(normalize_misspec({k: v for k, v in r["spec"].items() if k != "note"}))
|
||||
if act is None and {"axis", "key", "value"} <= set(r):
|
||||
act = active_axes(normalize_misspec({r["axis"]: {r["key"]: r["value"]}}))
|
||||
if act is not None:
|
||||
e = r["model_err_in_family"]
|
||||
err.setdefault(json.dumps(act, sort_keys=True), float(e["err_mean"] if isinstance(e, dict) else e))
|
||||
return err
|
||||
|
||||
|
||||
def load_smc(out: Path, rids: list[int]) -> pd.DataFrame:
|
||||
rows = []
|
||||
for rid in rids:
|
||||
f = out / f"smc_qc_rid{rid}.json"
|
||||
if not f.exists():
|
||||
continue
|
||||
q = json.loads(f.read_text())
|
||||
for regime, presets in q.items():
|
||||
if regime == "meta":
|
||||
continue
|
||||
for name, r in presets.items():
|
||||
m = r["mean"]
|
||||
rows.append({"rid": rid, "regime": regime, "preset": name, "phase0": r["phase0"], "phase_R": r["phase_R"],
|
||||
"dphase": abs(r["phase_R"] - r["phase0"]), "phase_edge": r["phase_edge"],
|
||||
"smc_warp_rmse_ms": m["SMC_warp_rmse_ms"], "cov90": m["SMC_warp_cov90"],
|
||||
"sigma_post_ms": m["SMC_warp_width90_ms"] / Z90, "r_post": m["r_post"], "kappa_post": m["kappa_post"],
|
||||
"b3c_warp_rmse_ms": m["B3c_warp_rmse_ms"], "b3d_warp_rmse_ms": m["B3d_warp_rmse_ms"],
|
||||
"lam": r["lam"], "time_s": sum(r["time_s"].values()), "active": json.dumps(r.get("active", {}), sort_keys=True)})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=[902, 903, 904, 905])
|
||||
ap.add_argument("--out", type=Path, default=REPO_ROOT / "outputs" / "bench" / "dev")
|
||||
a = ap.parse_args()
|
||||
if any(r < 900 for r in a.rids):
|
||||
raise SystemExit("dev realizations only")
|
||||
df = load_smc(a.out, a.rids)
|
||||
if df.empty:
|
||||
raise SystemExit("no smc_qc_rid*.json found")
|
||||
err = in_family_errors(a.out)
|
||||
cfg = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_bench.yaml").read_text())
|
||||
presets = cfg["misspec_presets"]
|
||||
# Rows are identified by their active knobs, not by the name stored in the json: preset names were redefined on
|
||||
# 29/10 (e.g. wv_L1 was minphase 1.0 on rid 902 and is minphase 0.5 now). Main-preset names win, then cand_*.
|
||||
from ml_porosity.data.synth_d2 import active_axes, normalize_misspec, preset_misspec
|
||||
main = [n for n in presets if not n.startswith("cand_")]
|
||||
by_active = {}
|
||||
for n in main + [n for n in presets if n.startswith("cand_")]:
|
||||
by_active.setdefault(json.dumps(active_axes(normalize_misspec(preset_misspec(cfg, n))), sort_keys=True), n)
|
||||
df["stored_name"] = df.preset
|
||||
df["preset"] = [("nominal" if a == "{}" else by_active.get(a, f"{n} (old definition)")) for a, n in zip(df.active, df.stored_name)]
|
||||
df = df.drop_duplicates(["rid", "regime", "active"]) # the same knobs run twice on one rid under two names
|
||||
df["overconfidence"] = df.smc_warp_rmse_ms / df.sigma_post_ms
|
||||
nom = df[df.preset == "nominal"].set_index(["rid", "regime"])
|
||||
df = df.join(nom[["smc_warp_rmse_ms", "cov90", "sigma_post_ms"]].rename(columns=lambda c: c + "_nom"), on=["rid", "regime"])
|
||||
df["warp_rmse_ratio_to_nominal"] = df.smc_warp_rmse_ms / df.smc_warp_rmse_ms_nom
|
||||
df["smc_beats_b3c"] = df.smc_warp_rmse_ms < df.b3c_warp_rmse_ms
|
||||
agg = df.groupby(["preset", "regime", "active"]).agg(n_rid=("rid", "nunique"), smc_warp_rmse_ms=("smc_warp_rmse_ms", "mean"),
|
||||
ratio_to_nominal=("warp_rmse_ratio_to_nominal", "mean"), cov90=("cov90", "mean"),
|
||||
sigma_post_ms=("sigma_post_ms", "mean"), overconfidence=("overconfidence", "mean"),
|
||||
dphase_deg=("dphase", "mean"), phase_R=("phase_R", "mean"),
|
||||
b3c_warp_rmse_ms=("b3c_warp_rmse_ms", "mean"), b3d_warp_rmse_ms=("b3d_warp_rmse_ms", "mean"),
|
||||
smc_beats_b3c_frac=("smc_beats_b3c", "mean"), r_post=("r_post", "mean"),
|
||||
time_s=("time_s", "mean")).reset_index()
|
||||
agg["in_family_err"] = agg.active.map(lambda a: err.get(a, np.nan))
|
||||
agg["err_over_noise"] = agg.in_family_err / agg.regime.map(NOISE)
|
||||
agg["note"] = agg.preset.map(lambda n: presets.get(n, {}).get("note", "nominal" if n == "nominal" else ""))
|
||||
agg["axis"] = agg.preset.map(lambda n: "nominal" if n == "nominal" else next((p for p in n.split("_") if p in ("rp", "wv", "dr")), "?"))
|
||||
agg = agg.sort_values(["regime", "axis", "preset"]).reset_index(drop=True)
|
||||
agg.to_csv(a.out / "calibration.csv", index=False)
|
||||
cols = ["regime", "axis", "preset", "active", "n_rid", "in_family_err", "err_over_noise", "smc_warp_rmse_ms", "ratio_to_nominal", "cov90",
|
||||
"sigma_post_ms", "overconfidence", "dphase_deg", "b3c_warp_rmse_ms", "smc_beats_b3c_frac", "r_post"]
|
||||
L = ["# S2 level calibration (dev; N = 4, c = 1, P = 1024, estR, γ = 1/κ; single-checkpoint SMC of scripts/33)", "",
|
||||
f"Realizations: {sorted(df.rid.unique().tolist())}. Means over realizations × 4 train wells. in_family_err from generator_qc.json "
|
||||
"(rid 902; NaN for presets without a light-QC entry). Declared targets (protocol calibration.procedure): L1 — err/noise(R10) "
|
||||
"0.5–1.0 and SMC still ahead of B3c at R10; L2 — err/noise(R10) 1.5–2 with coverage90 < 0.5 at R10 or warp RMSE ≥ 2 × nominal.", "",
|
||||
agg[cols].to_markdown(index=False, floatfmt=".3f"), "", "## Per realization", "",
|
||||
df[["rid", "regime", "preset", "stored_name", "smc_warp_rmse_ms", "cov90", "sigma_post_ms", "dphase", "b3c_warp_rmse_ms", "r_post"]]
|
||||
.sort_values(["regime", "preset", "rid"]).to_markdown(index=False, floatfmt=".3f"), ""]
|
||||
(a.out / "calibration.md").write_text("\n".join(L))
|
||||
pd.set_option("display.width", 250)
|
||||
print(agg[cols].round(3).to_string())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
41
scripts/run_bench.sh
Executable file
41
scripts/run_bench.sh
Executable file
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# protocol_bench (configs/protocol_bench.yaml) driver on the Linux GPU server: every stage is wrapped by
|
||||
# ml_porosity.runlog (logs/runs/<ts>_bench_<stage>/, logs/index.csv) and is restartable (completed jobs are skipped
|
||||
# by fingerprint and checksum). Long runs: detach with `setsid nohup scripts/run_bench.sh ... > logs/bench_<x>.out 2>&1 &`.
|
||||
# scripts/run_bench.sh lock # first lock (after the review of the draft)
|
||||
# STUDIES="S1" DEVICE=cuda:0 WORKERS=4 scripts/run_bench.sh posterior train
|
||||
# STUDIES="S3 S4 S8" DEVICE=cuda:1 scripts/run_bench.sh train
|
||||
# scripts/run_bench.sh summarize | status | repro
|
||||
# DEV=1 RIDS="902 903" STUDIES="S2" PRESETS="rp_L1 wv_L1" scripts/run_bench.sh posterior train # dev (never a result)
|
||||
# Env: DEVICE (default cuda:0), WORKERS (4), THREADS per worker (2), MEM_GB per SMC worker (6), STUDIES, REGIMES,
|
||||
# PRESETS, RIDS, DEV (1 → --dev), CONTROLS (1 → S2 controls), EXTRA (extra arguments).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
DEVICE="${DEVICE:-cuda:0}"
|
||||
WORKERS="${WORKERS:-4}"
|
||||
THREADS="${THREADS:-2}"
|
||||
MEM_GB="${MEM_GB:-6}"
|
||||
STUDIES="${STUDIES:-S1 S2 S3 S4 S8}"
|
||||
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
|
||||
NUMBA_NUM_THREADS=$THREADS PYTHONHASHSEED=0 PYTHONUTF8=1 CUBLAS_WORKSPACE_CONFIG=:4096:8
|
||||
args=(--device "$DEVICE" --workers "$WORKERS" --threads "$THREADS" --gpu-mem-gb "$MEM_GB")
|
||||
# shellcheck disable=SC2206
|
||||
args+=(--studies $STUDIES)
|
||||
[[ -n "${REGIMES:-}" ]] && args+=(--regimes $REGIMES)
|
||||
[[ -n "${PRESETS:-}" ]] && args+=(--presets $PRESETS)
|
||||
[[ -n "${RIDS:-}" ]] && args+=(--rids $RIDS)
|
||||
[[ "${DEV:-0}" == "1" ]] && args+=(--dev)
|
||||
[[ "${CONTROLS:-0}" == "1" ]] && args+=(--controls)
|
||||
[[ -n "${EXTRA:-}" ]] && args+=($EXTRA)
|
||||
tag="$(echo "$STUDIES" | tr ' ' '+')"
|
||||
[[ "${DEV:-0}" == "1" ]] && tag="dev_$tag"
|
||||
for stage in "${@:-status}"; do
|
||||
case "$stage" in
|
||||
status|lock|summarize|repro)
|
||||
"$PY" -m ml_porosity.runlog -n "bench_${stage}" -- "$PY" scripts/34_run_bench.py "$stage" "${args[@]}" ;;
|
||||
posterior|train|dev-budgets)
|
||||
"$PY" -m ml_porosity.runlog -n "bench_${stage}_${tag}_${DEVICE//:/}" -- "$PY" scripts/34_run_bench.py "$stage" "${args[@]}" ;;
|
||||
*) echo "unknown stage: $stage" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
127
tests/data/d2_fingerprints.json
Normal file
127
tests/data/d2_fingerprints.json
Normal file
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"meta": {
|
||||
"created": "2026-10-29",
|
||||
"purpose": "SHA-256 fingerprints of the D2 default path before misspecification parameters were added (phase P6, item p6-gen); recomputed by tests/test_d2_misspec.py",
|
||||
"generator": "ml_porosity/data/synth_d2.py at commit 0cfe202",
|
||||
"inputs": {
|
||||
"d2_config": "57b676f0fc569ebe44f6253426fe42a218fb06272323b949932e9f8d597ff0d3",
|
||||
"warp_prior": "55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27",
|
||||
"wavelet": "b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64"
|
||||
},
|
||||
"input_paths": {
|
||||
"d2_config": "configs/d2_synth_p2r.yaml",
|
||||
"warp_prior": "outputs/p2/warp_prior_f3.json",
|
||||
"wavelet": "outputs/wavelets.npz"
|
||||
},
|
||||
"warp_prior_fit": "matern32",
|
||||
"wavelet_key": "statistical",
|
||||
"rids": [
|
||||
900,
|
||||
8,
|
||||
902
|
||||
],
|
||||
"drift_factors": [
|
||||
0.0,
|
||||
1.0,
|
||||
2.0
|
||||
],
|
||||
"snr_db": 10,
|
||||
"sigma_a_ms": 7.0,
|
||||
"anchor_density": "full",
|
||||
"obs_wells": "8 test wells + first 4 pool wells, concatenated over drift factors then wells",
|
||||
"well_fields": [
|
||||
"seis_clean",
|
||||
"noise_unit",
|
||||
"phi_t",
|
||||
"z_g",
|
||||
"z_b",
|
||||
"boundaries_t",
|
||||
"eps_a"
|
||||
],
|
||||
"obs_keys": [
|
||||
"seis",
|
||||
"phi_log",
|
||||
"ai_log",
|
||||
"tau_k",
|
||||
"t_k",
|
||||
"b",
|
||||
"g",
|
||||
"t_of_tau_true",
|
||||
"y_true"
|
||||
],
|
||||
"env": {
|
||||
"numpy": "2.5.4",
|
||||
"scipy": "1.18.1",
|
||||
"python": "3.13.15",
|
||||
"platform": "Linux-6.8.0-136-generic-x86_64-with-glibc2.39"
|
||||
}
|
||||
},
|
||||
"realizations": {
|
||||
"900": {
|
||||
"wells": {
|
||||
"seis_clean": "e460372264253280218c769a4b2f65f4b531f3142fee5d5b595e90b5ee04914f",
|
||||
"noise_unit": "259ccc2614faeab0d496f0e17605105990ecfe4d26a512148e1aa3829ea64a54",
|
||||
"phi_t": "b07358ee2077dc844c995588966e7d539d007dd5315e24b7e0702dbdf59639ab",
|
||||
"z_g": "d42a6e15f2f13715b0adb65dadc4a26b1e15bf8cb82053c9148ae7abd6f1e61d",
|
||||
"z_b": "dcebebc51a5356182578dfe37f3957e8f84cf5b8bd1c0c419faa3d221eceb52e",
|
||||
"boundaries_t": "093d53cd27316aa07fb1e3c93b3fd080a228dd18071abaf380e23bf8b0622108",
|
||||
"eps_a": "5a3d87cdbace9cbeb6ca7884c6f55511c80506964099e2a2e28deac0e36503b3"
|
||||
},
|
||||
"obs": {
|
||||
"seis": "b096fac64e04ce61bcc8cf22bfe7d65538ba2a060b42e53fb236a52dbc5a7c78",
|
||||
"phi_log": "734bc3e4926415b40c3fd4127ba3e064be9ff139ebe3e08e7181bd90bc573956",
|
||||
"ai_log": "3204dbd982535fc9a5668156b57c44065dbc9cae20cc8027c8a448f5b62fa0e0",
|
||||
"tau_k": "35e971e2cd0a052ea99758c5409b9368c0e152f0eb7143f4a225945bdc0c8ffd",
|
||||
"t_k": "1cbb0f63cbebe841f393f03a4b44f0a736f3c442729e140ca82c1c0d2263ed61",
|
||||
"b": "288fdad9c7bb60b647c2d32f0db339e1158c53c6cfa6b9de9c114dbd4aa73e4d",
|
||||
"g": "50e489f199452348585a232b688037c76a3176fa311f1315d23d0ff1aec45075",
|
||||
"t_of_tau_true": "8615f79f1c306ce46ace0dbaf5e3d449d3ac25eadf97645492742ea422f90deb",
|
||||
"y_true": "9a96e7ff339bd6eff9cc113217679dc365e5d8116901972a6ad940ae92b10471"
|
||||
}
|
||||
},
|
||||
"8": {
|
||||
"wells": {
|
||||
"seis_clean": "cfca2356612b93197b614b4e3d5154fa4bae1586375fbc25280591edb5384ad0",
|
||||
"noise_unit": "a3aa075dc0eb79991380748b0ebff93d44f3821f6f42405b6f898299e07eab60",
|
||||
"phi_t": "802a7cd4da3ab63031ea7c1979d9b6e84a0d9c7ac7cd31940435fcbd62a250cc",
|
||||
"z_g": "65024e6ca2ae9dff122e16bc4f957e17d0844ebfbc260d5c0fde49c7cd619ada",
|
||||
"z_b": "e1653c27d05bdc055912e9bda3488b6cc735c30cd04e4d85a5efbc9f4f917d6c",
|
||||
"boundaries_t": "f407b1a729abda7a6acb7c22ece5e834c56afd72d87ece179482833d69b172f8",
|
||||
"eps_a": "da3cdea0869cbfd9f2c7a2d3d2f5ed789118df8ec87dfcda37661dc27a40b32e"
|
||||
},
|
||||
"obs": {
|
||||
"seis": "205947a1e5443da066c8e292255724def0d62d81bb22e2197a538461c5d2e3d4",
|
||||
"phi_log": "fa9bf941a520d2b8f213e27f0fcec14bef81fc64112dbbe969c9a29b7d4654b4",
|
||||
"ai_log": "9fd476bb875b5482c2f38f38c9cb5232d6cf503d16d7e37daec1c110880b8009",
|
||||
"tau_k": "00e51672611fc3b6672d0c6acdf484a025a999114fd5fc785c3d2ba2af8c745b",
|
||||
"t_k": "96e9393d77ec22f68c6d02bf8f9faf2405ed747b1f2318c0ce7f776b65fec057",
|
||||
"b": "0755adab47cbc6a08adaddecc3de50b2829dae738d63659040b86138fd1e17c8",
|
||||
"g": "7b1de59ada788bc7815b2c43e39b41d37475dd85c10f5dae5b0ac97f1437267c",
|
||||
"t_of_tau_true": "17264af616441713e0dba664b09ba03739fc7a06608a19ea0fd1787f63f5476d",
|
||||
"y_true": "44a8b5d80d0f5e5ebd2fa554ce032c174535a31677834bbd7763c7fbb3bd4417"
|
||||
}
|
||||
},
|
||||
"902": {
|
||||
"wells": {
|
||||
"seis_clean": "5f3534d09866d3703ae30e7d08d6debf359d0cec1ac0bd03badf0e1002db148c",
|
||||
"noise_unit": "7fc3986dee0a0b613879bf2074702429e266ad0cce0d819ac742b4704f1ba009",
|
||||
"phi_t": "e880ed13dcdf17c783acfd03bcf70403e15ac2ddc3c081bcb804f49df42ce724",
|
||||
"z_g": "d2b4e0551a08eb304f034c3289b68b85429c0b1518d98cd2c6d98cdee6f4714f",
|
||||
"z_b": "228ca890c469b1adfd0c2ceb26dfcc966fa08da2aaf7d60916419bf33b4e5d1d",
|
||||
"boundaries_t": "0c5e18d68c4d4d1f1c71e170edc7f2e80c6ab425ccc2b5e98e42207a8cb3d6e2",
|
||||
"eps_a": "7d640af84c68b56a6ce3446fcdd07ae6847b0aeedf80c18e73f7b7117a667451"
|
||||
},
|
||||
"obs": {
|
||||
"seis": "68203f9a4ff5c6a21f30227c997f6d7cf496058dfffe6fa257a57235c70c8013",
|
||||
"phi_log": "b2ba9800e47bc362bdbb1ea2d6afee208289d8972edefae7ff5f0f2a6615e039",
|
||||
"ai_log": "3467e34f9d9f4d649b6ae472dd91a8f505df2dc4a4b3e4ff6b71d3d0d6a8c641",
|
||||
"tau_k": "11d9bb79da9ae6ee0ccac5abde6508bd4c41ea180cfa9e304f8ad33274373e34",
|
||||
"t_k": "2eeebb99fb6725ef91bcbab55d5bedc9cac8c75339c7468a7bedcf8d1cc2efbe",
|
||||
"b": "edaf277378cd1bceb33e7eff98ad4f8738592af7522161b9f40c889b09b9ba91",
|
||||
"g": "65cb230013ccbf845128af85e871c126f1b9a3035ef13cecce37b0116c8170d1",
|
||||
"t_of_tau_true": "870ee33b8ccfdce32beb7117bfa4da65396987d775ecaa5e8a3b10aab58e0dc4",
|
||||
"y_true": "33bcedc3461259c7ab62e24e180d2eac78884c16cd7ad2e707104cbbd8981682"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
189
tests/test_bench.py
Normal file
189
tests/test_bench.py
Normal file
@@ -0,0 +1,189 @@
|
||||
"""protocol_bench runner: protocol consistency, cell enumeration, guards, TCN path, S8 two-mode banks, summary rules.
|
||||
|
||||
No GPU and no main-grid realization is touched; the generator-dependent tests skip when the D2 inputs are missing.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
import torch
|
||||
import yaml
|
||||
|
||||
from ml_porosity.benchmark import cells as C
|
||||
from ml_porosity.benchmark import protocol as PR
|
||||
from ml_porosity.paths import REPO_ROOT, f3_root
|
||||
|
||||
P = yaml.safe_load((REPO_ROOT / "configs" / "protocol_bench.yaml").read_text(encoding="utf-8"))
|
||||
GEN = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text(encoding="utf-8"))
|
||||
NEEDED = [f3_root() / ".survey", REPO_ROOT / GEN["horizon_cache"], REPO_ROOT / P["inputs"]["warp_prior"]["path"],
|
||||
REPO_ROOT / P["inputs"]["wavelet"]["path"]]
|
||||
needs_inputs = pytest.mark.skipif(not all(f.exists() for f in NEEDED), reason="missing D2 inputs")
|
||||
|
||||
|
||||
def test_protocol_consistency():
|
||||
presets = GEN["misspec_presets"]
|
||||
s2 = P["studies"]["S2"]
|
||||
for names in s2["presets"].values():
|
||||
assert all(n in presets for n in names), names
|
||||
assert all(n in presets for n in s2["controls"]["presets"])
|
||||
for s in P["studies"].values():
|
||||
for m in s["methods"]:
|
||||
assert m in P["training"]["budgets"], m
|
||||
assert set(P["grid"]["regimes"]) == set(GEN["regimes"])
|
||||
assert not set(P["grid"]["realizations"]) & set(P["grid"]["dev_realizations"])
|
||||
p2 = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text(encoding="utf-8"))
|
||||
assert not set(P["grid"]["realizations"]) & set(p2["grid"]["realizations"])
|
||||
p2r = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2r.yaml").read_text(encoding="utf-8"))
|
||||
assert P["grid"]["realizations"] == p2r["grid"]["realizations"]
|
||||
for m in ("Oracle", "B3b", "B3c", "B3c-R", "B3d", "B3d-Sa", "M2-Sa"):
|
||||
assert P["training"]["budgets"][m] == p2r["training"]["budgets"][m], m
|
||||
for m in ("B4a", "B4b", "B4c", "B4d"):
|
||||
assert P["training"]["budgets"][m] == p2["training"]["budgets"][m], m
|
||||
for k, h in P["hypotheses"].items():
|
||||
assert h["kind"] in ("claim", "descriptive", "disclosed"), k
|
||||
assert h.get("statement") or h.get("items"), k
|
||||
|
||||
|
||||
def test_cell_counts_and_uniqueness():
|
||||
counts = {"S1": 560, "S2": 224, "S3": 240, "S4": 48, "S8": 96}
|
||||
for s, n in counts.items():
|
||||
cs = C.study_cells(P, s)
|
||||
assert len(cs) == n, (s, len(cs))
|
||||
assert len(set((c.setting, c.tag, c.backbone) for c in cs)) == n
|
||||
s1 = C.study_cells(P, "S1")
|
||||
assert not any(c.c in (0, 1, 2) and c.n_train in (4, 16) for c in s1) # P2r cells are read, not recomputed
|
||||
assert sum(C.needs_posterior(c) for c in C.study_cells(P, "S3")) == 0 and all(c.posterior == "p2r" for c in C.study_cells(P, "S3"))
|
||||
assert all(c.posterior == "p2r" and c.backbone == "tcn" for c in C.study_cells(P, "S4"))
|
||||
assert sorted(set(c.delta_ms for c in C.study_cells(P, "S8"))) == [8.0, 16.0, 32.0]
|
||||
assert len(C.study_cells(P, "S2", controls=True)) == 224 + 32
|
||||
dev = C.study_cells(P, "S1", rids=[902], regimes=["R10"], grid={"drift_factors": [1.0], "n_train": [4]})
|
||||
assert len(dev) == 1 and dev[0].tag == "r902_c1_n4"
|
||||
|
||||
|
||||
def test_paths_shared_posterior_and_flat_names(tmp_path):
|
||||
a = C.Cell("S1", "R10", None, 1.0, 4, 902, ("Oracle",))
|
||||
b = C.Cell("S4", "R10", None, 1.0, 4, 902, ("Oracle",), backbone="tcn", posterior="bench")
|
||||
assert C.posterior_paths(a, tmp_path, 0)["particles"] == C.posterior_paths(b, tmp_path, 0)["particles"]
|
||||
assert C.posterior_paths(a, tmp_path, 0)["particles"].name == "r902_c1_n4_s0_particles.npz"
|
||||
assert C.train_paths(b, tmp_path)["csv"].name == "r902_c1_n4__tcn.csv"
|
||||
s8 = C.Cell("S8", "Rm5", None, 1.0, 16, 8, ("PM2",), posterior="none", delta_ms=32.0)
|
||||
assert C.posterior_dir(s8, tmp_path) is None and s8.tag == "r8_c1_n16_d32"
|
||||
s2 = C.Cell("S2", "R10", "wv_L1", 1.0, 16, 8, ("Oracle",))
|
||||
assert s2.setting == "R10__wv_L1"
|
||||
|
||||
|
||||
def test_guards():
|
||||
for rids, dev in (([0], True), ([3], False), ([8, 902], True), ([902], False), ([8], True), ([77], True)):
|
||||
with pytest.raises(SystemExit):
|
||||
PR.check_rids(rids, P, dev=dev)
|
||||
PR.check_rids([902, 905], P, dev=True)
|
||||
PR.check_rids([P["reproduction"]["rid"]], P, dev=False, repro=True)
|
||||
with pytest.raises(SystemExit):
|
||||
PR.check_rids([9], P, dev=False, repro=True)
|
||||
if not PR.LOCK.exists():
|
||||
with pytest.raises(RuntimeError):
|
||||
PR.check_rids([8], P, dev=False)
|
||||
|
||||
|
||||
def test_fingerprint_depends_on_settings():
|
||||
st = {"protocol_sha256": "x", "dev": True}
|
||||
assert PR.fingerprint(st, stage="train", rid=8) != PR.fingerprint(st, stage="train", rid=9)
|
||||
assert PR.fingerprint(st, a=1, b=2) == PR.fingerprint(st, b=2, a=1)
|
||||
|
||||
|
||||
def test_tcn_training_path_runs_on_cpu():
|
||||
from ml_porosity.benchmark.training import train_predict_tcn
|
||||
|
||||
rng = np.random.default_rng(0)
|
||||
X, Xte = rng.normal(size=(3, 9, 126)).astype(np.float32), rng.normal(size=(2, 9, 126)).astype(np.float32)
|
||||
Y = rng.normal(size=(3, 2, 126)).astype(np.float32)
|
||||
spec = {"kind": "bank", "Y": Y, "logpi": np.full((3, 2), -np.log(2), np.float32), "lam": 0.5}
|
||||
cfg = {"d_channels": 8, "p_dropout": 0.0, "lr": 1e-3, "grad_clip": 5.0}
|
||||
out = train_predict_tcn(X, Xte, spec, cfg, 0, [2, 3], "cpu")
|
||||
assert set(out) == {2, 3} and out[3][0].shape == (2, 126) and np.all(out[3][1] > 0)
|
||||
out2 = train_predict_tcn(X, Xte, spec, cfg, 0, [3], "cpu")
|
||||
assert np.allclose(out[3][0], out2[3][0]) # same seed, same trajectory
|
||||
spec_h = spec | {"lam": None}
|
||||
assert train_predict_tcn(X, Xte, spec_h, cfg, 0, [2], "cpu")[2][0].shape == (2, 126)
|
||||
|
||||
|
||||
@needs_inputs
|
||||
def test_two_mode_banks_match_corollary_setup():
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.training import two_mode_banks
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
|
||||
inp = load_inputs(PR.load_protocol())
|
||||
R = inp.realization(902, None)
|
||||
obs, _ = inp.observe(R, 1.0, "R10", 4)
|
||||
diag = [{} for _ in obs]
|
||||
banks = two_mode_banks(R, obs, 32.0, diag)
|
||||
assert np.stack(banks["BK2"]).shape == (4, 2, len(R.t_main)) and np.stack(banks["PM2"]).shape == (4, 1, len(R.t_main))
|
||||
sides = [d["side"] for d in diag]
|
||||
assert set(sides) <= {-1, 1}
|
||||
for i, o in enumerate(obs):
|
||||
y_aa = antialias(o["phi_log"], R.cfg["fine_dt_ms"], R.dt)
|
||||
oracle = labels_for_warps(R.tau_fine, y_aa, o["t_of_tau_true"][None], R.t_main)[0]
|
||||
assert np.allclose(banks["BK2"][i][0], oracle) # the truth is a member of the bank
|
||||
assert 11.0 < diag[i]["PM2_warp_rmse_ms"] < 19.0 # mean warp off by Δ/2 in t, i.e. Δ/(2 e^g) in τ
|
||||
again = two_mode_banks(R, obs, 32.0, [{} for _ in obs])
|
||||
assert all(np.array_equal(a, b) for a, b in zip(banks["BK2"], again["BK2"])) # declared stream → deterministic
|
||||
|
||||
|
||||
@needs_inputs
|
||||
def test_dev_grid_override_and_nominal_fingerprint_helper():
|
||||
from ml_porosity.benchmark.data import fingerprint_realization, load_inputs
|
||||
|
||||
inp = load_inputs(PR.load_protocol())
|
||||
fp = fingerprint_realization(inp.realization(902, None))
|
||||
stored = json.loads((REPO_ROOT / P["inputs"]["fingerprints"]["path"]).read_text())["realizations"]["902"]
|
||||
assert fp["wells"]["z_g"] == stored["wells"]["z_g"]
|
||||
assert fp["obs"]["seis"] == stored["obs"]["seis"]
|
||||
|
||||
|
||||
def test_summary_rules_on_synthetic_runs():
|
||||
from ml_porosity.benchmark.summary import h2a_cells, pair
|
||||
|
||||
rng = np.random.default_rng(1)
|
||||
rows = []
|
||||
for rid, seed, N, m in itertools.product(range(8), range(5), (4, 16), ("B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa")):
|
||||
base = {"B3b": 1.0, "B3c": 0.8, "B3c-R": 0.82, "B3d-Sa": 0.6, "M2-Sa": 0.58}[m]
|
||||
rows.append({"rid": rid, "seed": seed, "c": 1.0, "n_train": N, "method": m, "band_rmse": base + 0.01 * rng.standard_normal(),
|
||||
"band_pcc": 0.9 - base / 10, "rmse": base, "pcc": 0.9})
|
||||
run = pd.DataFrame(rows)
|
||||
cells = h2a_cells(run, "B3d-Sa", ["B3b", "B3c", "B3c-R"], np.random.default_rng(0), 200)
|
||||
assert len(cells) == 2 and cells.cell_pass.all() and (cells.best == "B3c").all()
|
||||
pr = pair(run[run.n_train == 16], "M2-Sa", "B3d-Sa", np.random.default_rng(0), 200)
|
||||
assert pr["better"] and pr["ratio"] < 1 and pr["ratio_lo"] <= pr["ratio"] <= pr["ratio_hi"]
|
||||
|
||||
|
||||
@needs_inputs
|
||||
def test_control_gp_bank_matches_t2_construction():
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.training import control_gp_bank
|
||||
|
||||
inp = load_inputs(PR.load_protocol())
|
||||
R = inp.realization(902, None)
|
||||
obs, _ = inp.observe(R, 1.0, "R10", 2)
|
||||
rng = np.random.default_rng(3)
|
||||
smc = {}
|
||||
for o in obs: # synthetic "particles": smooth g, b ~ N(0, 3 ms); 256 of them
|
||||
g = 0.02 + 0.03 * np.cumsum(rng.standard_normal((256, R.grid.n)), 1) / np.sqrt(np.arange(1, R.grid.n + 1))
|
||||
smc[f"{o['name']}/estR/g_acf"] = np.column_stack([3 * rng.standard_normal(256), g]).astype(np.float32)
|
||||
diag = [{} for _ in obs]
|
||||
banks, logpi = control_gp_bank(R, obs, smc, inp.reg, 0, diag)
|
||||
assert np.stack(banks).shape == (2, inp.reg["S"], len(R.t_main)) and np.stack(logpi).shape == (2, inp.reg["S"])
|
||||
assert all(0.8 < d["Ctl-GP_sd_ratio"] < 1.2 for d in diag) and all(d["Ctl-GP_n_valid"] == inp.reg["S"] for d in diag)
|
||||
again, _ = control_gp_bank(R, obs, smc, inp.reg, 0, [{} for _ in obs])
|
||||
assert all(np.array_equal(a, b) for a, b in zip(banks, again))
|
||||
|
||||
|
||||
def test_budget_list_includes_equal_budget_arm():
|
||||
from ml_porosity.benchmark.training import budget_list, budget_of
|
||||
|
||||
assert budget_of(P, "B3d-Sa", "cnngru") == 250 and budget_list(P, "B3d-Sa", "cnngru") == sorted({250, P["training"]["equal_budget_arm"]})
|
||||
assert budget_list(P, "Oracle", "cnngru") == [500]
|
||||
assert budget_list(P, "B3b-TCN", "tcn")[0] == (P["training"].get("budgets_tcn") or {}).get("B3b", 125)
|
||||
294
tests/test_d2_misspec.py
Normal file
294
tests/test_d2_misspec.py
Normal file
@@ -0,0 +1,294 @@
|
||||
"""Misspecification parameters of the D2 generator (phase P6, item p6-gen; plan §12 item 22, decision 2).
|
||||
|
||||
The nominal path of ml_porosity/data/synth_d2.py must stay bit-identical to the generator used by protocol_p2 and
|
||||
protocol_p2r: tests/data/d2_fingerprints.json records SHA-256 fingerprints of the realization fields and of the
|
||||
observe() outputs, taken before the misspecification parameters were added. The other tests check that each axis
|
||||
changes only what it claims to change (common random numbers) and that the anchors stay consistent with the true warp.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import scipy
|
||||
import yaml
|
||||
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||||
from ml_porosity.paths import REPO_ROOT, f3_root
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
P = yaml.safe_load(open(REPO_ROOT / "configs" / "protocol_p2r.yaml"))
|
||||
INP = P["inputs"]
|
||||
CFG = yaml.safe_load(open(REPO_ROOT / INP["d2_config"]["path"]))
|
||||
FP_PATH = REPO_ROOT / "tests" / "data" / "d2_fingerprints.json"
|
||||
NEEDED = [f3_root() / ".survey", REPO_ROOT / CFG["horizon_cache"], REPO_ROOT / INP["warp_prior"]["path"],
|
||||
REPO_ROOT / INP["wavelet"]["path"]]
|
||||
pytestmark = pytest.mark.skipif(not all(p.exists() for p in NEEDED), reason="missing D2 inputs (run scripts/09, 10)")
|
||||
|
||||
WELL_FIELDS = ("seis_clean", "noise_unit", "phi_t", "z_g", "z_b", "boundaries_t", "eps_a")
|
||||
OBS_KEYS = ("seis", "phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true")
|
||||
FP_RIDS = (900, 8, 902) # P2/P2r dev, first P2r main realization, first bench dev realization
|
||||
FP_DRIFT = (0.0, 1.0, 2.0)
|
||||
FP_SNR_DB, FP_SIGMA_A, FP_DENSITY = 10, 7.0, "full"
|
||||
|
||||
|
||||
def _sha(chunks) -> str:
|
||||
h = hashlib.sha256()
|
||||
for a in chunks:
|
||||
h.update(np.ascontiguousarray(np.asarray(a)).tobytes())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def fingerprint_wells(R) -> dict:
|
||||
return {k: _sha(getattr(w, k) for w in R.wells) for k in WELL_FIELDS}
|
||||
|
||||
|
||||
def fingerprint_obs(R, **kw) -> dict:
|
||||
wells = R.test + R.pool[:4]
|
||||
obs = [R.observe(w, c, FP_SNR_DB, FP_SIGMA_A, FP_DENSITY, **kw) for c in FP_DRIFT for w in wells]
|
||||
return {k: _sha(o[k] for o in obs) for k in OBS_KEYS}
|
||||
|
||||
|
||||
def fingerprint(R, **kw) -> dict:
|
||||
return {"wells": fingerprint_wells(R), "obs": fingerprint_obs(R, **kw)}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def make():
|
||||
hg = load_horizon_grid(CFG["horizons"], REPO_ROOT / CFG["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / INP["warp_prior"]["path"]).read_text())["fits"][INP["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / INP["wavelet"]["path"])[INP["wavelet"]["key"]]
|
||||
return lambda rid, **kw: D2Realization(CFG, rid, hg, WarpHyper(**prior["hyper"]), wav, **kw)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def recorded() -> dict:
|
||||
fp = json.loads(FP_PATH.read_text())
|
||||
env = fp["meta"]["env"]
|
||||
if (env["numpy"], env["scipy"]) != (np.__version__, scipy.__version__):
|
||||
pytest.skip(f"fingerprints recorded with numpy {env['numpy']} / scipy {env['scipy']}; "
|
||||
f"this environment has {np.__version__} / {scipy.__version__}")
|
||||
return fp
|
||||
|
||||
|
||||
def test_inputs_match_fingerprint_record(recorded):
|
||||
for key in ("d2_config", "warp_prior", "wavelet"):
|
||||
f = REPO_ROOT / INP[key]["path"]
|
||||
assert hashlib.sha256(f.read_bytes()).hexdigest() == recorded["meta"]["inputs"][key], key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rid", FP_RIDS)
|
||||
def test_default_path_matches_fingerprints(make, recorded, rid):
|
||||
"""Realizations and observations are bit-identical to the record taken before the misspec parameters existed."""
|
||||
fp = fingerprint(make(rid))
|
||||
for part in ("wells", "obs"):
|
||||
for k, v in recorded["realizations"][str(rid)][part].items():
|
||||
assert fp[part][k] == v, f"rid {rid}: {part}.{k} changed"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- bench config and preset validation
|
||||
|
||||
BENCH = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_bench.yaml").read_text())
|
||||
|
||||
|
||||
def test_d2_bench_generator_matches_p2r():
|
||||
"""configs/d2_synth_bench.yaml uses the protocol_p2r generator and regimes: only misspec_presets may be added."""
|
||||
from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec
|
||||
|
||||
p2r = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_p2r.yaml").read_text())
|
||||
bench = dict(BENCH)
|
||||
presets = bench.pop("misspec_presets")
|
||||
assert bench == p2r
|
||||
assert preset_misspec(BENCH, None) is None and preset_misspec(BENCH, "nominal") is None
|
||||
for name in presets:
|
||||
ms = normalize_misspec(preset_misspec(BENCH, name))
|
||||
assert ms["rock_physics"]["region"] == "all"
|
||||
with pytest.raises(KeyError):
|
||||
preset_misspec(BENCH, "no_such_preset")
|
||||
|
||||
|
||||
def test_normalize_misspec_rejects_unknown_keys():
|
||||
from ml_porosity.data.synth_d2 import MISSPEC_DEFAULTS, active_axes, normalize_misspec
|
||||
|
||||
assert normalize_misspec(None) == normalize_misspec({}) == MISSPEC_DEFAULTS
|
||||
assert active_axes(normalize_misspec({"wavelet": {"Q": None, "Q_t_ref_ms": 500.0}})) == {}
|
||||
assert active_axes(normalize_misspec({"drift": {"step_ms": 4.0}})) == {"drift": {"step_ms": 4.0}}
|
||||
for bad in ({"rockphysics": {}}, {"wavelet": {"Q_factor": 2.0}}, {"drift": {"ell_factor": 0.0}},
|
||||
{"rock_physics": {"region": "train"}}, {"wavelet": {"minphase_frac": 1.5}}):
|
||||
with pytest.raises(ValueError):
|
||||
normalize_misspec(bad)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- common random numbers and axis semantics
|
||||
|
||||
RID = 902
|
||||
C, SNR, SIGMA_A = 1.0, 10, 7.0
|
||||
CRN_FIELDS = ("phi_t", "noise_unit", "z_g", "z_b", "boundaries_t", "eps_a")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def R0(make):
|
||||
return make(RID)
|
||||
|
||||
|
||||
def _assert_crn(R, R0):
|
||||
"""Earth model, noise and standard-normal draws identical to the nominal realization."""
|
||||
for a, b in zip(R.wells, R0.wells):
|
||||
assert (a.name, a.il, a.xl) == (b.name, b.il, b.xl)
|
||||
for k in CRN_FIELDS:
|
||||
np.testing.assert_array_equal(getattr(a, k), getattr(b, k))
|
||||
|
||||
|
||||
def test_all_nominal_misspec_is_bit_identical(make, R0):
|
||||
explicit = {"rock_physics": {"dt_slope_factor": 1.0, "region": "all"}, "wavelet": {"Q": None},
|
||||
"drift": {"sigma_b_factor": 1.0, "step_ms": 0.0, "jitter_sd_ms": 0.0}}
|
||||
R = make(RID, misspec=explicit)
|
||||
assert R.misspec_active == {} and R.w_fine is R.w_fine_nominal and R.drift_true is R.drift
|
||||
assert fingerprint(R) == fingerprint(R0)
|
||||
|
||||
|
||||
def test_rock_physics_changes_seismic_only(make, R0):
|
||||
R = make(RID, misspec={"rock_physics": {"dt_slope_factor": 1.15, "unit_dt_intercept_sd": 0.05}})
|
||||
_assert_crn(R, R0)
|
||||
for w, w0 in zip(R.wells, R0.wells):
|
||||
assert not np.allclose(w.seis_clean, w0.seis_clean)
|
||||
o, o0 = (r.observe(x, C, SNR, SIGMA_A) for r, x in ((R, w), (R0, w0)))
|
||||
for k in ("phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true"):
|
||||
np.testing.assert_array_equal(o[k], o0[k]) # labels, anchors, warp: unchanged
|
||||
ai_true = R.ai_log_true(w, o)
|
||||
assert ai_true.shape == o["ai_log"].shape and not np.allclose(ai_true, o["ai_log"])
|
||||
np.testing.assert_array_equal(R0.ai_log_true(w0, o0), o0["ai_log"])
|
||||
# region: the perturbation acts on the named wells only
|
||||
Rt = make(RID, misspec={"rock_physics": {"unit_dt_intercept_sd": 0.05, "region": "test"}})
|
||||
for w, w0 in zip(Rt.pool, R0.pool):
|
||||
np.testing.assert_array_equal(w.seis_clean, w0.seis_clean)
|
||||
assert not np.allclose(Rt.test[0].seis_clean, R0.test[0].seis_clean)
|
||||
assert Rt.rp_applies("T00") and not Rt.rp_applies("P00")
|
||||
|
||||
|
||||
def test_rock_physics_uniform_error_is_near_affine(make):
|
||||
"""Uniform coefficient errors change ln AI almost affinely in φ over the D2 porosity range (15–20 % coefficient
|
||||
errors: 4 % of ln AI, of which < 1 % of the ln AI range is non-affine), so the profiled amplitude of the tie
|
||||
likelihood absorbs them; this is why the rp_* presets add per-unit scatter."""
|
||||
from ml_porosity.data.synth_d2 import phi_to_ai
|
||||
|
||||
phi = np.linspace(0.2, 0.43, 200)
|
||||
R = make(RID, misspec={"rock_physics": {"dt_slope_factor": 1.15, "dt_intercept_factor": 1.15,
|
||||
"rho_slope_factor": 1.2}})
|
||||
d = np.log(R.phi_to_ai_true(phi)) - np.log(phi_to_ai(phi))
|
||||
resid = d - np.polyval(np.polyfit(phi, d, 1), phi)
|
||||
assert np.abs(d).max() > 0.02 and np.abs(resid).max() < 0.01 * np.ptp(np.log(phi_to_ai(phi)))
|
||||
|
||||
|
||||
def test_wavelet_axis_changes_seismic_only(make, R0):
|
||||
from ml_porosity.data.wavelet import rotate_phase
|
||||
|
||||
cases = {"phase": {"phase_deg": 45.0}, "minphase": {"minphase_frac": 1.0}, "peak": {"peak_freq_factor": 1.2},
|
||||
"delay": {"delay_ms": 4.0}, "Q": {"Q": 80.0}}
|
||||
phases = np.arange(-180.0, 180.0, 1.0)
|
||||
for name, wv in cases.items():
|
||||
R = make(RID, misspec={"wavelet": wv})
|
||||
_assert_crn(R, R0)
|
||||
w, w0 = R.pool[0], R0.pool[0]
|
||||
assert not np.allclose(w.seis_clean, w0.seis_clean), name
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
for k in ("phi_log", "ai_log", "tau_k", "t_k", "t_of_tau_true", "y_true"):
|
||||
np.testing.assert_array_equal(o[k], o0[k])
|
||||
if name == "Q":
|
||||
assert R.w_fine is R.w_fine_nominal # stationary part nominal; Q acts in the forward
|
||||
k600, k1100 = R.true_wavelet_at(600.0), R.true_wavelet_at(1100.0)
|
||||
spec = lambda k: np.abs(np.fft.rfft(k, 4096))
|
||||
f = np.fft.rfftfreq(4096, 0.0005)
|
||||
hi = f > 50
|
||||
assert (spec(k1100)[hi] / spec(k1100).max()).sum() < (spec(k600)[hi] / spec(k600).max()).sum()
|
||||
else:
|
||||
cc = [np.corrcoef(rotate_phase(R.w_fine_nominal, p), R.w_fine)[0, 1] for p in phases]
|
||||
best = phases[int(np.argmax(cc))]
|
||||
if name == "phase":
|
||||
assert abs(best - 45.0) <= 1.0 and max(cc) > 0.999 # inside the constant-phase family
|
||||
if name == "minphase":
|
||||
assert max(cc) < 0.9 # not representable by a constant phase
|
||||
assert len(R.wavelet) == len(R0.wavelet) and len(R.w_fine) == len(R0.w_fine)
|
||||
|
||||
|
||||
def test_minimum_phase_keeps_amplitude_spectrum(R0):
|
||||
from ml_porosity.data.synth_d2 import fractional_minimum_phase
|
||||
|
||||
w = R0.w_fine_nominal
|
||||
for frac in (0.0, 0.5, 1.0):
|
||||
y = fractional_minimum_phase(w, frac)
|
||||
a, b = np.abs(np.fft.rfft(w, 4096)), np.abs(np.fft.rfft(y, 4096))
|
||||
band = a > 0.1 * a.max() # truncation to 128 ms only touches the band edges
|
||||
assert np.abs(b[band] / a[band] - 1.0).max() < 0.05, frac
|
||||
assert abs(np.sum(y**2) / np.sum(w**2) - 1.0) < 0.01, frac
|
||||
np.testing.assert_allclose(fractional_minimum_phase(w, 0.0), w, atol=1e-9)
|
||||
|
||||
|
||||
def test_drift_hyper_factors_use_common_random_numbers(make, R0):
|
||||
R = make(RID, misspec={"drift": {"sigma_b_factor": 3.0, "sigma_g_factor": 1.5}})
|
||||
_assert_crn(R, R0)
|
||||
for w, w0 in zip(R.pool[:3], R0.pool[:3]):
|
||||
np.testing.assert_array_equal(w.seis_clean, w0.seis_clean) # the seismic is untouched
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
assert o["b"] == pytest.approx(3.0 * o0["b"])
|
||||
m = C * R.drift.m_g
|
||||
np.testing.assert_allclose(o["g"] - m, 1.5 * (o0["g"] - m), atol=1e-12)
|
||||
np.testing.assert_array_equal(o["t_k"], o0["t_k"]) # picks keep their noise draws
|
||||
np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9)
|
||||
Rl = make(RID, misspec={"drift": {"ell_factor": 0.5}})
|
||||
assert Rl.drift_true.ell_ms == pytest.approx(0.5 * R0.drift.ell_ms) and Rl.Lg_true is not Rl.Lg
|
||||
|
||||
|
||||
def test_drift_step_is_exact_jump_below_horizon(make, R0):
|
||||
J, width = 8.0, 12.0
|
||||
R = make(RID, misspec={"drift": {"step_ms": J, "step_width_ms": width}})
|
||||
_assert_crn(R, R0)
|
||||
k = CFG["horizons"].index("Truncation")
|
||||
for w, w0 in zip(R.wells, R0.wells):
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
d = o["t_of_tau_true"] - o0["t_of_tau_true"]
|
||||
t_h = R.hg.at(w.il, w.xl)[k]
|
||||
tau_h = np.interp(t_h, o0["t_of_tau_true"], R.tau_fine)
|
||||
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
np.testing.assert_allclose(d[R.tau_fine < tau_h - R.grid.dtau], 0.0, atol=1e-9)
|
||||
np.testing.assert_allclose(d[R.tau_fine > tau_h + width + 2 * R.grid.dtau], J, atol=1e-9)
|
||||
np.testing.assert_allclose(R.grid.t_of_tau(o["b"], o["g"])[0], R.true_warp_grid(w, C), atol=1e-9)
|
||||
np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9)
|
||||
assert o["b"] == o0["b"] and np.count_nonzero(o["g"] != o0["g"]) == int(round(width / R.grid.dtau))
|
||||
Rn = make(RID, misspec={"drift": {"step_ms": -6.0}})
|
||||
o = Rn.observe(Rn.pool[0], C, SNR, SIGMA_A)
|
||||
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
|
||||
|
||||
def test_drift_jitter_is_high_frequency_and_monotone(make, R0):
|
||||
sd, ell = 1.0, 8.0
|
||||
R = make(RID, misspec={"drift": {"jitter_sd_ms": sd, "jitter_ell_ms": ell}})
|
||||
_assert_crn(R, R0)
|
||||
rms = []
|
||||
for w, w0 in zip(R.wells, R0.wells):
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
d = o["t_of_tau_true"] - o0["t_of_tau_true"]
|
||||
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
np.testing.assert_array_equal(o["g"], o0["g"]) # jitter is not folded into g
|
||||
np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9)
|
||||
rms.append(np.sqrt(np.mean(d**2)))
|
||||
# decorrelates within a few ℓ: lag-40 ms autocorrelation small, lag-4 ms large
|
||||
g = np.interp(R.grid.tau, R.tau_fine, d)
|
||||
acf = lambda lag: np.corrcoef(g[:-lag], g[lag:])[0, 1]
|
||||
assert acf(1) > 0.5 and abs(acf(10)) < 0.4
|
||||
assert 0.5 * sd < np.mean(rms) < 1.5 * sd
|
||||
assert R.misspec_info["monotone_repairs"] == 0
|
||||
assert "z_jitter" in R.wells[0].extra and "z_jitter" not in R0.wells[0].extra
|
||||
|
||||
|
||||
def test_presets_build_and_report_active_axes(make, R0):
|
||||
from ml_porosity.data.synth_d2 import preset_misspec
|
||||
|
||||
for name in BENCH["misspec_presets"]:
|
||||
R = make(RID, misspec=preset_misspec(BENCH, name))
|
||||
_assert_crn(R, R0)
|
||||
axis = next(p for p in name.split("_") if p in ("rp", "wv", "dr")) # names: rp_L1, wv_Q, cand_dr_s, ...
|
||||
assert list(R.misspec_active) == [{"rp": "rock_physics", "wv": "wavelet", "dr": "drift"}[axis]]
|
||||
o = R.observe(R.pool[0], C, SNR, SIGMA_A)
|
||||
assert np.isfinite(o["seis"]).all() and np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
Reference in New Issue
Block a user