3 Commits

Author SHA1 Message Date
5a6fb2fc8c P2r main grid: runner, summary, results; close the P2r decision
- scripts/11: check_rids guard; scripts 14/15 accept the protocol_p2r main grid
  (realizations 8-15) only when protocol_p2r and its inputs match the locked SHA-256
- scripts/run_p2r_main.sh: per-regime pipelines (posterior then training) on cuda:0/cuda:1
- scripts/18_summarize_p2r.py: H2a / H2b / H3 / sigma_a verdicts per the locked rules
- docs/plan.md, report.html: H2a and H2b pass, sigma_a arm fails, no Pivot 1
- logs/index.csv: run records of the P2r grid

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:27:32 +00:00
f95123174f Rename protocol_p3 to protocol_p2r; close P2
protocol_p3 (cee2ff0) was the rerun of P2 on new realizations, not the
plan's phase P3 (F3 field). Renamed to P2r before any of realizations 8-15
was generated: protocol, D2 config, dev runner and summary script, output
dir outputs/p2/diag/p2rdev, tag protocol-p3 -> protocol-p2r. Protocol
content changes only names plus two notes in p2_outcome: the deviation from
protocol_p2's if_fail rule (pivot) and what the diagnosis did not test
(sigma_b, rock-physics stress). Re-locked: sha256 eb887311...

Docs: plan §12 item 12 and report section closing P2 (locked verdict kept,
diagnosis, decision, deviation, untested items, link to phase P3 / G-C).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:48:52 +00:00
cee2ff0859 P2 diagnosis on dev, P3 dev experiments, lock protocol_p3
- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:33 +00:00
86 changed files with 9323 additions and 462 deletions

3
.gitignore vendored
View File

@@ -16,6 +16,9 @@ __pycache__/
events.out.tfevents.* events.out.tfevents.*
outputs/ outputs/
# Log + runtime từng lần chạy (ml_porosity/runlog.py): log thô chỉ giữ cục bộ, logs/index.csv có thể commit
logs/runs/
# Repo lồng nhau (clone từ GitHub) và horizon rất lớn # Repo lồng nhau (clone từ GitHub) và horizon rất lớn
facies_classification_benchmark/ facies_classification_benchmark/
docs/*.pdf docs/*.pdf

View File

@@ -17,8 +17,24 @@ Dữ liệu F3 Demo 2023 đặt ở `data/F3_Demo_2023/F3_Demo_2023/`, dữ li
```bash ```bash
scripts/run_p0.sh # toàn bộ pipeline P0 và test scripts/run_p0.sh # toàn bộ pipeline P0 và test
scripts/run_p1.sh # P1: tie QC, LOWO baseline (khoảng 16 phút với GPU) scripts/run_p1.sh # P1: tie QC, LOWO baseline (khoảng 16 phút với GPU)
scripts/run_p2.sh # P2: prior warp F3, QC D2, test, lưới D2, H1, tổng hợp (GPU cuda:1; đổi bằng DEVICE=...)
scripts/run_p2r_dev.sh # chuẩn bị P2r (chạy lại P2) trên dev 900/901: screen, train, stability, sigma_a, f3, h3 (+ stability_m5, b3d_old, train_sa)
``` ```
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`:
```bash
scripts/runlog.sh scripts/15_diag_train.py --rids 900 901 --device cuda:1 # file .py chạy bằng .venv/bin/python
scripts/runlog.sh -n ten_rieng --note "ghi chú" -- <lệnh bất kỳ>
scripts/runlog.sh ls # các lần chạy gần nhất, cả lần đang chạy
```
`logs/runs/` không đẩy lên git; `logs/index.csv` thì có thể commit. Các dòng có `source=backfill` là lần chạy trước ngày 27/10/2026, dựng lại từ log còn lại và transcript (trường nào không đo được thì để trống). Chạy lại sau khi bị ngắt: `11_run_d2.py`, `14_diag_posterior.py`, `15_diag_train.py` bỏ qua các ô đã có CSV kết quả; `05_lowo.py` và `12_h1_blur.py` chạy lại từ đầu.
P2 theo `configs/protocol_p2.yaml` (khoá bằng `configs/protocol_p2.sha256`) và bộ sinh `configs/d2_synth.yaml`. P2r, tức chạy lại P2 trên realization mới sau khi cổng G-B trượt (không phải pha P3 F3 của plan), theo `configs/protocol_p2r.yaml` (khoá bằng `configs/protocol_p2r.sha256` và tag git `protocol-p2r`) và `configs/d2_synth_p2r.yaml` (cùng bộ sinh, thêm các chế độ SNR × mật độ anchor); mọi lựa chọn của P3 dựa trên dev 900/901, tổng hợp ở `outputs/p2/diag/p2rdev/summary.md`; lưới chính dùng realization 8–15.
Biến môi trường máy đặt sẵn `OMP_NUM_THREADS=40` (cả MKL, OpenBLAS): các script nhiều worker tự giới hạn luồng, còn khi chạy tay thì đặt rõ `OMP_NUM_THREADS`, `MKL_NUM_THREADS`, `OPENBLAS_NUM_THREADS` (và `CUDA_VISIBLE_DEVICES=` cho việc chỉ dùng CPU). Lý thuyết (Mệnh đề 1–2, chọn λ, các baseline là trường hợp riêng của RML): [docs/theory.md](docs/theory.md).
| Script | Việc | | Script | Việc |
| --- | --- | | --- | --- |
| `scripts/00_data_manifest.py [--check] [--dataset f3\|volve\|nlog]` | Ghi/kiểm SHA-256 theo `data_manifest/*.json` (F3: 279 file) | | `scripts/00_data_manifest.py [--check] [--dataset f3\|volve\|nlog]` | Ghi/kiểm SHA-256 theo `data_manifest/*.json` (F3: 279 file) |
@@ -30,5 +46,14 @@ scripts/run_p1.sh # P1: tie QC, LOWO baseline (khoảng 16 phút với
| `scripts/06_summarize_p1.py` | Bảng macro/theo giếng, calibration, G-A → `outputs/p1/summary.md`, `outputs/figures/p1_lowo.png` | | `scripts/06_summarize_p1.py` | Bảng macro/theo giếng, calibration, G-A → `outputs/p1/summary.md`, `outputs/figures/p1_lowo.png` |
| `scripts/07_volve_interp_qc.py` | QC horizon, well picks, checkshot và cube ST10010 của Volve theo `configs/d3_volve.yaml` → `outputs/volve/` | | `scripts/07_volve_interp_qc.py` | QC horizon, well picks, checkshot và cube ST10010 của Volve theo `configs/d3_volve.yaml` → `outputs/volve/` |
| `scripts/08_d1_label_check.py` | Kiểm tra D-1: porosity theo RHOB đo của NLOG so với nhãn sonic PHIE_DT → `outputs/d1/` | | `scripts/08_d1_label_check.py` | Kiểm tra D-1: porosity theo RHOB đo của NLOG so với nhãn sonic PHIE_DT → `outputs/d1/` |
| `scripts/09_fit_warp_prior_f3.py` | Fit prior warp GP Matérn-3/2 (type-II ML) trên marker TD của F3, kiểm tra leave-one-anchor-out → `outputs/p2/warp_prior_f3.json`, `outputs/figures/p2_f3_drift.png`. File json đã ghi hash trong protocol P2: không chạy lại khi đã có |
| `scripts/10_build_d2.py` | QC bộ sinh D2 so với F3 (nhãn, anchor, drift) → `outputs/d2/qc.json`, `outputs/figures/p2_d2_qc.png` |
| `scripts/11_run_d2.py --dev\|--main [--workers 6] [--device cuda:1]` | Mỗi ô (realization, c, N): đăng ký warp giếng train, huấn luyện Oracle, B3a–B3d, B4a–B4d, M1, M2 với 5 seed, chấm điểm trên 8 giếng test → `outputs/p2/{dev,main}/`. `--dev` chọn ngân sách bước; `--main` cần protocol khớp hash |
| `scripts/12_h1_blur.py [--workers 6] [--device cuda:1]` | H1: huấn luyện MSE với nhãn lệch δ ~ N(0, σ²), so hàm truyền đo được với exp(−2π²σ²f²) → `outputs/p2/h1/` |
| `scripts/13_summarize_p2.py [--mode main\|dev]` | Cổng G-B, bản đồ pha v1, H1, H3 (M2-ens so với B5), H4, chẩn đoán warp → `outputs/p2/summary/<mode>/`, `outputs/figures/p2_*.png` |
| `scripts/14_diag_posterior.py [--snr] [--anchor-density] [--sigma-a-reg] [--particles] [--smc-seeds] [--device cuda:1]` | Chẩn đoán posterior warp trên dev: SMC tôi luyện có điều kiện seismic (γ = 1/κ, pha phase_R ước lượng qua log Z), sai số warp, độ phủ, σ_post → `outputs/p2/diag/…` |
| `scripts/15_diag_train.py [--post-dir] [--methods] [--budgets-from] [--save-preds]` | Huấn luyện trên dev với nhãn từ posterior SMC (B3d-Sa, M2-Sa…) và các baseline, cổng kiểu G-B, ensemble kiểu H3 → `outputs/p2/diag/train*/` |
| `scripts/16_f3_posterior.py [--device cuda:1]` | Đặt F3 lên trục σ_post (chỉ mô tả): posterior SMC trên 4 giếng F3 → `outputs/p2/diag/f3_posterior/` |
| `scripts/17_summarize_p2r_dev.py [--only …]` | Tổng hợp dev cho P2r: screen, train/dose-response H2b, B(σ), stability, σ_a, F3 → `outputs/p2/diag/p2rdev/summary.md` |
`test 2/` là bản lưu trữ code luận văn, không sửa. `test 2/` là bản lưu trữ code luận văn, không sửa.

View File

@@ -1,11 +1,11 @@
# B2 (CNN–GRU v2, pipeline đã sửa, loss gốc), chạy thử hạ tầng P0. # B2 (CNN–GRU v2, corrected pipeline, original loss), P0 infrastructure smoke run.
# KHÔNG phải kết quả baseline: protocol.yaml phải được commit trước khi chạy thật (plan mục 5.2). # NOT a baseline result: protocol.yaml must be committed before any real run (plan §5.2).
dataset: f3_wells.npz dataset: f3_wells.npz
tdr: calibrated tdr: calibrated
label: PHIE label: PHIE
test_well: F06-1 test_well: F06-1
val_well: F03-2 val_well: F03-2
train_wells: [F03-4] # F02-1 có định nghĩa PHIE khác (plan mục 1.2d) nên không trộn ở đây train_wells: [F03-4] # F02-1 uses a different PHIE definition (plan §1.2d), so it is not mixed in here
epochs: 100 epochs: 100
lr: 5.0e-3 lr: 5.0e-3
d_channels: 64 d_channels: 64

View File

@@ -1,18 +1,18 @@
# D1: F3 Demo 2023, 4 giếng. Đường dẫn dữ liệu lấy từ ml_porosity/paths.py # D1: F3 Demo 2023, 4 wells. Data paths come from ml_porosity/paths.py
# (mặc định data/F3_Demo_2023/F3_Demo_2023, đổi bằng biến ML_POROSITY_F3_ROOT). # (default data/F3_Demo_2023/F3_Demo_2023, override with the ML_POROSITY_F3_ROOT variable).
wells: [F02-1, F03-2, F03-4, F06-1] wells: [F02-1, F03-2, F03-4, F06-1]
time_window_ms: [600, 1100] # cửa sổ chính; D-2 chưa chốt time_window_ms: [600, 1100] # main window; D-2 not yet finalized
ext_window_ms: [400, 1300] # cửa sổ lưu trữ (biên cho inversion B1 và synthetic) ext_window_ms: [400, 1300] # stored window (margin for B1 inversion and synthetics)
patch_radius: 1 # 3×3 trace như luận văn patch_radius: 1 # 3×3 traces as in the thesis
curves: [PHIE, PHIE_DT, DT, RHOB, GR, AI] # PHIE_DT = −0.2018 + 0.0011·DT (D-1) curves: [PHIE, PHIE_DT, DT, RHOB, GR, AI] # PHIE_DT = −0.2018 + 0.0011·DT (D-1)
# Các TDR được dựng cho mỗi giếng (xem ml_porosity/data/tdr.py): # TDRs built for each well (see ml_porosity/data/tdr.py):
# legacy tích phân DT từ mẫu LAS đầu, không hiệu chỉnh (cách của luận văn, chỉ để audit) # legacy DT integrated from the first LAS sample, uncalibrated (the thesis approach; audit only)
# calibrated marker-calibrated sonic: tham chiếu chấm điểm theo plan mục 5.2 # calibrated marker-calibrated sonic: scoring reference per plan §5.2
# anchors nội suy tuyến tính giữa các cặp marker TD, không dùng DT của giếng # anchors linear interpolation between TD marker pairs, does not use the well's DT
# wlt Depth2Time model của OpendTect (WellInfo/*.wlt), dùng cho phân tích độ nhạy # wlt OpendTect Depth2Time model (WellInfo/*.wlt), used for sensitivity analysis
tdrs: [legacy, calibrated, anchors, wlt] tdrs: [legacy, calibrated, anchors, wlt]
resample: resample:
fine_dt_ms: 0.25 fine_dt_ms: 0.25
cutoff_frac: 0.8 # lọc thông thấp ở 0.8·Nyquist của lưới 4 ms (100 Hz) cutoff_frac: 0.8 # low-pass at 0.8·Nyquist of the 4 ms grid (100 Hz)

44
configs/d2_synth.yaml Normal file
View File

@@ -0,0 +1,44 @@
# D2: synthetic hiệu chỉnh theo F3 (plan mục 5.1, 5.5). Bộ sinh: ml_porosity/data/synth_d2.py.
# Các thông số thuộc tính được hiệu chỉnh theo PHIE_DT calibrated của 4 giếng F3 trên cửa sổ 400–1300 ms
# (std phần dư sau trend tuyến tính 0.025–0.051, std băng > 6 Hz 0.010–0.026, τ_c 2.1–3.5 mẫu,
# độ dốc PSD 10–80 Hz từ −1.0 đến −2.3); xem scripts/10_build_d2.py.
horizons: [Shallow, FS8, FS7, Truncation, MFS4] # 5 horizon phủ ≥ 95% survey (Top-Foresets 74%, FS6 49%)
horizon_cache: outputs/d2/horizon_grid.npz
min_gap_ms: 8 # bỏ bin có hai horizon liên tiếp cách nhau < 8 ms hoặc đảo thứ tự
sub_unit_ms: 60 # độ dày danh nghĩa của đơn vị con (biên đơn vị = marker/anchor)
model_t_ms: [-300, 2400] # miền earth model theo thời gian thật; đủ rộng để t(τ) của log 100–1650 ms nằm trong miền ở drift ×2
log_tau_ms: [100, 1650] # miền log theo thời gian sonic τ
fine_dt_ms: 0.5
warp_dtau_ms: 4.0 # lưới của g
dt_ms: 4
ext_window_ms: [400, 1300] # seismic + anchor (như F3)
main_window_ms: [600, 1100] # input/nhãn/chấm điểm (như F3)
patch_radius: 1
wells:
n_test: 8
n_train_pool: 16 # N_train ∈ {2, 4, 8, 16} lấy lồng nhau từ pool
min_dist_test_m: 1000 # test cách mọi giếng khác ≥ 1 km (tách khối không gian)
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: # tổng các quá trình OU theo toạ độ địa tầng
- {sd: 0.010, ell_ms: 10.0}
- {sd: 0.006, ell_ms: 2.0}
clip: [0.05, 0.45]
wavelet: statistical # outputs/wavelets.npz (pha không, 128 ms) từ scripts/04
snr_db: 10 # lưới chính; stress {inf, 20, 5} để sau
drift:
prior_json: outputs/p2/warp_prior_f3.json # fit Matérn-3/2 trên anchor F3 (scripts/09)
factors: [0, 0.5, 1, 2]
anchors:
density: full
sigma_a_ms: 7.0 # σ robust (MAD) của chênh lệch marker–horizon tại 4 giếng F3 (18 cặp): 6.9 ms

50
configs/d2_synth_p2r.yaml Normal file
View File

@@ -0,0 +1,50 @@
# D2 for protocol_p2r: GENERATOR IDENTICAL to configs/d2_synth.yaml (protocol_p2, sha256 68e8f844…). This file differs only in
# comments and the `regimes` 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. Do not edit configs/d2_synth.yaml (locked in protocol_p2).
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; protocol_p2r 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: # protocol_p2r: observation regimes (seismic SNR at train + test wells, anchor density at train wells)
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)

View File

@@ -1,17 +1,17 @@
# D3: Volve. Dữ liệu tải từ data village nằm ở data/Volve (ml_porosity.paths.volve_root, đổi bằng # D3: Volve. Data downloaded from the data village live in data/Volve (ml_porosity.paths.volve_root, override with
# ML_POROSITY_VOLVE_ROOT); mọi đường dẫn dưới đây tính từ đó. Hash ở data_manifest/volve.json. # ML_POROSITY_VOLVE_ROOT); all paths below are relative to it. Hashes in data_manifest/volve.json.
well_logs_dir: Well_logs_pr_WELL well_logs_dir: Well_logs_pr_WELL
# Stack ST10010 (time, Kirchhoff final, góc 3–41°), tải từ data village ngày 26/10/2026 # Stack ST10010 (time, Kirchhoff final, angles 3–41°), downloaded from the data village on 2026-10-26
cube: Seismic/ST10010/Stacks/ST10010ZC11_PZ_PSDM_KIRCH_FULL_T.MIG_FIN.POST_STACK.3D.JS-017536.segy cube: Seismic/ST10010/Stacks/ST10010ZC11_PZ_PSDM_KIRCH_FULL_T.MIG_FIN.POST_STACK.3D.JS-017536.segy
picks: Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat picks: Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat
horizons_twt: Geophysical_Interpretations/Horizons/Horizons_TWT horizons_twt: Geophysical_Interpretations/Horizons/Horizons_TWT
grid_horizon: Official_Horizons/Hugin_Fm_Top+ST10010ZC11_Near_190314+STAT+TIME.dat grid_horizon: Official_Horizons/Hugin_Fm_Top+ST10010ZC11_Near_190314+STAT+TIME.dat
# 9 giếng có PHIF và F-15 A (có VSP checkshot, không có PHIF) # 9 wells with PHIF, plus F-15 A (VSP checkshot, no PHIF)
wells: [NO 15/9-F-1, NO 15/9-F-1 A, NO 15/9-F-1 B, NO 15/9-F-1 C, NO 15/9-F-11 A, NO 15/9-F-11 B, wells: [NO 15/9-F-1, NO 15/9-F-1 A, NO 15/9-F-1 B, NO 15/9-F-1 C, NO 15/9-F-11 A, NO 15/9-F-11 B,
NO 15/9-F-11 T2, NO 15/9-F-12, NO 15/9-F-15 A, NO 15/9-F-15 D] NO 15/9-F-11 T2, NO 15/9-F-12, NO 15/9-F-15 A, NO 15/9-F-15 D]
# Mặt pick ↔ horizon TWT để đối chiếu (BCU so với Draupne Fm. Top) # Pick surface ↔ TWT horizon for cross-checking (BCU vs. Draupne Fm. Top)
pick_horizons: pick_horizons:
Utsira Fm. Top: Other_Horizons/Utsira_Top+ST10010_Pz_PSDM_Full+STAT+TIME.dat Utsira Fm. Top: Other_Horizons/Utsira_Top+ST10010_Pz_PSDM_Full+STAT+TIME.dat
Ty Fm. Top: Official_Horizons/Ty_Fm_Top+ST10010_Full+STAT+TIME.dat Ty Fm. Top: Official_Horizons/Ty_Fm_Top+ST10010_Full+STAT+TIME.dat
@@ -21,12 +21,12 @@ pick_horizons:
Hugin Fm. VOLVE Top: Official_Horizons/Hugin_Fm_Top+ST10010ZC11_Near_190314+STAT+TIME.dat Hugin Fm. VOLVE Top: Official_Horizons/Hugin_Fm_Top+ST10010ZC11_Near_190314+STAT+TIME.dat
Hugin Fm. VOLVE Base: Official_Horizons/Hugin_Fm_Base+ST10010ZC11_Near_190314+STAT+TIME.dat Hugin Fm. VOLVE Base: Official_Horizons/Hugin_Fm_Base+ST10010ZC11_Near_190314+STAT+TIME.dat
# TWT của các pick nông không dùng làm anchor: cùng một MD (F-1 A/B/C dùng chung lỗ khoan) nhưng TWT # TWT of shallow picks is not used as anchors: the same MD (F-1 A/B/C share a borehole) has TWTs
# lệch nhau ~110 ms, và ở F-11 T2 lệch checkshot ~100 ms. # differing by ~110 ms, and at F-11 T2 the offset from the checkshot is ~100 ms.
anchor_exclude_surfaces: [Seabed, NORDLAND GP. Top, Utsira Fm. Top, HORDALAND GP. Top] anchor_exclude_surfaces: [Seabed, NORDLAND GP. Top, Utsira Fm. Top, HORDALAND GP. Top]
# NL (not logged): đoạn giếng không có log; 31/51 pick NL vẫn ghi TWT nhưng không kiểm chứng được. # NL (not logged): well interval without logs; 31/51 NL picks still record a TWT that cannot be verified.
# NR (not reached, ví dụ F-11 B đi ngang trong Hugin): điểm quay đầu của giếng, không nằm trên mặt phản xạ # NR (not reached, e.g. F-11 B running horizontally in the Hugin): the well's turning point, not on the reflector
# (lệch horizon ~−40 ms) và mỗi dòng bị lặp hai lần. # (~−40 ms off the horizon), and each row is duplicated.
anchor_exclude_qlf: [NL, NR] anchor_exclude_qlf: [NL, NR]
checkshots: checkshots:
@@ -37,5 +37,5 @@ checkshots:
NO 15/9-F-15 A: NO 15/9-F-15 A:
VSP: 15_9-F-15 A/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC VSP: 15_9-F-15 A/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC
# ROI từ quỹ đạo của 10 giếng trên + 500 m (inventory D3 mục 4), ED50 / UTM 31N # ROI from the trajectories of the 10 wells above + 500 m (D3 inventory §4), ED50 / UTM 31N
roi_xy: [433308, 437150, 6477323, 6479997] roi_xy: [433308, 437150, 6477323, 6479997]

View File

@@ -0,0 +1 @@
0733620042c4ec1b7dce447eef3ec64f915db05acbebbe5b6c977ac42e71a470 configs/protocol_p2.yaml

129
configs/protocol_p2.yaml Normal file
View File

@@ -0,0 +1,129 @@
# Giao thức P2 (pre-registration, plan mục 4–6; gate G-B, giả thuyết H1, H3, H4).
# Khoá bằng SHA-256 trong configs/protocol_p2.sha256 TRƯỚC khi chạy lưới chính và H1; scripts/11_run_d2.py --main
# và scripts/12_h1_blur.py từ chối chạy nếu hash không khớp. Chỉ mục training.budgets được điền sau vòng dev
# (realization 900, 901 — không bao giờ dùng cho kết quả) và trước khi khoá. Mọi thay đổi sau khoá: tạo version mới.
version: 1
date: 2026-10-26
inputs:
d2_config: {path: configs/d2_synth.yaml, sha256: 68e8f8449e4854f49c4bba3e9134688d9f22ad0e3af42c51be940d574b7199d4}
warp_prior: {path: outputs/p2/warp_prior_f3.json, sha256: 55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27,
fit: matern32}
wavelet: {path: outputs/wavelets.npz, key: statistical, sha256: b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64}
grid:
drift_factors: [0, 0.5, 1, 2] # warp thật = prior F3 × c (g → c·g, b → c·b)
realistic_drift: 1 # "vùng drift thực tế" của G-B
n_train: [2, 4, 8, 16] # lồng nhau từ pool 16 giếng
realizations: [0, 1, 2, 3, 4, 5, 6, 7]
dev_realizations: [900, 901] # chỉ để chọn ngân sách bước
seeds: [0, 1, 2, 3, 4] # seed điều khiển mẫu warp, multi-start MAP-II và khởi tạo mạng
snr_db: 10
anchor_density: full
test_wells: 8 # cùng 8 giếng test cho mọi ô của một realization
registration: # ml_porosity/registration/pipeline.py
hyper: MAP-II (m_g, σ_g, ℓ) trên anchor của giếng train; σ_a, σ_b cố định
kernel: matern32
sigma_a_ms: 7.0 # bằng σ_a sinh dữ liệu (MAD marker–horizon F3)
sigma_b_ms: 50.0 # prior bulk shift rộng
hyperprior: {sigma_g: [0.05, 1.0], ell_ms: [150.0, 1.0]} # log-normal (trung vị, sd log)
hyper_starts: 4
S: 64 # mẫu warp mỗi giếng (Laplace/Gauss–Newton + elliptical slice)
g_max: 1.0 # sai khác: plan ghi |g| ≤ 0.15; drift ×2 của D2 có g thật vượt 0.15
wavelet: thống kê pha không 128 ms từ trace giữa của giếng train
phase: "pha hằng ∈ {−180, −165, …, 165}° cực đại Σ_w log mean_s p(s_w | g_ws, φ) trên mẫu warp anchor; biên độ α ≥ 0"
physics_weights: "log p = −(n/2) log RSS (α ≥ 0, σ_n profile) trên 400–1300 ms; π ∝ p^γ, γ lớn nhất cho ESS ≥ S/4"
invalid_samples: mẫu warp không phủ hết cửa sổ chính có π = 0
ess_min_frac: 0.25
shift_K: 8 # bank B4: ±8 mẫu
wavelet_ms: 128
lambda: "λ = 1/τ_c, τ_c = 1 + 2 Σ ρ(k)², ρ = ACF gộp của nhãn train B3b lọc thông cao 6 Hz (tới lag đầu tiên ρ ≤ 0)"
training: # ml_porosity/models/bank_train.py
backbone: CNNGRUHetero(9 kênh, σ_min 1e-3) # cùng backbone P1
model: {d_channels: 64, p_dropout: 0.05}
optimizer: {name: Adam, lr: 5.0e-3, grad_clip: 5.0}
batch: full batch mọi giếng train
windows: "sub-window 64 mẫu bắt đầu 0, 2, …, 62 (32 cửa sổ/giếng); mọi loss tính trên cùng các cửa sổ"
input: patch 3×3 trên cửa sổ chính, z-score theo kênh trong từng giếng (như P1)
label_norm: trung bình/sd của log φ (chống alias) trên τ ∈ cửa sổ chính của giếng train (không phụ thuộc tie)
device: cuda:1
budget_candidates: [125, 250, 500, 1000, 2000]
budget_selection: >
Riêng từng phương pháp: ngân sách có RMSE tổng (p.u., macro 8 giếng test) trung bình nhỏ nhất trên
realization dev {900, 901} × N ∈ {4, 16} × seed {0, 1} ở c = 1. Cùng tập ứng viên và cùng công sức cho mọi
phương pháp; không dùng metric băng để chọn.
budgets: {Oracle: 500, B3a: 250, B3b: 125, B3c: 250, B3d: 250, B4a: 125, B4b: 125, B4c: 500, B4d: 250,
M1: 250, M2: 125, MSE0: 500} # outputs/p2/dev/budgets.json
dev_note: >
Ghi trước khi chạy lưới chính: ở dev, σ dự đoán co lại theo số bước với mọi loss có σ học được
(coverage_90 ≈ 0.10–0.66, NLL 2.5–99 ở ngân sách đã chọn) do mạng nhớ nhãn train khi N ≤ 16. Không sửa
trong P2; metric calibration báo cáo nguyên trạng, H3 là so sánh tương đối (cùng backbone, cùng UQ).
softdtw: {gamma: 0.1, band: 8}
dilate: {alpha: 0.5, gamma: 0.1, band: 8}
methods: # nhãn của mọi phương pháp: labels_for_warps (log chống alias, warp nghịch)
Oracle: {bank: warp thật, S: 1, loss: Gaussian NLL, note: "trần tham chiếu; không là đối thủ"}
B3a: {tie: "một điểm tại anchor nông nhất, t = τ + (t_0 − τ_0)", loss: Gaussian NLL}
B3b: {tie: "marker-calibrated sonic qua anchor (bỏ anchor đảo thứ tự bằng dãy con tăng dài nhất)", loss: Gaussian NLL}
B3c: {tie: "B3b + dịch cục bộ theo tương quan synthetic–seismic (cửa sổ 120 ms, bước 20 ms, ±16 ms, r ≥ 0.3, trơn 3)", loss: Gaussian NLL}
B3d: {tie: "warp trung bình có trọng số M2 (sai khác: plan ghi MAP)", loss: Gaussian NLL}
B4a: {bank: "nhãn B3b dịch ±8 mẫu (±32 ms), π đều", loss: "hard-min theo cửa sổ của Gaussian NLL (sai khác: σ học được, không cố định)"}
B4b: {bank: như B4a, loss: "RML (soft-min) với λ"}
B4c: {loss: "soft-DTW, chi phí Gaussian NLL, bước đối xứng (chéo ×2), γ = 0.1, dải ±8, chia 2n", labels: B3b}
B4d: {loss: "DILATE α = 0.5 (soft-DTW + TDI, Ω_ij = ((i − j)/n)²), γ = 0.1, dải ±8", labels: B3b}
B5: "ensemble 5 seed của B3b: μ = trung bình μ_s, σ² = trung bình σ_s² + phương sai μ_s"
M1: {bank: "S = 64 mẫu warp posterior theo anchor", weights: đều, loss: "RML với λ"}
M2: {bank: như M1, weights: "π vật lý (tempered)", loss: "RML với λ"}
M2-ens: như B5 cho M2
M3: hoãn (ngoài phạm vi P2)
metrics:
reference: "y_true: φ thật của earth model theo thời gian thật, chống alias, trên 600–1100 ms (8 giếng test)"
units: p.u. (×100)
bands: {f_c_hz: 6, filter: Butterworth bậc 4 pha không}
per_run: macro trên 8 giếng test cho mỗi (realization, c, N, method, seed)
calibration: [NLL, CRPS, coverage_50, coverage_80, coverage_90, coverage_95]
warp_diagnostics: "RMSE τ(t) trên cửa sổ chính so với warp thật, coverage 90% (chỉ báo cáo, không dùng để chọn)"
gates:
G-B:
text: "M2 hơn B3/B4 tốt nhất: RMSE băng seismic −10% hoặc PCC băng +0.05 ở ≥ 4/5 seed và đa số realization; không kém hơn 2% khi drift = 0."
competitors: [B3a, B3b, B3c, B3d, B4a, B4b, B4c, B4d]
best_competitor: "mỗi ô (c, N): đối thủ có band RMSE trung bình (realization × seed) nhỏ nhất"
improves: "band_rmse(M2) ≤ 0.90 · band_rmse(best) HOẶC band_pcc(M2) ≥ band_pcc(best) + 0.05"
cell_pass: >
improves đúng ở ≥ 4/5 seed (mỗi seed: trung bình trên realization) VÀ ở > 1/2 số realization (mỗi
realization: trung bình trên seed)
realistic_pass: cell_pass ở c = 1 cho ≥ 3/4 giá trị N
zero_drift_guard: >
ở c = 0: band_rmse(M2) ≤ 1.02 · band_rmse(best), xét trên trung bình theo N (macro) và từng N
pass: realistic_pass VÀ zero_drift_guard
report: "bản đồ pha (c × N) của tỉ số band RMSE M2/best và chênh band PCC; CI bootstrap 95% theo realization"
if_fail: "chẩn đoán λ/prior ≤ 2 tuần rồi pivot theo plan mục 9; báo cáo bất kể chiều nào"
hypotheses:
H1:
statement: "Prop 1: MSE với nhãn lệch thời gian ngẫu nhiên δ ~ N(0, σ²) cho dự đoán bị làm mờ với hàm truyền exp(−2π²σ²f²)"
setup: "c = 0, N = 16, nhãn Oracle; mỗi (giếng, cửa sổ) một δ cố định ~ N(0, σ_δ²); loss MSE trên μ; 5 seed; mọi realization"
sigma_ms: [0, 4, 8, 16, 32]
budget: ngân sách dev của MSE0 (nhãn Oracle không dịch, loss MSE theo cửa sổ)
estimator: >
Ĥ(f) = Σ Re[Y* P_σ] / Σ Re[Y* P_0] gộp mọi giếng test, realization và seed (taper Hann trên 126 mẫu);
tần số dùng: f ≥ 6 Hz, lý thuyết exp(−2π²σ²f²) ≥ 0.1 và Re S_{y,p0}(f) ≥ 10% cực đại trong băng
statistic: "r(σ) = trung bình hình học Ĥ/lý thuyết trên các tần số dùng"
reject_if: "r(σ) ∉ [0.5, 2] ở bất kỳ σ > 0 nào"
also_report: [band_std_ratio, band_pcc, band_rmse]
H3:
statement: "M2-ens hiệu chỉnh tốt hơn B5 ở drift thực tế"
cells: c = 1, mọi N
ce: "trung bình |coverage − danh nghĩa| trên 50/80/90/95%"
reject_if: "CE(M2-ens) ≥ CE(B5), hoặc CE giảm nhưng độ rộng khoảng (mean σ) > 1.2 × B5 trong khi cả NLL lẫn CRPS đều không tốt hơn"
H4:
statement: "Anchor cần thiết: bỏ anchor (chỉ vật lý) làm warp và nhãn xấu đi"
setup: >
c = 1, N = 4: M1/M2 không anchor, mẫu từ prior F3 × c với σ_b = 50 ms, wavelet pha không (pha thật của D2 —
thuận lợi cho biến thể không anchor), λ từ nhãn trung bình có trọng số M2; ngân sách = của M1/M2
reject_if: "warp RMSE (không anchor / có anchor) ≤ 1.10 VÀ band RMSE (không anchor / có anchor) ≤ 1.02 cho M2"
deferred: [M3, "lưới stress (SNR {inf, 20, 5}, mật độ anchor)", "backbone thứ hai"]

View File

@@ -0,0 +1 @@
eb887311f26a7c1c3dc69d9623d0086cfb5ccc79eea9e5ef59c723078f49c8aa configs/protocol_p2r.yaml

200
configs/protocol_p2r.yaml Normal file
View File

@@ -0,0 +1,200 @@
# Protocol P2r (pre-registration; rerun of P2 on new realizations after gate G-B failed; not the plan's phase P3, F3 field). Locked by SHA-256 in
# configs/protocol_p2r.sha256 and git tag protocol-p2r BEFORE generating or running any of realizations 8–15.
# Every choice below is based on dev 900/901 (outputs/p2/diag, summary in outputs/p2/diag/p2rdev/summary.md) and F3
# (descriptive only); no test labels of realizations 0–7 or 8–15 are used for selection. Changes after locking: new version.
# STATUS: LOCKED 2026-10-27, before realizations 8–15 were generated.
version: 1
date: 2026-10-27
supersedes: {path: configs/protocol_p2.yaml, sha256: 0733620042c4ec1b7dce447eef3ec64f915db05acbebbe5b6c977ac42e71a470}
history: "first locked as configs/protocol_p3.yaml (commit cee2ff0, tag protocol-p3); renamed to P2r before any of
realizations 8–15 was generated, to avoid confusion with the plan's phase P3 (F3 field); only names and the p2_outcome
deviation/untested notes changed"
p2_outcome: # reported as is, not rewritten
G-B: "failed — 0/4 cells at c = 1 passed (band RMSE ratio M2/best 0.985–1.045); c = 0 guard failed (macro 1.039)"
H1: "not rejected (Prop 1 matches at σ = 4–32 ms)"
H3: "rejected — CE(M2-ens) 0.278 ≥ CE(B5) 0.230"
H4: "not rejected"
diagnosis_dev: >
(dev 900/901, SNR 10, full) the M2 posterior is only 64 anchor-conditioned samples with tempered physical weights:
it does not contract to the true warp (warp RMSE 3.25 ms, 90% width 11.6 ms at c = 1 — on par with B3c 3.85 ms), so M2 ≈ B3d ≈
B3c. Seismic-conditioned SMC tempering (phase re-estimated via log Z) gives warp RMSE 0.56 ms and 90% coverage
0.97; labels at the SMC mean warp are close to Oracle. P2 therefore could not test the RML hypothesis: the failure lies in registration.
deviation: >
protocol_p2 gates.G-B.if_fail prescribes a time-boxed diagnosis followed by a pivot (plan §9); the option to rerun on
new realizations was added to the plan only after G-B failed. P2r is therefore a new pre-registration designed after
seeing the P2 failure (on dev realizations only). The P2 verdict stands and is reported as is; P2r results are not
presented as a P2 result.
untested_in_diagnosis: >
σ_b was neither learned nor stressed; σ_a was stressed (3.5 / 14 ms) but learned only on F3 (type-II ML ≈ 0.4 ms,
treating TD markers as exact; not reliable); the rock-physics misspecification stress was cut (plan §6, cut order item 6).
inputs:
d2_config: {path: configs/d2_synth_p2r.yaml, sha256: 57b676f0fc569ebe44f6253426fe42a218fb06272323b949932e9f8d597ff0d3} # generator identical to configs/d2_synth.yaml; adds regimes
warp_prior: {path: outputs/p2/warp_prior_f3.json, sha256: 55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27,
fit: matern32}
wavelet: {path: outputs/wavelets.npz, key: statistical, sha256: b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64}
budgets: {path: outputs/p2/diag/train/budgets.json, sha256: 815c6f7abc3d961255feb79bbed57a3e326cbc24cec11bbd97f455f0356e28c5}
grid:
regimes: [R10, R0, Rm5, R0h, R10tb] # configs/d2_synth_p2r.yaml; full-anchor R10/R0/Rm5 for H2a, all five for H2b
drift_factors: [0, 1, 2]
realistic_drift: 1
n_train: [4, 16] # nested from the 16-well pool
realizations: [8, 9, 10, 11, 12, 13, 14, 15] # new; 0–7 already used for P2 (and the B(σ) exploration, see notes)
dev_realizations: [900, 901] # used to design P2r; never used for results
seeds: [0, 1, 2, 3, 4] # network seeds; registration and SMC use seed 0 (reg_seed) as in dev
test_wells: 8 # observed at the regime SNR (test seismic is noisy too)
sigma_a_arm: # secondary, reported; sets the scope of the H2a claim (hypotheses.H2a.sigma_a_scope)
regime: R10
sigma_a_reg_ms: [3.5, 14] # data generated with σ_a = 7 ms; every method registered with the same σ_a_reg
drift_factors: [1]
n_train: [4, 16]
registration:
base: "as in protocol_p2 (MAP-II, σ_a 7 ms, σ_b 50 ms, 128 ms statistical wavelet, anchor-based constant phase) — for B3b, B3c, B3d"
phase_R: "constant phase re-estimated from the SMC log Z on the train wells (smc_fit_phase, 15° grid)"
smc:
code: ml_porosity/registration/smc_torch.py (smc_tie_posterior), same algorithm as smc.py
start: "P anchor-posterior samples (Laplace/Gauss–Newton + elliptical slice) for each well"
target: "p(warp | anchor) · p(seis | warp, wavelet phase_R)^γ, γ = 1/κ (κ = residual-ACF inflation factor at the best anchor sample; g_acf)"
tempering: "γ increased adaptively keeping ESS ≥ P/2; systematic resampling; 8 elliptical-slice steps per level; inflation 2"
particles: 1024
runs_K: 1 # one run (phase + SMC) per (realization, c, N); SMC seeds as in dev
stability:
criterion: >
registered before the trial: p95 over t of |τ̄_k(t) − τ̄_l(t)| between independent runs k ≠ l (main window),
averaged over the train wells of a cell (rid, c, N), ≤ 0.5 ms; the per-well maximum is reported alongside
dev_result: >
(SNR 10, full, rid 900/901, N 4/16) P = 256, K = 1: c = 1 passes 2/4 cells (max 0.69 ms), c = 2 0/4 (max 2.9 ms),
phase_R differs by up to 10°/26° between runs. P = 256 pooled K = 2: c = 1 4/4 (max 0.43 ms), c = 2 0/4.
P = 1024, K = 1: c = 1 4/4 (max 0.29 ms; worst well 0.86 ms), c = 2 2/4 (max 0.95 ms), phase differs
≤ 3°/9°. Cost of P = 1024 ≈ 3.3 × P = 256 per run. SNR −5, full (F3-like), P = 1024, K = 1: c = 1 passes 3/4 cells
(0.42–0.45 ms; r900 N = 4: 0.95 ms with phase_R differing by 12.6°), c = 2 0/4 (0.59–0.73 ms); relative to
σ_post (2.8 / 3.8 ms) the run-to-run p95 is ≤ 0.34 σ_post.
choice: "P = 1024, K = 1: passes at c = 1 with margin; one phase estimate (no phase mixing across runs)"
limitation: >
at c = 2 the posterior is multimodal and the mean warp is unstable between runs under every configuration tried;
c = 2 results are reported with an "unstable posterior" flag and are not primary evidence for H2a.
At low SNR the 0.5 ms criterion also fails in 1/4 cells at c = 1 (phase estimate varies between runs); this Monte
Carlo variability is small relative to σ_post but is not removed; reported as a limitation, not corrected.
training:
backbone: as in protocol_p2 (CNNGRUHetero, Adam 5e-3, full batch, 64-sample window, per-well z-score)
device: cuda:1
budgets: {Oracle: 500, B3b: 125, B3c: 250, B3c-R: 500, B3d: 250, B3d-Sa: 250, M2-Sa: 250} # iterations; from dev
# (inputs.budgets, SNR 10, c = 1); B3b, B3c, B3d, Oracle as protocol_p2; not re-selected per regime
lambda: "λ = 1/τ_c as in protocol_p2"
bank_S: 64 # M2-S: 64 particles drawn without replacement from the P particles, uniform π
methods:
Oracle: {labels: true warp, note: "reference ceiling; not a competitor"}
B3b: as in protocol_p2
B3c: as in protocol_p2 (protocol_p2 wavelet phase)
B3c-R: "B3c with wavelet phase phase_R"
B3d: "weighted mean warp of the old M2 (protocol_p2)"
B3d-Sa: "labels at the mean warp of the SMC particles (g_acf)"
M2-Sa: "RML (soft-min, λ) on a bank of 64 SMC particles (g_acf), uniform π"
ensembles: "Oracle-ens, B5 (= B3b-ens), B3c-R-ens, B3d-Sa-ens, M2-Sa-ens: 5 network seeds, μ = mean μ_s, σ² = mean σ_s² + var μ_s"
cells: "cell = (regime, c, N); all cell statistics are averaged over realization × seed as in protocol_p2"
common:
improves_seed: "mean difference (over realizations) for seed s in the hypothesized direction"
cell_pass: ">= 4/5 seeds AND > 1/2 of realizations (per realization: mean over seeds) — same rule as G-B"
ci: "95% bootstrap CI over realizations (2000 resamples) for every ratio; reported regardless of direction"
hypotheses:
H2a:
statement: "Labels from the tie posterior (SMC mean warp) beat labels from the best point tie"
method: B3d-Sa # primary; M2-Sa reported additionally under the same rule, not as a substitute
competitors: [B3b, B3c, B3c-R] # point ties, as in the statement
best_competitor: "per cell: the competitor with the smallest mean band RMSE"
improves: "band_rmse(B3d-Sa) ≤ 0.90 · band_rmse(best) OR band_pcc(B3d-Sa) ≥ band_pcc(best) + 0.05 (protocol_p2 rule)"
regimes: [R10, R0, Rm5] # full anchors; one verdict per regime
regime_pass: "cell_pass at c = 1 for both N, AND zero_drift_guard of the same regime"
zero_drift_guard: "at c = 0 of the same regime: band_rmse(B3d-Sa) ≤ 1.02 · band_rmse(best), macro over N and for each N"
pass: >
H2a passes if R10 passes. The claim is scoped to the regimes that pass; Rm5 (the F3-like regime, notes.f3_placement)
is reported as a separate pre-registered verdict, and no claim is made for a regime that fails.
sigma_a_scope: >
the H2a rule applied to grid.sigma_a_arm (no c = 0 guard). If it fails for a σ_a_reg, the paper states that the
H2a result requires a correctly specified anchor uncertainty σ_a. Dev: fails for both 3.5 and 14 ms (notes.sigma_a_stress).
secondary_vs_B3d: >
same rule with competitors [B3b, B3c, B3c-R, B3d], where B3d is the protocol_p2 M2 mean warp (an anchor-conditioned
posterior mean with tempered physical weights, not a point tie). Reported per regime; a claim that SMC labels beat the
P2 anchor posterior is made only for regimes where this passes. Added after dev showed B3d is the strongest
competitor at SNR 0 and −5 dB.
dev_result: >
(900/901, 5 seeds; with 2 dev realizations cell_pass needs both) point-tie competitors, c = 1, N = 4 / 16:
R10 ratio 0.85 / 0.76 (pass / pass; c = 0 guard 0.85 / 0.77 with 2 seeds); R0 0.87 / 0.89, ΔPCC +0.11 / +0.07
(pass / 1 of 2 realizations); Rm5 0.94 / 0.95, ΔPCC +0.10 / +0.08 (pass / 1 of 2). Including B3d: R10 unchanged
(B3d is not best at c = 1); R0 0.91 / 0.90 and Rm5 0.98 / 0.95 against B3d (no cell passes). c = 2: R10 ratio
0.91 / 0.83 but improves in 1 of 2 realizations (unstable posterior, see registration.smc.stability).
H2b:
statement: >
RML on the posterior bank beats posterior-mean labels when the tie posterior is wide, the gain increases with
σ_post, and RML costs at most 2% band RMSE when the posterior is narrow
ratio: "band_rmse(M2-Sa) / band_rmse(B3d-Sa) per cell"
sigma_post: "from SMC particles of the train wells (notes.sigma_post); no labels used; mean over realizations"
wide: "σ_post ≥ 1.5 ms (Prop 1: 50 Hz transfer factor ≤ 0.90)"
primary_n: 16
tests:
a_wide_gain: "at N = 16, M2-Sa < B3d-Sa (cell_pass) in ≥ 2/3 of wide cells"
b_dose: "at N = 16, Spearman ρ(σ_post, ratio) over all cells (c ∈ {0, 1, 2} × regime) < 0; one-sided permutation p reported"
c_narrow_guard: "at N = 16, mean ratio over narrow cells (σ_post < 1.5 ms) ≤ 1.02 (no-harm guard; a gain there is not required)"
pass: "a AND b AND c"
secondary_n4: >
N = 4 reported only (no claim): on dev the gain is smaller and unstable (ratio < 1 in 16/19 wide cells;
SNR −5/full ratio 1.02).
mechanism_note: >
Do not attribute the gain to deblurring (Prop 1) unless the measured ratio lies within the bound 1/B(σ_post) (notes.blur_bound):
on dev at SNR −5 the 4% gain exceeds the bound of ≈ 0–2% (docs/theory.md §1.4).
H3:
status: "not tested as a hypothesis in P2r; reported descriptively (decided on dev before locking)"
reason: >
dev h3_smc (900/901, SNR 10, full, 5 seeds; CE as in protocol_p2) at c = 1 / 2, N = 16: CE(B5) 0.113 / 0.152,
CE(B3d-Sa-ens) 0.298 / 0.319, CE(M2-Sa-ens) 0.318 / 0.335, CE(Oracle-ens) 0.389 / 0.366 (N = 4: 0.31 / 0.29 vs
0.45 / 0.41 / 0.45 / 0.48). Every ensemble trained on better labels under-covers more than B5, and the ensemble
trained on the true warp is the worst calibrated. CE against B5 therefore rewards label noise that widens the
predicted σ, not propagation of tie uncertainty: a seed ensemble of the heteroscedastic network does not carry
the tie posterior to the test wells. Testing H3 as in protocol_p2 cannot inform the posterior-label question.
reported: "for each ensemble at c = 1 per regime and N: CE, coverage 50/80/90/95%, NLL, CRPS, mean σ, with bootstrap CI"
claim_forbidden: "no claim that posterior-label ensembles are calibrated or better calibrated than B5"
notes:
sigma_post: "σ_post = (90% width of τ(t) over the main window, mean over train wells) / 3.29; computed from particles, no labels used"
sigma_a_stress: >
(dev 900/901, SNR 10, full, estR, g_acf; data generated with σ_a = 7 ms) registering with the correct σ_a gives warp RMSE
0.56/1.63 ms and 90% coverage 0.97/0.93 at c = 1/2. With σ_a = 3.5 ms (anchors over-trusted): RMSE 5.9/5.7 ms, coverage
0.45/0.54. With σ_a = 14 ms: RMSE 3.1/3.4 ms, coverage 0.50/0.75, σ_post 1.1/1.8 ms (overconfident). The SMC posterior
is calibrated only when σ_a is correct, in both directions. All P2r D2 results use the correct σ_a and are therefore
optimistic about registration; on F3 σ_a is not known (TD markers are not independent checkshots). Training under
misspecified σ_a: dev train_sa (900/901, 5 seeds, every method registered with the same σ_a), B3d-Sa / best point tie
at c = 1, N = 4 / 16: σ_a = 3.5 ms 1.08 / 1.18, σ_a = 14 ms 1.04 / 0.96 (0/4 cells pass at c ∈ {1, 2} in both cases);
M2-Sa / best: 1.04 / 1.10 and 0.98 / 0.93. The H2a advantage on dev depends on a correctly specified σ_a.
blur_bound: >
B(σ) = band_rmse(Gaussian blur_σ of the Oracle prediction μ) / band_rmse(μ), per regime and N, from the Oracle
predictions of the main run (descriptive; used only for mechanism_note, never for selection). If B3d-Sa labels carry
N(0, σ_post²) timing errors and RML removed them fully, the best attainable M2-Sa/B3d-Sa ratio is ≈ 1/B(σ_post).
Dev: SNR 10, full, N = 16: B(1.5 / 2 / 3 ms) = 1.015 / 1.044 / 1.157; N = 4: 0.98 / 0.98 / 1.01. SNR −5, full:
B ≤ 1.003 up to 3 ms for both N (noisy inputs already smooth the prediction), yet M2-Sa/B3d-Sa = 0.96 at N = 16.
f3_placement: >
descriptive only (scripts/16, 4 F3 wells, P = 256, never used to choose γ, P, λ or budgets). Under the protocol
registration (σ_a = 7 ms): σ_post 2.5–3.4 ms (g_acf), κ 1.7–2.6, r_post 0.24–0.57, run-to-run p95 0.63–1.31 ms,
i.e. close to Rm5 (dev σ_post ≈ 3.0 ms at c = 1). With the type-II ML σ_a of scripts/09 (≈ 0.4 ms, treating TD
markers as exact): σ_post 0.56–0.64 ms, i.e. narrower than R10. Since the SMC posterior is calibrated only for the
correct σ_a (notes.sigma_a_stress) and σ_a is not identifiable on F3, F3's place on the σ_post axis is uncertain
between these two ends; no F3 claim is drawn from the D2 regime results.
wording: # plan §10 + prior literature
prior_art: >
Uncertainty in the time–depth tie is not new: Gunning & Glinsky (2006) cast the tie as MAP + a Laplace approximation of the
time–depth posterior; Buland & Omre (2003) sample marker shifts by MCMC. SMC tempering here is a tool, not a
contribution. The contribution under test: using the tie posterior as training labels (posterior mean or RML on a bank).
forbidden: ["first", "novel", "new posterior tie",
"F3 labels called porosity without stating they are linear in DT",
"calibration/conformal assuming i.i.d. time samples",
"generalizing to the field from synthetic results",
"TD markers as independent checkshots",
"geologically plausible without a metric",
"tuning on test labels", "claims about λ (λ = 1/τ_c kept fixed; no evidence that a variant is better)"]

BIN
docs/figures/workflow.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

1101
docs/figures/workflow.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 223 KiB

96
docs/figures/workflow.tex Normal file
View File

@@ -0,0 +1,96 @@
% Detailed workflow figure (docs/technical_overview.md, paper Fig. workflow).
% Rebuild: xelatex workflow.tex, then export PNG/SVG as described in technical_overview §5
\documentclass[border=8pt]{standalone}
\usepackage{fontspec}
\setmainfont{lmroman10-regular.otf}[BoldFont=lmroman10-bold.otf, ItalicFont=lmroman10-italic.otf]
\usepackage{tikz}
\usetikzlibrary{positioning,fit,arrows.meta,calc}
\begin{document}
\hyphenpenalty=10000 \exhyphenpenalty=10000
\begin{tikzpicture}[
font=\normalsize,
>={Stealth[length=2.2mm]},
box/.style={draw, rectangle, align=center, text width=5.0cm, minimum height=1.15cm, inner sep=4pt, fill=white},
inp/.style={box, text width=3.4cm},
stage/.style={draw, dashed, rounded corners=2pt, inner sep=9pt},
st/.style={font=\large\bfseries, anchor=south},
arr/.style={->, thick},
aux/.style={->, densely dotted, thick},
]
% ---------- Inputs ----------
\node[inp] (las) at (0,0) {LAS well logs\\DT, RHOB, $\varphi$};
\node[inp] (mk) at (0,-2.6) {Well markers\\+ seismic horizons};
\node[inp] (segy) at (0,-5.2) {SEG-Y\\seismic volume};
\node[inp] (true) at (0,-7.8) {True warp\\(D2 only)};
\node[st] at ($(las.north)+(0,0.45)$) {Inputs};
% ---------- 1. Preprocessing ----------
\node[box] (tau) at (5.3,0) {DT integration\\$\to$ sonic-time axis $\tau$};
\node[box] (anc) at (5.3,-2.6) {Anchor pairs $(\tau_k, t_k)$\\pick noise $\sigma_a\,{=}\,7$ ms};
\node[box] (patch) at (5.3,-5.2) {Corrected well locations\\$3{\times}3$ seismic patch extraction};
\node[stage, fit=(patch)(tau)(anc)] (s1) {};
\node[st] at (s1.north) {1. Preprocessing};
% ---------- 2. Registration posterior ----------
\node[box] (prior) at (11.8,0) {GP prior on warp $t(\tau)$\\$b$, $g \sim$ Matérn-3/2 (MAP-II)};
\node[box] (post) at (11.8,-2.6) {Anchor-conditioned posterior\\Laplace + elliptical slice};
\node[box] (lik) at (11.8,-5.2) {Physics-based tie likelihood\\synthetic = AI $\ast$ wavelet\\vs.\ seismic at the well};
\node[box] (wgt) at (11.8,-7.8) {$S$ weighted warp samples $t^{(s)}(\tau)$\\(M2: $\pi_s\,{\propto}\,p_s^{\gamma}$; SMC: $\gamma_{\mathrm{acf}}$)};
\node[stage, fit=(prior)(post)(lik)(wgt)] (s2) {};
\node[st] at (s2.north) {2. Registration posterior};
% ---------- 3. Label bank ----------
\node[box] (inv) at (18.3,0) {Warp inversion $\to \tau^{(s)}(t)$\\anti-alias-filtered $\varphi$ readout};
\node[box] (bank) at (18.3,-2.4) {Label bank $y^{(s)}(t)$\\$S \times L$ matrix with weights $\pi_s$};
\node[stage, fit=(inv)(bank)] (s3) {};
\node[st] at (s3.north) {3. Label bank};
% ---------- 4. Training ----------
\node[box] (net) at (18.3,-5.2) {CNN–GRU\\outputs $(\mu, \sigma)$};
\node[box] (loss) at (18.3,-7.4) {$\mathrm{RML}_\lambda$ loss\\$\lambda\,{=}\,1/\tau_c$};
\node[box] (sel) at (18.3,-9.6) {Step count selected on dev\\5-seed ensemble};
\node[stage, fit=(net)(loss)(sel)] (s4) {};
\node[st, anchor=south west] at (s4.north west) {4. Training};
% ---------- 5. Prediction ----------
\node[box] (pred) at (18.3,-13.4) {Test-well or full-volume seismic\\$\to \mu \pm \sigma$ (no warp required)};
\node[stage, fit=(pred)] (s5) {};
\node[st, anchor=south west] at (s5.north west) {5. Prediction};
% ---------- 6. Evaluation ----------
\node[box] (ref) at (11.8,-11.2) {Blind wells, fixed reference\\(calibrated; sensitivity: .wlt)};
\node[box] (met) at (11.8,-13.4) {Band-wise RMSE, PCC\\NLL, CRPS, coverage\\warp error (D2)};
\node[box] (gate) at (5.3,-13.4) {Baselines B0–B5 and Oracle\\$\to$ go/no-go gates G-A…G-D};
\node[stage, fit=(met)(ref)(gate)] (s6) {};
\node[st, anchor=south west] at (s6.north west) {6. Evaluation (SHA-256-locked protocol)};
% ---------- Arrows ----------
\draw[arr] (las) -- (tau);
\draw[arr] (mk) -- (anc);
\draw[arr] (segy) -- (patch);
\draw[arr] (tau) -- (anc);
\draw[arr] (tau) -- (prior);
\draw[arr] (anc) -- (post);
\draw[arr] (patch) -- (lik);
\draw[aux] ($(tau.east)+(0,-0.3)$) -- (8.55,-0.3) |- ($(lik.west)+(0,0.3)$);
\draw[arr] (prior) -- (post);
\draw[arr] (post) -- (lik);
\draw[arr] (lik) -- (wgt);
\draw[arr] (wgt.east) -- (14.95,-7.8) |- (inv.west);
\draw[arr] (inv) -- (bank);
\draw[arr] ($(bank.south)+(1.8,0)$) -- ($(net.north)+(1.8,0)$);
\draw[arr] (net) -- (loss);
\draw[arr] (loss) -- (sel);
\draw[arr] (patch.south) -- (5.3,-9.25) -- (15.2,-9.25) |- (net.west);
\draw[arr] ($(sel.south)+(1.8,0)$) -- ($(pred.north)+(1.8,0)$);
\draw[arr] (pred) -- (met);
\draw[arr] (ref) -- (met);
\draw[arr] (met) -- (gate);
\draw[aux] (true.south) |- (gate.west);
\end{tikzpicture}
\end{document}

View File

@@ -26,8 +26,8 @@ Quy ước nhãn:
| **Đóng góp (C1–C4)** | C1: formulation và lý thuyết, gồm "MSE dưới misregistration = học một target bị làm mờ" và điều kiện nhận dạng. C2: phương pháp RML. C3: giao thức đánh giá có xét registration, kèm benchmark synthetic hiệu chỉnh theo F3 và phase diagram "khi nào việc này quan trọng". C4: audit dữ liệu F3 cho bài toán porosity (mục 1.2). | | **Đóng góp (C1–C4)** | C1: formulation và lý thuyết, gồm "MSE dưới misregistration = học một target bị làm mờ" và điều kiện nhận dạng. C2: phương pháp RML. C3: giao thức đánh giá có xét registration, kèm benchmark synthetic hiệu chỉnh theo F3 và phase diagram "khi nào việc này quan trọng". C4: audit dữ liệu F3 cho bài toán porosity (mục 1.2). |
| **Không phải đóng góp** | Backbone mới, thêm attention, thêm loss, Cycle-GAN, hay chỉ sửa leakage. | | **Không phải đóng góp** | Backbone mới, thêm attention, thêm loss, Cycle-GAN, hay chỉ sửa leakage. |
| **Venue chính** | *Geophysical Prospecting* hoặc *Journal of Applied Geophysics*. Dự phòng: *Frontiers in Earth Science*, *Earth Science Informatics*, *Acta Geophysica*. Quartile phải kiểm tra lại trên SCImago khi nộp [XM]. | | **Venue chính** | *Geophysical Prospecting* hoặc *Journal of Applied Geophysics*. Dự phòng: *Frontiers in Earth Science*, *Earth Science Informatics*, *Acta Geophysica*. Quartile phải kiểm tra lại trên SCImago khi nộp [XM]. |
| **Thời gian** | 24 tuần (26/10/2026 → khoảng 02/05/2027), có 4 cổng go/no-go ở tuần 5, 9, 13 và 17. | | **Thời gian** | **Lịch nén (chốt 27/10/2026): xong toàn bộ bài trước thứ 7, 31/10/2026.** 6 ngày (T2 26/10 → T7 31/10/2026), 4 cổng go/no-go: G-A và G-B ngày 26/10 (đã đánh giá), G-C cuối 28/10, G-D cuối 29/10. Lịch gốc 24 tuần (→ 02/05/2027) đã bỏ. |
| **Việc tuần này** | Mục 12. | | **Việc tuần này** | Mục 6 (lịch theo ngày) và mục 12. |
--- ---
@@ -208,7 +208,7 @@ Với sai số tới 14–66 ms (tùy giếng) đo được ở mục 1.2, phầ
**Đã làm:** đọc 15 bài trong survey; chạy 6 lượt tìm kiếm ngày 25/10/2026 với các cụm "well-tie uncertainty + neural network training", "soft-DTW + seismic inversion", "joint well tie + inversion DL", "time-depth uncertainty as label noise". **Không tìm thấy** công trình nào ghép đủ tie, bất định tie và việc học thuộc tính. Một bài 2026 ở *Geophysical Prospecting* dùng DL ước lượng time shift làm misfit cho FWI; bài này khác bài toán. **Đã làm:** đọc 15 bài trong survey; chạy 6 lượt tìm kiếm ngày 25/10/2026 với các cụm "well-tie uncertainty + neural network training", "soft-DTW + seismic inversion", "joint well tie + inversion DL", "time-depth uncertainty as label noise". **Không tìm thấy** công trình nào ghép đủ tie, bất định tie và việc học thuộc tính. Một bài 2026 ở *Geophysical Prospecting* dùng DL ước lượng time shift làm misfit cho FWI; bài này khác bài toán.
**Còn phải làm [XM], trước tuần 5 và một lần nữa trước khi nộp:** **Còn phải làm [XM], trước khi bắt đầu viết (29/10/2026) và một lần nữa trước khi nộp (31/10/2026):**
1. ~~Đọc paper RING 2025 (Boucard, Caumon & Baville).~~ Bỏ: ngày 26/10/2026 không tìm thấy bài này, quyết định bỏ qua. 1. ~~Đọc paper RING 2025 (Boucard, Caumon & Baville).~~ Bỏ: ngày 26/10/2026 không tìm thấy bài này, quyết định bỏ qua.
2. ~~Đọc toàn văn Gunning & Glinsky (2006).~~ **Đã đọc ngày 26/10/2026** (`refs/j.cageo.2005.10.001.pdf`, tóm tắt ở L1). Hệ quả cho P2: (a) là baseline cổ điển cho tie có bất định; (b) anchor cứng của `calibrate_to_anchors` là giới hạn σ_t → 0 của mô hình marker trong bài, nên phiên bản anchor mềm có sẵn tiền lệ; (c) wavelet chung cho nhiều giếng là một cách xử lý việc B1 hỏng ngoài mẫu do pha wavelet không khớp giữa các giếng; (d) bài cảnh báo rằng khi nhiễu cao, cho phép sai số định vị sẽ tạo ra fit tốt giả, cùng loại rủi ro với việc chọn shift theo r. 2. ~~Đọc toàn văn Gunning & Glinsky (2006).~~ **Đã đọc ngày 26/10/2026** (`refs/j.cageo.2005.10.001.pdf`, tóm tắt ở L1). Hệ quả cho P2: (a) là baseline cổ điển cho tie có bất định; (b) anchor cứng của `calibrate_to_anchors` là giới hạn σ_t → 0 của mô hình marker trong bài, nên phiên bản anchor mềm có sẵn tiền lệ; (c) wavelet chung cho nhiều giếng là một cách xử lý việc B1 hỏng ngoài mẫu do pha wavelet không khớp giữa các giếng; (d) bài cảnh báo rằng khi nhiễu cao, cho phép sai số định vị sẽ tạo ra fit tốt giả, cùng loại rủi ro với việc chọn shift theo r.
3. ~~Đọc bài EAGE 2023.~~ Bỏ (quyết định 26/10/2026). Link Fraunhofer `publica/418100` trong bản plan cũ là bài Tschannen et al. 2022, không phải bài EAGE, và bài EAGE chưa xác định được. 3. ~~Đọc bài EAGE 2023.~~ Bỏ (quyết định 26/10/2026). Link Fraunhofer `publica/418100` trong bản plan cũ là bài Tschannen et al. 2022, không phải bài EAGE, và bài EAGE chưa xác định được.
@@ -305,6 +305,7 @@ Bảng này biến ablation thành một con đường đi từ v2 tới RML.
- **Mệnh đề 1 (blur):** phát biểu như mục 2.3. Hệ quả: (i) cận trên của std ratio và của PCC trong băng; (ii) L_Var chỉ chỉnh lại biên độ mà không khôi phục được độ kết hợp pha. - **Mệnh đề 1 (blur):** phát biểu như mục 2.3. Hệ quả: (i) cận trên của std ratio và của PCC trong băng; (ii) L_Var chỉ chỉnh lại biên độ mà không khôi phục được độ kết hợp pha.
- **Mệnh đề 2 (nhận dạng):** nếu f_θ đẳng biến với phép dịch thời gian (chính xác với mạng tích chập hoàn toàn, xấp xỉ với CNN–biGRU) và prior warp bất biến với phép dịch (không có anchor), thì likelihood bất biến với cặp biến đổi (dịch mạng c, dịch warp −c). MAP vì vậy không xác định được. Anchor có σ_a hữu hạn làm posterior trở nên proper. Thêm vào đó, warp linh hoạt có thể căn chỉnh theo noise; mức linh hoạt bị giới hạn bởi (σ_g, ℓ) học từ anchor. Có báo cáo chẩn đoán *strain energy*. - **Mệnh đề 2 (nhận dạng):** nếu f_θ đẳng biến với phép dịch thời gian (chính xác với mạng tích chập hoàn toàn, xấp xỉ với CNN–biGRU) và prior warp bất biến với phép dịch (không có anchor), thì likelihood bất biến với cặp biến đổi (dịch mạng c, dịch warp −c). MAP vì vậy không xác định được. Anchor có σ_a hữu hạn làm posterior trở nên proper. Thêm vào đó, warp linh hoạt có thể căn chỉnh theo noise; mức linh hoạt bị giới hạn bởi (σ_g, ℓ) học từ anchor. Có báo cáo chẩn đoán *strain energy*.
- (Tùy chọn) Tính nhất quán của estimator marginal likelihood khi prior đúng và số view tăng. - (Tùy chọn) Tính nhất quán của estimator marginal likelihood khi prior đúng và số view tăng.
- **Bản viết (26/10/2026):** [theory.md](docs/theory.md) có chứng minh Mệnh đề 1 và hai hệ quả, Mệnh đề 2 với sd của dịch chung ≈ σ_a/√K, heuristic λ = 1/τ_c, Bổ đề 1–5 (các baseline ở mục 4.5 là trường hợp riêng của RML) và kết quả H1. Chưa làm: chẩn đoán strain energy, tính nhất quán của estimator.
### 4.7 Dự đoán và bất định ### 4.7 Dự đoán và bất định
@@ -398,17 +399,29 @@ Lưới thí nghiệm:
--- ---
## 6. Lộ trình 24 tuần với cổng go/no-go ## 6. Lộ trình với cổng go/no-go (lịch nén: xong trước T7 31/10/2026)
| Pha | Tuần (ngày) | Việc chính | Đầu ra | Cổng | Chốt ngày 27/10/2026: toàn bộ bài, gồm cả review nội bộ và bản nộp, phải xong trước thứ 7, 31/10/2026. Lịch gốc 24 tuần (26/10/2026 → 02/05/2027) bỏ. P0–P2 đã xong trong ngày 26/10, nên lịch nén chỉ còn chẩn đoán sau G-B, F3, Volve, viết và nộp. Ngưỡng các cổng **không đổi**; chỉ ngày thay đổi.
| Pha | Ngày | Việc chính | Đầu ra | Cổng |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| **P0 Hạ tầng** | 1–2 (26/10–08/11/2026) | `git init`; tải dữ liệu iCloud về máy (SEGY, horizon, outputs); tái cấu trúc code (mục 7); khóa môi trường; bỏ đường dẫn Windows; unit test cho geometry (Set Point) và TD | Pipeline chạy end-to-end trên macOS; manifest dữ liệu | — | | **P0 Hạ tầng** | T2 26/10 (xong) | `git init`; tải dữ liệu iCloud về máy (SEGY, horizon, outputs); tái cấu trúc code (mục 7); khóa môi trường; bỏ đường dẫn Windows; unit test cho geometry (Set Point) và TD | Pipeline chạy end-to-end; manifest dữ liệu | — |
| **P1 Audit + baseline đúng** | 2–5 (02/11–29/11) | Geometry; so sánh các nguồn TD; wavelet và tần số trội; synthetic seismogram cho 4 giếng (QC tie); QC nhãn và quyết định D-1; LOWO cho B0, B1, B2, B3a–b. Bắt đầu kiểm kê Volve song song. | Ghi chú audit dữ liệu (thành mục 3 của bài); bảng baseline | **G-A (cuối tuần 5):** baseline tái lập được (5 seed, có phương sai); đã ước lượng misregistration còn lại. *Nếu* sau tie tốt nhất misregistration còn < 1/8 chu kỳ ở mọi giếng **và** B3a ≈ B3b, thì H2 khó thể hiện trên F3: dồn trọng tâm sang D2 + D3. | | **P1 Audit + baseline đúng** | T2 26/10 (xong) | Geometry; so sánh các nguồn TD; wavelet và tần số trội; synthetic seismogram cho 4 giếng (QC tie); QC nhãn và quyết định D-1; LOWO cho B0, B1, B2, B3a–b; kiểm kê Volve | Ghi chú audit dữ liệu (thành mục 3 của bài); bảng baseline | **G-A (26/10, đã đánh giá):** baseline tái lập được (5 seed, có phương sai); đã ước lượng misregistration còn lại. *Nếu* sau tie tốt nhất misregistration còn < 1/8 chu kỳ ở mọi giếng **và** B3a ≈ B3b, thì H2 khó thể hiện trên F3: dồn trọng tâm sang D2 + D3. Kết quả: không pivot. |
| **P2 Lý thuyết + synthetic + RML v1** | 5–9 (30/11/2026–03/01/2027) | Chứng minh MĐ1/MĐ2; bộ sinh synthetic; RML M1/M2; B4/B5 | Kết quả synthetic, phase diagram v1 | **G-B (cuối tuần 9):** trong vùng drift thực tế, M2 hơn B3/B4 tốt nhất theo ngưỡng chốt trước (đề xuất: RMSE băng −10% hoặc PCC băng +0.05) ở ≥ 4/5 seed và đa số realization; không kém hơn 2% khi drift = 0. Nếu trượt: chẩn đoán (λ, prior) tối đa 2 tuần, rồi pivot (mục 9). | | **P2 Lý thuyết + synthetic + RML v1** | T2 26/10 (lưới chính xong); chẩn đoán đến hết T3 27/10 | Chứng minh MĐ1/MĐ2; bộ sinh synthetic; RML M1/M2; B4/B5. Chẩn đoán sau G-B: học σ_a, σ_b; lưới stress trên dev (SNR thấp, ít anchor, rock physics sai). Ngày 27/10: đã khoá `protocol_p2r` và chạy lại D2 trên realization 8–15 (cuda:0 + cuda:1, xong 11:29); H2a và H2b đạt, không Pivot 1 (mục 12, ý 14) | Kết quả synthetic, phase diagram v1; `protocol_p2r` và `outputs/p2r/summary/` | **G-B (26/10, không đạt):** trong vùng drift thực tế, M2 hơn B3/B4 tốt nhất theo ngưỡng chốt trước (RMSE băng −10% hoặc PCC băng +0.05) ở ≥ 4/5 seed và đa số realization; không kém hơn 2% khi drift = 0. Luật trượt: chẩn đoán (λ, prior) có thời hạn (protocol cho tối đa 2 tuần; lịch nén rút còn đến hết 27/10), rồi chạy lại hoặc pivot (mục 9). |
| **P3 F3 field** | 9–13 (04/01–31/01) | Nested LOWO đầy đủ; ensemble; calibration; ablation; leave-one-anchor-out; volume kèm bất định; M3 | Bảng và hình F3 | **G-C (cuối tuần 13):** 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 | | **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 |
| **P4 Field 2** | Kiểm kê từ tuần 2; thí nghiệm tuần 12–17 (25/01–07/03) | ROI Volve, tie, pipeline; chạy tập con B1, B3 tốt nhất, B4, B5, M2 | Bảng field 2 | **G-D (cuối tuần 17):** 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ả | | **P4 Field 2** | T4 28/10 dựng pipeline (song song P3); T5 29/10 chạy | ROI Volve, tie, pipeline; chạy tập con B1, B3 tốt nhất, B4, B5, M2 | Bảng field 2 | **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ả |
| **P5 Viết** | 15–21 (08/02–11/04) | 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 (tuần 19), v2 (tuần 21) | Review nội bộ | | **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 | 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) | Review nội bộ |
| **P6 Review + nộp** | 21–24 (12/04–02/05/2027) | GVHD và một người làm địa vật lý review; kiểm tra novelty lần cuối; preprint (EarthArXiv/ESSOAr) nếu venue cho phép; nộp | Bản nộp | — | | **P6 Review + nộp** | T7 31/10 | 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 | — |
**Thứ tự cắt phạm vi nếu trễ** (cắt từ trên xuống, không cắt các cổng hay ngưỡng):
1. M3 (RML-EM): đã hoãn.
2. Cửa sổ mở rộng của F3 (D-2): chỉ báo cáo cửa sổ chính 600–1100 ms.
3. Volume kèm bất định: chỉ một inline và một crossline qua giếng thay vì cả khối.
4. Leave-one-anchor-out: chỉ chạy ở c = 1 và một giếng F3.
5. Volve: chỉ B3 tốt nhất, B3d-S và M2 (bỏ B1, B4, B5).
6. Lưới stress ở P2: chỉ trục SNR và mật độ anchor.
**Ngân sách GPU (cuda:1):** lưới D2 chính mất 89 phút với posterior cũ; bản chạy lại với SMC dự kiến vài giờ, nên chạy qua đêm 27/10 → 28/10. Mọi bước trên F3 và Volve phải chạy được trong ban ngày.
--- ---
@@ -480,11 +493,11 @@ Giữ nguyên `test 2/` làm bản lưu trữ của luận văn; không sửa t
| R1: sau tie tốt, misregistration trên F3 nhỏ nên gain không đáng kể | Trung bình | Claim đổi thành "khi nào quan trọng" (phase diagram) cộng "không gây hại" trên F3 cộng D3. Lưu ý rằng chính cách tích phân DT phổ biến trong các bài ML (kể cả luận văn) đã tạo ra lỗi tới 14–66 ms. | | R1: sau tie tốt, misregistration trên F3 nhỏ nên gain không đáng kể | Trung bình | Claim đổi thành "khi nào quan trọng" (phase diagram) cộng "không gây hại" trên F3 cộng D3. Lưu ý rằng chính cách tích phân DT phổ biến trong các bài ML (kể cả luận văn) đã tạo ra lỗi tới 14–66 ms. |
| R2: B1 (inversion cổ điển) mạnh hơn mọi mô hình DL trên F3 | Trung bình–cao, vì φ ≈ tuyến tính(AI) | Báo cáo trung thực. Claim chính là *tác dụng của registration trong mô hình học* và vẫn đứng được. Có thể áp dụng nguyên lý RML cho bước tie của B1. | | R2: B1 (inversion cổ điển) mạnh hơn mọi mô hình DL trên F3 | Trung bình–cao, vì φ ≈ tuyến tính(AI) | Báo cáo trung thực. Claim chính là *tác dụng của registration trong mô hình học* và vẫn đứng được. Có thể áp dụng nguyên lý RML cho bước tie của B1. |
| R3: chỉ có 4 giếng nên thống kê yếu | Chắc chắn | Sức mạnh thống kê đến từ D2; D3; báo cáo theo từng giếng; không dùng p-value giả | | R3: chỉ có 4 giếng nên thống kê yếu | Chắc chắn | Sức mạnh thống kê đến từ D2; D3; báo cáo theo từng giếng; không dùng p-value giả |
| R4: phát hiện công trình trùng ý | Thấp–trung bình | Kiểm tra mục 2.4 trước G-A; nếu trùng thì khác biệt hóa bằng anchor + vật lý + giao thức đánh giá, hoặc pivot 1 | | R4: phát hiện công trình trùng ý | Thấp–trung bình | Kiểm tra mục 2.4 trước khi viết (29/10/2026) và lần cuối ngày nộp (31/10/2026); nếu trùng thì khác biệt hóa bằng anchor + vật lý + giao thức đánh giá, hoặc pivot 1 |
| R5: reviewer nói "đây chỉ là dự đoán sonic" | Cao | Nói thẳng ngay từ mục Data; D3 có porosity tính độc lập; coi PHIE = f(DT) là *lợi thế* cho vật lý chính xác | | R5: reviewer nói "đây chỉ là dự đoán sonic" | Cao | Nói thẳng ngay từ mục Data; D3 có porosity tính độc lập; coi PHIE = f(DT) là *lợi thế* cho vật lý chính xác |
| R6: RML-EM suy sụp hoặc trọng số suy biến | Trung bình | M2 (fixed) là phương pháp chính; theo dõi ESS và các chẩn đoán ở mục 4.8 | | R6: RML-EM suy sụp hoặc trọng số suy biến | Trung bình | M2 (fixed) là phương pháp chính; theo dõi ESS và các chẩn đoán ở mục 4.8 |
| R7: truy cập dữ liệu (iCloud, dung lượng và giấy phép Volve) | Trung bình | Tải từ P0; chỉ lấy ROI; kiểm tra giấy phép trước khi công bố dữ liệu dẫn xuất | | R7: truy cập dữ liệu (iCloud, dung lượng và giấy phép Volve) | Trung bình | Tải từ P0; chỉ lấy ROI; kiểm tra giấy phép trước khi công bố dữ liệu dẫn xuất |
| R8: trễ tiến độ | Trung bình | Cắt lưới D2; D3 chỉ chạy tập con phương pháp; các gate đã có ngày cố định | | R8: trễ tiến độ (lịch nén 6 ngày, xong trước 31/10/2026) | Cao | Cắt phạm vi theo thứ tự ở mục 6; các gate có ngày cố định; chạy GPU qua đêm; viết song song với thí nghiệm. Không nới ngưỡng cổng để kịp lịch. |
**Các hướng pivot:** **Các hướng pivot:**
- **Pivot 1:** chuyển thành bài phân tích. *"Label registration error in sparse-well seismic property learning: theory, benchmark and registration-aware evaluation"*, giữ C1 + C3 + C4, phương pháp chỉ là phần phụ. Vẫn khả thi ở Q2, ví dụ *Frontiers* hoặc *Earth Science Informatics*. - **Pivot 1:** chuyển thành bài phân tích. *"Label registration error in sparse-well seismic property learning: theory, benchmark and registration-aware evaluation"*, giữ C1 + C3 + C4, phương pháp chỉ là phần phụ. Vẫn khả thi ở Q2, ví dụ *Frontiers* hoặc *Earth Science Informatics*.
@@ -534,7 +547,7 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
--- ---
## 12. Việc làm ngay (tuần 26/10–01/11/2026) ## 12. Việc làm ngay (26/10–31/10/2026)
1. `git init` kèm `.gitignore` loại trừ dữ liệu và `outputs/`. Ghi lại hash của dữ liệu theo `cleanup-manifest.json`. 1. `git init` kèm `.gitignore` loại trừ dữ liệu và `outputs/`. Ghi lại hash của dữ liệu theo `cleanup-manifest.json`.
2. ~~Tải về máy `F3_entire.segy` và các horizon.~~ **Đã xong ngày 26/10/2026** (tải F3 Demo 2023 đầy đủ qua gdown; 104 file đã lọc trước đó khớp byte-by-byte với bản mới). Còn thiếu `outputs/`. 2. ~~Tải về máy `F3_entire.segy` và các horizon.~~ **Đã xong ngày 26/10/2026** (tải F3 Demo 2023 đầy đủ qua gdown; 104 file đã lọc trước đó khớp byte-by-byte với bản mới). Còn thiếu `outputs/`.
@@ -549,3 +562,45 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
- **D-3:** field thứ hai. Chốt Volve. - **D-3:** field thứ hai. Chốt Volve.
- **D-4:** venue đích và ngưỡng của các gate (mục 3, mục 6). Giữ đề xuất; quartile chưa tra. - **D-4:** venue đích và ngưỡng của các gate (mục 3, mục 6). Giữ đề xuất; quartile chưa tra.
- **G-A:** điều kiện pivot không thoả, nên sang P2 theo luật đã khoá. - **G-A:** điều kiện pivot không thoả, nên sang P2 theo luật đã khoá.
9. **P2 chạy sớm so với lịch, xong ngày 26/10/2026:**
- Lý thuyết ở [theory.md](docs/theory.md). Code ở `ml_porosity/registration/`, `ml_porosity/losses/` và `scripts/09`–`13`. `configs/protocol_p2.yaml` được khoá bằng SHA-256 trước lưới chính.
- Lưới D2 chính: 128 ô (8 realization × c ∈ {0, 0.5, 1, 2} × N ∈ {2, 4, 8, 16}), mỗi ô 11 phương pháp × 5 seed, chạy hết 89 phút.
- **G-B không đạt.** Ở c = 1, tỉ số RMSE băng M2/B3c là 0.985–1.045 và 0/4 ô đạt. Khi drift = 0, M2 kém B3d 3.9% (macro), vượt ngưỡng 2%. H1 không bị bác, H3 bị bác, H4 không bị bác.
- Chẩn đoán: lấy trung bình trên bank giúp 3–14% so với B3d khi c ≥ 1, nhưng likelihood seismic quá nhọn. ESS ở γ = 1 chỉ ≈ 1/64, nên γ bị ép xuống 0.02–0.11 và warp của M2 không tốt hơn B3c (rủi ro R6, mục 4.8).
- Theo luật đã khoá: chẩn đoán có thời hạn (protocol cho tối đa 2 tuần; lịch nén ngày 27/10/2026 rút còn đến hết 27/10/2026), chỉ trên realization dev, khoá protocol mới rồi chạy lại trên realization mới. Nếu vẫn trượt thì pivot theo mục 9. Chi tiết ở `outputs/p2/summary/main/summary.md` và [report.html](report.html).
10. **Chẩn đoán sau G-B (26/10/2026, chỉ trên realization dev 900/901; chưa khoá):**
- Code: `ml_porosity/registration/smc.py` và `smc_torch.py` (SMC tempering từ mẫu posterior anchor, 8 bước elliptical slice mỗi tầng, ESS ≥ P/2; ước lượng lại pha hằng bằng log Z_w; γ_acf = 1/κ theo tự tương quan phần dư), `scripts/14_diag_posterior.py` (posterior) và `scripts/15_diag_train.py` (huấn luyện, gate kiểu G-B với hai tập đối thủ). Bản torch chạy trên cuda:1, trùng bản numpy tới 1e-11.
- **Posterior là nút thắt.** Ở c = 1, sai số warp của M2 cũ là 3.40/3.21 ms (N = 4/16). SMC với γ_acf và pha ước lượng lại đưa xuống 0.58/0.56 ms, ngang trần dùng wavelet thật; B3c vẫn ở 3.8–4.2 ms. Phần lớn đến từ γ: M2 cũ chỉ đánh lại trọng số mẫu anchor nên luật ESS ép γ xuống (trung vị 0.057, so với 0.41 của γ_acf). Coverage 90% của warp là 0.90–0.98 với γ_acf và 0.73–0.86 với γ = 1; số này gộp theo mẫu thời gian nên không phải claim calibration.
- **Huấn luyện (2 realization × 2 seed).** Nhãn từ posterior SMC đạt mức Oracle: RMSE băng ở c = 1 thấp hơn B3c 22–23%. M2-Sa và M2-S1 đạt gate với tập đối thủ của protocol_p2. Khi thêm đối thủ cùng posterior (B3d-S, một nhãn là warp trung bình của các hạt), mọi biến thể M2-S đều 0/2 ô; tỉ số M2-Sa/B3d-Sa là 0.92–1.03. Điều này khớp Mệnh đề 1: posterior hẹp (độ rộng 90% 0.9–2.9 ms ở c ≤ 1) nên lấy trung bình trên bank gần như không làm mờ.
- λ: với posterior SMC, λ ∈ {1/τ_c, 1, 3, ∞} chênh nhau tối đa 7% RMSE băng; với bank cũ, λ > 1/τ_c kém hơn ở 16/18 cặp (ô, λ).
- Ở c = 2 posterior đa mode và P = 256 chưa ổn định: hai bản lặp lệch > 1 ms ở 10/240 trường hợp, tối đa 5.7 ms. Pha ước lượng lại dao động tới ≈ 10° giữa hai bản lặp.
- **Hệ quả:** H2 không được ủng hộ trước đối thủ cùng posterior; đóng góp đo được là posterior tie (sửa ở mục 11: tie posterior đã có từ Gunning & Glinsky 2006, điều đang kiểm là dùng posterior làm nhãn). Việc còn lại đến hết 27/10/2026 (lịch nén, mục 6): học σ_a, σ_b; lưới stress trên dev (SNR thấp, ít anchor, rock physics sai mô hình) để tìm vùng posterior đủ rộng cho RML. Sau đó hoặc khoá `protocol_p2r` (posterior SMC, thêm B3d-S vào tập đối thủ, realization mới 8–15, P lớn hơn hoặc nhiều lần chạy SMC), hoặc Pivot 1 (mục 9), với phần phương pháp là posterior tie còn RML và nhãn warp trung bình là hai cách dùng posterior đó. Số liệu ở `outputs/p2/diag/` và mục Chẩn đoán sau G-B của [report.html](report.html).
11. **Dev cho P2r (chạy lại P2) và khoá `protocol_p2r` (27/10/2026; dev 900/901, 5 seed; SMC P = 1024):**
- Báo cáo P2 giữ nguyên trong `p2_outcome` của protocol (G-B trượt, H1 không bác, H3 bác, H4 không bác). Lưới chính dùng realization mới 8–15; D2 ở file mới `configs/d2_synth_p2r.yaml`, generator giữ nguyên, chỉ thêm 5 regime R10, R0, Rm5, R0h, R10tb. Chạy dev bằng `scripts/run_p2r_dev.sh` (runlog), tổng hợp bằng `scripts/17_summarize_p2r_dev.py` ra `outputs/p2/diag/p2rdev/summary.md`.
- **Tách H2 thành H2a và H2b.** H2a: nhãn từ warp trung bình của posterior SMC (B3d-Sa) hơn nhãn của tie điểm tốt nhất trong {B3b, B3c, B3c-R}. Trên dev, ở c = 1 với N = 4/16, tỉ số là R10 0.85/0.76 (đạt), R0 0.87/0.89 và Rm5 0.94/0.95 (N = 16 chỉ cải thiện ở 1/2 realization). Khi tính cả B3d, tức warp trung bình của M2 cũ, thì R0 và Rm5 không ô nào đạt, nên so sánh với B3d để thành phân tích phụ. H2b: RML trên bank (M2-Sa) hơn B3d-Sa khi posterior rộng (σ_post ≥ 1.5 ms), lợi ích tăng theo σ_post, và khi hẹp thì không kém quá 2%. Dev N = 16 (21 ô): ρ = −0.63 (p = 0.002), tỉ số < 1 ở 19/19 ô rộng (trung bình 0.89), ô hẹp trung bình 0.98. N = 4 chỉ báo cáo, không claim.
- **Ổn định SMC:** chọn P = 1024, K = 1. Ở SNR 10, c = 1 đạt 4/4 ô (p95 lệch giữa các lần chạy ≤ 0.29 ms); c = 2 đạt 2/4 nên gắn cờ posterior không ổn định và không dùng làm bằng chứng chính. SNR −5, c = 1 đạt 3/4 ô; lệch giữa các lần chạy ≤ 0.34 σ_post.
- **σ_a sai mô hình:** đăng ký với σ_a = 3.5 ms thì sai số warp 5.9 ms, coverage 0.45; với 14 ms thì 3.1 ms, coverage 0.50. Huấn luyện trên các posterior đó: B3d-Sa không còn hơn tie điểm (0/4 ô ở cả hai σ_a). Lợi thế của H2a phụ thuộc σ_a đúng, nên lưới chính có thêm nhánh σ_a ∈ {3.5, 14} ms ở R10 (`grid.sigma_a_arm`) để giới hạn phạm vi claim.
- **H3 với posterior SMC:** mọi ensemble học trên nhãn tốt hơn lại under-cover hơn B5, và Oracle-ens có CE tệ nhất (0.39 so với 0.11 ở c = 1, N = 16). CE so với B5 vì vậy thưởng nhiễu nhãn chứ không đo việc truyền bất định tie. P2r chỉ báo cáo H3 dạng mô tả và cấm claim calibration.
- **F3 trên trục σ_post (chỉ mô tả, P = 256):** với σ_a = 7 ms thì σ_post 2.5–3.4 ms, gần Rm5. Với σ_a ML ≈ 0.4 ms (coi marker TD là chính xác) thì σ_post 0.56–0.64 ms. Vì σ_a không xác định được trên F3, vị trí của F3 không chắc chắn và không suy ra claim F3 từ D2.
- **Cơ chế:** ở SNR −5, lợi ích 4% của M2-Sa vượt cận làm mờ 1/B(σ_post) ≈ 0–2%, nên không quy lợi ích cho khử mờ (Mệnh đề 1) nếu không nằm trong cận này.
- **Diễn đạt:** tie posterior không mới (Gunning & Glinsky 2006, Laplace; Buland & Omre 2003, MCMC); SMC chỉ là công cụ. Điều đang kiểm là dùng tie posterior làm nhãn huấn luyện (warp trung bình hoặc RML trên bank). Câu "đóng góp đo được là posterior tie" ở mục 10 không dùng trong bài.
- **Sơ suất đã ghi nhận:** B(σ) từng được thử trên realization 0–7 của P2; P2r dùng 8–15 nên không ảnh hưởng.
- Khoá: `configs/protocol_p2r.yaml` + `configs/protocol_p2r.sha256`, tag git `protocol-p2r`, trên branch `p2r-protocol`. Bước tiếp theo là lưới chính 8–15 (chưa chạy).
- Đổi tên (27/10/2026, trước khi sinh realization 8–15): bản khoá đầu tên `protocol_p3` (commit cee2ff0, tag `protocol-p3`) nhưng trùng tên với pha P3 (F3 field) ở mục 6, nên đổi thành **P2r** (P2 rerun) cho protocol, `configs/d2_synth_p2r.yaml`, `scripts/run_p2r_dev.sh`, `scripts/17_summarize_p2r_dev.py`, `outputs/p2/diag/p2rdev/`. Nội dung chỉ đổi tên và thêm hai ghi chú `deviation`, `untested_in_diagnosis`; sha mới ở `configs/protocol_p2r.sha256`. Pha P3 F3 chưa có protocol; khi khoá sẽ là `configs/protocol_f3.yaml`.
12. **Chốt P2 (27/10/2026).** Về thí nghiệm, P2 đã đóng; mọi kết luận mới về posterior SMC hay RML chỉ lấy từ lưới chính P2r (realization 8–15).
- **Kết quả đã khoá (protocol_p2, realization 0–7), giữ nguyên:** G-B không đạt (0/4 ô ở c = 1, tỉ số M2/best 0.985–1.045; drift = 0 kém 3.9%). H1 không bị bác, H3 bị bác, H4 không bị bác. Số liệu ở `outputs/p2/summary/main/`, hình `outputs/figures/p2_*.png`. Không chạy thêm gì trên realization 0–7.
- **Chẩn đoán theo luật trượt (λ, prior), chỉ trên dev 900/901:** nút thắt là posterior warp (γ bị luật ESS ép xuống 0.02–0.11, nên warp của M2 ≈ B3c); λ không phải nguyên nhân (≤ 7% giữa các giá trị); đã quét SNR × mật độ anchor và stress σ_a (mục 10–11).
- **Quyết định cuối 27/10:** khoá `protocol_p2r` thay vì Pivot 1.
- **Lệch so với luật đã khoá:** `protocol_p2.yaml` (G-B, `if_fail`) ghi "chẩn đoán ≤ 2 tuần rồi pivot theo mục 9"; phương án chạy lại trên realization mới chỉ được thêm vào plan sau khi G-B trượt. Vì vậy P2r là một pre-registration mới, thiết kế sau khi thấy P2 trượt (chỉ dựa trên dev); kết luận G-B của P2 giữ nguyên. Ghi trong `p2_outcome.deviation` của protocol_p2r và phải nêu trong phần Methods của bài.
- **Chưa kiểm trong chẩn đoán:** σ_b chưa học hay stress; σ_a chỉ stress (3.5 / 14 ms), bản học trên F3 (≈ 0.4 ms, coi marker là chính xác) không đáng tin; stress rock physics sai mô hình bị cắt theo thứ tự cắt phạm vi ở mục 6 (mục 6 của danh sách).
- **Giới hạn bằng chứng:** chẩn đoán chỉ có 2 realization dev nên chỉ dùng để thiết kế P2r, không làm kết quả.
- **Liên quan tới pha P3 (F3 field, G-C):** "chiều cải thiện trên synthetic" của G-C lấy từ lưới chính P2r. Điều kiện coverage 80/90% trong ±5% của G-C nhiều khả năng trượt (dev: mọi ensemble under-cover); ngưỡng không nới, G-C báo cáo đúng như đã đặt.
13. **Lưới chính P2r (27/10/2026, xong 11:29 giờ máy chủ; cuda:0 + cuda:1):** `scripts/run_p2r_main.sh` chạy posterior SMC (P = 1024, K = 1) và huấn luyện (Oracle, B3b, B3c, B3c-R, B3d, B3d-Sa, M2-Sa; 5 seed) trên realization 8–15 cho 5 regime × c ∈ {0, 1, 2} × N ∈ {4, 16}, rồi nhánh σ_a (R10, c = 1, σ_a = 3.5 / 14 ms). Scripts 14/15 chỉ nhận 8–15 khi `protocol_p2r` và các input khớp SHA-256. `scripts/18_summarize_p2r.py` áp đúng luật H2a/H2b/H3 đã khoá → `outputs/p2r/summary/` (verdict.json, summary.md); chạy thử trên dev tái tạo đúng số dev ghi trong protocol. Kết quả báo cáo như ra, kể cả khi trượt. Học σ_a, σ_b và stress rock physics không chạy thêm: protocol đã khoá nên kết quả mới không đổi được luật, và chúng được ghi là giới hạn (`p2_outcome.untested_in_diagnosis`).
14. **Kết quả P2r (27/10/2026; `outputs/p2r/summary/`): mục "khoá protocol_p2r hoặc Pivot 1" đã đóng, không pivot.**
- **H2a: ĐẠT.** R10 ở c = 1, band RMSE của B3d-Sa chia cho point tie tốt nhất: 0.857 (N = 4) và 0.782 (N = 16); 5/5 seed, 6/8 (N = 4) và 8/8 (N = 16) realization; guard c = 0 là 0.83 / 0.79. R0 (0.888 / 0.888) và Rm5 (0.915 / 0.923, đạt nhờ ΔPCC +0.10 / +0.09) cũng đạt. M2-Sa đạt ở cả ba regime này theo cùng luật.
- **So với cả B3d (phụ):** R10 đạt; R0 với B3d-Sa 1/2 ô (M2-Sa 2/2, nhưng M2-Sa không thay được B3d-Sa); Rm5 0/2 (M2-Sa cũng 0/2). Claim "nhãn SMC hơn posterior neo của P2" chỉ cho R10.
- **Nhánh σ_a: trượt** (σ_a = 3.5 ms: 0.98 / 1.14; 14 ms: 0.99 / 0.93). Bài phải nói kết quả H2a cần σ_a được đặt đúng; đây là rủi ro chính cho G-C vì σ_a trên F3 không biết.
- **H2b: ĐẠT.** N = 16: 8/8 ô posterior rộng, ρ(σ_post, tỉ số) = −0.85, permutation p = 1e-4; ô hẹp 0.996. N = 4 (chỉ báo cáo): 6/8, ρ = −0.77.
- **Diễn giải bắt buộc:** B3d-Sa đã hơn point tie ở c = 0 (≈ 0.81), nên phần lớn lợi của H2a không do drift; phần gắn với drift là B3d-Sa gần Oracle và không đổi khi c tăng (R10, N = 16: 0.457 → 0.455) trong khi B3d xấu đi (0.484 → 0.675). Ở phần lớn ô rộng c = 1, lợi của H2b vượt cận 1/B(σ_post), nên không quy hết cho khử nhoè. c = 2 có cờ "unstable posterior", không là bằng chứng chính.
- **H3 (mô tả):** mọi ensemble, kể cả Oracle, under-cover (coverage 90% từ 0.31 đến 0.79, trung vị 0.47); không claim calibration.
- **Vận hành:** lưới bị ngắt lúc 09:44 khi phiên Claude kết thúc; chạy tiếp từ các CSV đã ghi (scripts 14/15 bỏ qua job đã xong; mọi file đã kiểm tra đọc được). Seed của mỗi job cố định nên kết quả không phụ thuộc lịch chạy.

781
docs/technical_overview.md Normal file
View File

@@ -0,0 +1,781 @@
# Tổng quan kỹ thuật: học porosity từ seismic khi well tie không chắc chắn
Cập nhật 27/10/2026, phản ánh trạng thái dự án đến hết ngày 26/10/2026.
Tài liệu này dành cho người mới: chưa làm địa vật lý, chưa quen phần Bayes, hoặc cả hai. Nó giải thích bài toán, ý tưởng, từng thành phần và lý thuyết đằng sau, rồi chỉ ra mỗi thứ nằm ở đâu trong code. Chi tiết đầy đủ, số liệu kiểm tra và chứng minh nằm ở [plan.md](plan.md) và [theory.md](theory.md).
**Cách đọc.**
- Mục 1–3: bức tranh lớn, gần như không có công thức. Đọc trước.
- Mục 4: kiến thức nền. Bỏ qua phần nào đã biết.
- Mục 5–6: phương pháp và lý thuyết.
- Mục 7–10: dữ liệu, đối thủ so sánh, cách đánh giá, kết quả hiện tại.
- Mục 11–12: bản đồ code và bảng thuật ngữ. Gặp từ lạ thì tra mục 12.
---
## 1. Bài toán trong một trang
**Mục tiêu.** Ước lượng **porosity** (độ rỗng: tỉ lệ thể tích lỗ rỗng trong đá) ở mọi điểm của một khối **seismic** 3D, khi chỉ có vài **giếng khoan** đo được porosity.
**Hình dung.** Seismic giống ảnh siêu âm của lòng đất: phủ cả vùng nhưng mờ và gián tiếp. Giếng khoan giống vài mẫu sinh thiết: chính xác nhưng chỉ ở vài chỗ. Ta huấn luyện một mô hình học máy ánh xạ "ảnh seismic quanh giếng → đường porosity của giếng", rồi áp mô hình đó cho toàn khối.
**Chỗ khó.** Hai nguồn dữ liệu dùng hai trục khác nhau:
- Seismic ghi theo **thời gian**: sóng phản xạ mất bao nhiêu mili giây để đi xuống rồi quay lên.
- Log giếng ghi theo **độ sâu**: mét dọc lỗ khoan.
Muốn ghép một mẫu porosity với đúng đoạn seismic tương ứng, ta cần biết độ sâu z ứng với thời gian t nào. Quan hệ này (**time–depth relationship**, TDR) phải ước lượng, và bước ước lượng gọi là **well tie**. Trên dữ liệu F3 dùng trong bài:
- Sai số của TDR lên tới **14–66 ms** tùy giếng, và thay đổi theo độ sâu.
- Một chu kỳ của sóng seismic chỉ khoảng **17–20 ms**.
Nghĩa là nhãn porosity có thể bị đặt lệch **một đến vài chu kỳ** so với seismic. Ta đang dạy mô hình bằng những cặp (input, nhãn) mà nhãn bị trượt đi một lượng không biết trước, khác nhau theo độ sâu.
**Cách làm phổ biến** là chọn một TDR tốt nhất, coi nó là đúng, rồi huấn luyện. **Ý tưởng của bài** là coi độ lệch đó là một **biến ngẫu nhiên chưa biết** (biến ẩn):
1. Ràng buộc nó bằng các điểm neo độc lập (**anchor**) và bằng vật lý truyền sóng.
2. Khi huấn luyện, không chọn một căn chỉnh duy nhất mà **lấy tổng có trọng số trên mọi căn chỉnh hợp lý** (marginalize).
3. Đưa bất định này vào cả cách đánh giá.
Phương pháp có tên làm việc là **RML** (*Registration-Marginalized Learning*).
---
## 2. Vì sao lệch thời gian lại nghiêm trọng
### 2.1 Ví dụ đồ chơi
Giả sử porosity dao động như một hình sin tần số 50 Hz, tức chu kỳ 20 ms.
- Nhãn lệch 5 ms (một phần tư chu kỳ): nhãn và tín hiệu thật có tương quan bằng 0.
- Nhãn lệch 10 ms (nửa chu kỳ): tương quan bằng −1. Nhãn nói "cao" đúng chỗ thực tế "thấp".
Vậy chỉ một độ lệch nhỏ hơn chu kỳ đã đủ biến nhãn thành vô nghĩa, thậm chí ngược dấu, ở các tần số mà seismic mang thông tin.
### 2.2 Học bằng MSE trên nhãn lệch ngẫu nhiên thì học được gì?
Nếu độ lệch δ là ngẫu nhiên, mô hình tối ưu theo MSE sẽ học **trung bình của mọi phiên bản bị dịch** của nhãn. Lấy trung bình nhiều bản dịch của một đường cong là làm mờ nó: các dao động nhanh triệt tiêu nhau, chỉ còn phần chậm.
Đó là nội dung của **Mệnh đề 1** (mục 6.1). Với δ ~ N(0, σ²), biên độ thành phần tần số f bị nhân với
$$
e^{-2\pi^2\sigma^2 f^2}.
$$
Với phổ seismic thật của F3 (tâm khoảng 50 Hz):
| σ_δ | Hệ số ở 40 Hz | Hệ số ở 50 Hz | Phần phương sai trong băng seismic còn lại |
| --- | --- | --- | --- |
| 4 ms | 0.60 | 0.45 | 28% |
| 8 ms | 0.13 | 0.04 | 6% |
| 16 ms | ≈ 0 | ≈ 0 | 2% |
Chỉ cần σ_δ = 8 ms là gần như toàn bộ chi tiết mà seismic có thể cung cấp bị xoá khỏi mục tiêu học. Trên F3, sai số thực tế còn lớn hơn thế.
Phép tính này giải thích các "triệu chứng" của mô hình trong luận văn gốc (code trong `test 2/`):
- dự đoán bị trơn (smoothing);
- phải thêm loss khớp phương sai (L_Var) vì dự đoán co biên độ;
- phải thêm bước tìm best-shift ±64 ms.
Những thứ đó là mẹo chữa triệu chứng. Bài này nhắm vào nguyên nhân.
---
## 3. Ý tưởng và đóng góp
### 3.1 Research gap
Pipeline chuẩn hiện nay: *tie → chuyển nhãn sang thời gian → huấn luyện f(seismic) → đánh giá với nhãn đã tie*. Bất định của tie bị **thu về một điểm trước khi học**. Literature liên quan chia thành ba nhóm tách rời:
| Nhóm | Làm gì | Thiếu gì |
| --- | --- | --- |
| L1: tie tự động, tie có bất định (Buland & Omre 2003; Gunning & Glinsky 2006; Wu & Caumon 2017; Tschannen et al. 2022) | Ước lượng tie, có khi kèm posterior của độ lệch | Dừng ở tie, không đưa bất định sang bước học thuộc tính |
| L2: dự đoán thuộc tính bằng deep learning, có UQ | Học seismic → porosity/impedance, có khi ước lượng bất định | Giả định nhãn đã đăng ký đúng |
| L3: loss chịu lệch thời gian (soft-DTW, DILATE, hard-min shift) | Cho phép dự đoán và nhãn lệch nhau | Không anchor, không vật lý, không bất định có kiểm chứng |
Bài nhắm vào phần giao của ba nhóm: coi sai số đăng ký là biến ẩn, ràng buộc bằng anchor và vật lý, marginalize khi huấn luyện, và tính đến nó khi đánh giá. Theo các lượt tìm kiếm literature đã làm (plan §2.4), chưa thấy công trình nào làm đủ cả bốn việc. Quy tắc viết bài: không dùng chữ "first".
### 3.2 Bốn đóng góp dự kiến
- **C1, lý thuyết.** "MSE dưới misregistration = học một target bị làm mờ" (Mệnh đề 1) và điều kiện nhận dạng (Mệnh đề 2).
- **C2, phương pháp RML.** Prior trên warp có điều kiện theo anchor, likelihood tie vật lý, loss marginal likelihood có hiệu chỉnh.
- **C3, giao thức đánh giá có xét registration.** Gồm benchmark synthetic hiệu chỉnh theo F3 và "phase diagram" cho biết khi nào vấn đề này đáng kể.
- **C4, audit dữ liệu F3** cho bài toán porosity (mục 7.1).
**Không phải đóng góp:** backbone mạng mới, thêm attention, thêm loss, GAN, hay chỉ sửa leakage.
---
## 4. Kiến thức nền
### 4.1 Địa chấn phản xạ (reflection seismic)
**Cách thu.** Nguồn phát sóng âm ở mặt (súng hơi ngoài biển). Sóng đi xuống, gặp ranh giới giữa hai lớp đá thì phản xạ một phần lên. Máy thu ghi lại tín hiệu theo thời gian.
- **Trace:** chuỗi biên độ ghi tại một vị trí, theo thời gian.
- **TWT** (two-way time): thời gian đi xuống và về, tính bằng ms. Trục dọc của seismic là TWT, không phải độ sâu.
- **Bước mẫu** của F3 là 4 ms. Tần số Nyquist khi đó là 125 Hz.
- Các trace xếp thành lưới **inline × crossline**. Mỗi ô của lưới là một **bin**. Cả khối gọi là **cube**. Dữ liệu dùng ở đây là **post-stack**: mỗi bin một trace, đã cộng nhiều lần thu.
**Trở kháng âm và hệ số phản xạ.**
- Acoustic impedance AI = mật độ × vận tốc sóng P.
- Tại ranh giới giữa lớp 1 và lớp 2, hệ số phản xạ là
$$
r = \frac{AI_2 - AI_1}{AI_2 + AI_1}.
$$
**Mô hình tích chập.** Trace seismic xấp xỉ bằng chuỗi hệ số phản xạ theo thời gian tích chập với một xung ngắn gọi là **wavelet**, cộng nhiễu:
$$
s(t) = (w * r)(t) + \text{noise}.
$$
- Wavelet có **băng tần hữu hạn**. F3 có năng lượng ở khoảng 4–83 Hz, đỉnh khoảng 50–60 Hz. Ví dụ wavelet đơn giản: Ricker.
- Wavelet có **pha**: pha không thì đối xứng, pha khác 0 thì méo lệch. Pha thật thường không biết, phải ước lượng.
- **Synthetic seismogram:** lấy log AI ở giếng, chuyển sang thời gian, tính r rồi tích chập với wavelet. Kết quả là trace "nhân tạo", đem so với trace thật tại giếng.
**Hệ quả quan trọng: seismic gần như mù với tần số thấp.** Dưới khoảng 6 Hz, seismic F3 có rất ít năng lượng (dưới 8 Hz chỉ 1–2%). Phần biến thiên chậm của porosity (xu hướng nén chặt theo độ sâu, mức trung bình) không đến từ seismic. Nó đến từ giếng, từ mô hình tần số thấp (**LFM**) hoặc từ xu hướng theo thời gian. Vì vậy bài tách đánh giá thành hai băng:
- **băng thấp** (< f_c = 6 Hz): chủ yếu là xu hướng;
- **băng seismic** (≥ 6 Hz): phần mà seismic thực sự đóng góp, và cũng là phần bị misregistration phá hỏng.
**Horizon:** một mặt phản xạ liên tục được dò (pick) xuyên qua cube, ví dụ nóc một tầng đá. F3 có 7 horizon và một đứt gãy (FaultA).
### 4.2 Log giếng (well logs)
**Độ sâu.**
- **MD** (measured depth): chiều dài dọc lỗ khoan.
- **TVD:** độ sâu thẳng đứng.
- **KB** (kelly bushing): mốc đo trên giàn.
- Cả 4 giếng F3 đều thẳng đứng, nên MD và TVD chỉ khác nhau hằng số KB.
**Các đường log dùng trong bài** (file định dạng **LAS**):
| Log | Đo gì | Đơn vị |
| --- | --- | --- |
| DT (sonic) | thời gian sóng đi qua 1 m đá, tức nghịch đảo vận tốc (slowness) | µs/m |
| RHOB | mật độ khối | kg/m³ |
| GR | phóng xạ gamma tự nhiên, chỉ thị sét | API |
| PHIE | porosity hiệu dụng (đã tính từ các log khác, không đo trực tiếp) | phân số; báo cáo bằng **p.u.** = ×100 |
| AI | trở kháng âm = RHOB × 10⁶ / DT | |
**Rock physics** là các công thức nối thuộc tính đá với log. Ví dụ, porosity theo mật độ:
$$
\varphi = \frac{\rho_{ma} - \rho}{\rho_{ma} - \rho_{fl}},
$$
với ρ_ma là mật độ khung đá và ρ_fl là mật độ chất lưu.
**Phát hiện về nhãn F3** (plan §1.2d). Ở 3/4 giếng:
- PHIE = −0.2018 + 0.0011·DT chính xác (R² = 1.00000);
- đồng thời PHIE = (2650 − RHOB)/1600.
Lý do: mật độ trong bản demo F3 ở các giếng này là mật độ **dự đoán từ sonic**, không phải số đo. Vậy "porosity" của F3 thực chất là **sonic biến đổi tuyến tính**. Dự án chọn nhãn chính là PHIE_DT = −0.2018 + 0.0011·DT cho cả 4 giếng (quyết định D-1) và nói thẳng điều này trong bài. Mặt tốt: chuỗi porosity → DT → RHOB → AI được biết chính xác, nên likelihood tie vật lý (mục 5.5) trên F3 không phải xấp xỉ.
### 4.3 Quan hệ thời gian–độ sâu (TDR)
**Từ sonic.** Thời gian hai chiều tại độ sâu z là tích phân slowness:
$$
t(z) = t_{\text{ref}} + 2\int_{z_{\text{ref}}}^{z} \mathrm{DT}(u)\,du.
$$
**Drift.** Thời gian tích phân từ sonic lệch dần so với thời gian seismic, và lệch càng nhiều khi xuống sâu. Nguyên nhân:
- Sonic đo ở tần số kHz, seismic ở vài chục Hz. Vận tốc phụ thuộc tần số (dispersion), nên sonic thấy đá "nhanh" hơn.
- Sonic chỉ đo vùng sát thành lỗ khoan, có thể bị ảnh hưởng bởi lỗ khoan bị sập rộng (washout).
- Log có đoạn thiếu, và mốc thời gian bắt đầu không chắc chắn.
Trên F3, drift trong cửa sổ 600–1100 ms thay đổi tới 45 ms bên trong một giếng (F06-1). Một độ lệch hằng số (bulk shift) không mô tả được kiểu sai số này.
**Nguồn thông tin độc lập về thời gian.**
- **Checkshot/VSP:** đo trực tiếp thời gian sóng từ mặt xuống các độ sâu trong giếng.
- **Marker:** nóc một tầng đá xác định trên log (biết độ sâu), khớp với horizon trên seismic (biết thời gian). Mỗi marker cho một cặp (z_k, t_k), gọi là **anchor**.
- Lưu ý: trên F3, file "Checkshot" thực ra là các cặp marker–horizon, không phải VSP độc lập. Anchor vì vậy mang sai số pick (σ_a), không được coi là chân lý.
**Bốn TDR mà code dựng cho F3** ([tdr.py](../ml_porosity/data/tdr.py)):
| Tên | Cách dựng | Vai trò |
| --- | --- | --- |
| legacy | tích phân DT, t = 0 tại mẫu LAS đầu, không hiệu chỉnh | tái hiện luận văn, chỉ để audit |
| sonic | tích phân DT qua một điểm neo | trục tham chiếu τ |
| calibrated | co giãn thời gian sonic trong từng khoảng giữa hai anchor để đi qua đúng mọi anchor ("marker-calibrated sonic", thực hành chuẩn trong ngành) | **tham chiếu chấm điểm** |
| wlt | mô hình Depth2Time của OpendTect | phân tích độ nhạy của đánh giá |
Các nguồn này không thống nhất với nhau: chênh lệch giữa chúng là 9–36 ms. Bất định registration vì vậy là **thuộc tính của bài toán**, không chỉ là lỗi trong code.
### 4.4 Well tie
**Well tie** là chỉnh TDR sao cho synthetic seismogram tại giếng khớp nhất với trace seismic thật:
1. Đưa log AI sang thời gian bằng TDR hiện tại.
2. Tính reflectivity và tích chập với wavelet để được synthetic.
3. So với trace thật, dịch hoặc co giãn TDR để tăng độ khớp (tương quan).
4. Lặp lại.
Tie khó vì nghiệm không duy nhất:
- **Cycle skipping:** lệch đúng một chu kỳ vẫn khớp khá tốt.
- **Pha wavelet:** pha chưa biết có thể bù cho một phần dịch thời gian (theory §2.1).
- **Nhiễu:** tương quan cao có thể chỉ do ngẫu nhiên.
### 4.5 Học có giám sát trên chuỗi thời gian
**Dữ liệu cho mạng.**
- **Input X:** patch 3×3 trace seismic quanh giếng, tức 9 kênh. Mỗi kênh dài L = 126 mẫu (600–1100 ms, bước 4 ms) và được chuẩn hoá z-score theo từng kênh trong từng giếng.
- **Output:** đường porosity tại đúng 126 thời điểm đó.
**Backbone CNN–GRU** ([cnn_gru.py](../ml_porosity/models/cnn_gru.py), giữ nguyên kiến trúc của luận văn):
- 3 lớp tích chập 1D có dilation 1, 2, 4, để bắt mẫu hình cục bộ ở nhiều tầm.
- 2 tầng GRU hai chiều, để mỗi điểm "nhìn" được ngữ cảnh cả phía trên lẫn phía dưới.
- Một nhánh skip 1×1 nối thẳng từ input ra output.
**Head heteroscedastic** ([train.py](../ml_porosity/models/train.py), lớp `CNNGRUHetero`): mạng xuất hai đường, μ(t) (dự đoán) và σ(t) > 0 (độ bất định tại từng điểm). Huấn luyện bằng **Gaussian NLL**:
$$
-\log\mathcal N(y;\mu,\sigma^2) = \log\sigma + \frac{(y-\mu)^2}{2\sigma^2} + \tfrac12\log 2\pi .
$$
Chỗ nào khó đoán, mạng được phép khai σ lớn, nhưng phải trả giá ở số hạng log σ.
**Deep ensemble:** huấn luyện M = 5 mạng với seed khác nhau.
- Phương sai tổng = trung bình σ² của các mạng (bất định **aleatoric**, do dữ liệu) + phương sai giữa các μ (bất định **epistemic**, do mô hình).
**Sub-window.** Mỗi giếng chỉ là một chuỗi, và chỉ có vài giếng: luận văn thực chất chỉ có 2 chuỗi huấn luyện. Loss vì vậy tính trên nhiều cửa sổ con 64 mẫu chồng lên nhau (P2: bắt đầu ở 0, 2, …, 62). Các cửa sổ không độc lập; đây chỉ là công cụ tối ưu.
**LOWO** (leave-one-well-out): lần lượt giữ một giếng làm test, huấn luyện trên các giếng còn lại. Với 4 giếng có 4 fold.
### 4.6 Bayes và lấy mẫu: đủ để hiểu RML
**Prior, likelihood, posterior.**
$$
\underbrace{p(u\mid\text{dữ liệu})}_{\text{posterior}} \propto \underbrace{p(\text{dữ liệu}\mid u)}_{\text{likelihood}}\cdot\underbrace{p(u)}_{\text{prior}} .
$$
- Prior: ta tin gì về u trước khi xem dữ liệu.
- Likelihood: u giải thích dữ liệu tốt đến đâu.
- Posterior: niềm tin sau khi kết hợp cả hai.
- Ở đây u là warp (độ lệch thời gian theo độ sâu) của một giếng.
**Gaussian process (GP)** là phân phối xác suất trên các *hàm*. Mỗi lần rút ngẫu nhiên từ GP cho ra một đường cong. GP được xác định bởi:
- hàm trung bình m;
- **kernel** k(x, x'): hai điểm cách nhau bao xa thì giá trị tương quan bao nhiêu.
Bài dùng kernel **Matérn-3/2** với hai tham số:
- σ (biên độ): đường cong dao động mạnh cỡ nào;
- ℓ (độ dài tương quan): bao xa thì hai điểm coi như độc lập. Đường cong rút ra liên tục, khả vi một lần, không trơn quá mức.
**Hyperparameter** là các tham số của prior như (m, σ, ℓ). Chọn chúng bằng **type-II maximum likelihood** (empirical Bayes): chọn bộ giá trị làm cho dữ liệu quan sát (ở đây là anchor) có xác suất cao nhất sau khi đã tích phân hết hàm warp. Nếu thêm prior lên chính hyperparameter thì gọi là **MAP-II**. Chỉ dùng anchor của giếng train, nên không rò rỉ thông tin từ giếng test.
**Xấp xỉ Gaussian (tuyến tính hoá / Laplace).** Khi warp nhỏ, quan hệ giữa warp và thời gian anchor gần tuyến tính, nên posterior gần Gaussian và tính được bằng công thức đóng. Lặp tuyến tính hoá quanh nghiệm hiện tại (Gauss–Newton) cho nghiệm MAP và một Gaussian xấp xỉ quanh đó.
**MCMC và elliptical slice sampling.** Muốn có *mẫu* đúng từ posterior thật (phi tuyến, có ràng buộc), ta dùng MCMC: một chuỗi ngẫu nhiên mà sau đủ lâu, các điểm của nó phân phối theo posterior. **Elliptical slice sampling** (Murray, Adams & MacKay 2010) là một MCMC dành cho trường hợp "prior Gaussian × likelihood bất kỳ":
- Mỗi bước, nó đề xuất các điểm trên một ellipse đi qua điểm hiện tại và một mẫu prior mới.
- Nó co dần góc trên ellipse cho tới khi được chấp nhận.
- Không phải chỉnh bước nhảy bằng tay.
**Importance sampling và ESS** (effective sample size).
- Có S mẫu từ một phân phối q, nhưng muốn phân phối p. Gán cho mẫu s trọng số w_s ∝ p/q.
- ESS đo xem S mẫu có trọng số "đáng giá" bao nhiêu mẫu đều:
$$
\mathrm{ESS} = \frac{(\sum_s w_s)^2}{\sum_s w_s^2}.
$$
- Nếu một mẫu chiếm gần hết trọng số thì ESS ≈ 1. Hiện tượng này gọi là **suy biến trọng số**.
> ⚠️ Trong repo, "ESS" có hai nghĩa: *elliptical slice sampling* (thuật toán lấy mẫu) và *effective sample size* (chỉ số trọng số). Phải đọc ngữ cảnh.
**Tempering.** Nâng likelihood lên luỹ thừa γ ∈ [0, 1]:
- γ = 0 bỏ qua likelihood;
- γ = 1 dùng đủ likelihood;
- γ nhỏ làm phân phối bớt nhọn, giảm suy biến trọng số.
**SMC tempering** (sequential Monte Carlo): bắt đầu từ γ = 0 với một đám "hạt" (mẫu), tăng γ từng bậc nhỏ. Ở mỗi bậc:
1. tính lại trọng số;
2. resample (nhân bản hạt tốt, bỏ hạt kém);
3. di chuyển các hạt bằng vài bước MCMC.
Cách này đến được γ = 1 mà không suy biến trọng số.
**Power likelihood và residual tự tương quan.** Likelihood Gaussian coi 64 mẫu trong cửa sổ là 64 quan sát độc lập. Thực tế các mẫu liên tiếp tương quan với nhau, nên chúng chứa ít thông tin hơn. Coi chúng độc lập làm phân phối quá nhọn (quá tự tin). Cách sửa đơn giản nhất là nâng likelihood lên luỹ thừa λ < 1 (*magnitude adjustment* cho composite likelihood). Đây là nguồn gốc của λ trong RML (mục 5.7).
### 4.7 Căn chỉnh chuỗi thời gian
- **Cross-correlation lag:** dịch cả chuỗi một hằng số để tương quan lớn nhất.
- **DTW** (dynamic time warping): tìm đường căn chỉnh đơn điệu tốt nhất giữa hai chuỗi, cho phép co giãn cục bộ. Dải **Sakoe–Chiba** giới hạn độ lệch tối đa |i − j| ≤ band.
- **Soft-DTW** (Cuturi & Blondel 2017): thay "min trên mọi đường" bằng "soft-min", nên khả vi và dùng được làm loss.
- **DILATE** (Le Guen & Thome 2019): soft-DTW cộng một số hạng phạt độ méo thời gian (TDI).
Các loss này cho phép dự đoán và nhãn lệch nhau, nhưng lệch bao nhiêu thì do chính chúng tự quyết định để khớp tốt nhất. Không có anchor hay vật lý nào ràng buộc. Mệnh đề 2 cho thấy vì sao điều này nguy hiểm.
---
## 5. Phương pháp RML, từng thành phần
### Workflow chi tiết
![Detailed RML workflow: from input data to go/no-go gates](figures/workflow.png)
*Hình 1. Workflow chi tiết. Khung nét đứt là các giai đoạn; mũi tên chấm là luồng phụ: log AI dùng để dựng synthetic, và *True warp* (warp thật, chỉ có trên D2) dùng để chấm sai số warp và huấn luyện Oracle. Nhãn trong hình viết bằng tiếng Anh để dùng thẳng cho paper; bảng dưới ghi tên tiếng Anh của từng giai đoạn trong ngoặc. Bản vector: [workflow.svg](figures/workflow.svg); nguồn TikZ: [workflow.tex](figures/workflow.tex).*
| Giai đoạn | Làm gì | Code |
| --- | --- | --- |
| 1. Tiền xử lý (*Preprocessing*) | Đặt giếng đúng toạ độ rồi trích patch seismic 3×3. Tích phân DT để có trục τ. Ghép marker giếng với horizon seismic thành anchor (τ_k, t_k). | [geometry.py](../ml_porosity/data/geometry.py), [tdr.py](../ml_porosity/data/tdr.py), [horizons.py](../ml_porosity/data/horizons.py) |
| 2. Posterior căn chỉnh (*Registration posterior*) | Prior GP cho warp, cập nhật theo anchor, rồi chấm từng mẫu warp bằng độ khớp synthetic–seismic. Ra S mẫu warp kèm trọng số π_s (mục 5.1–5.5). | [warp_prior.py](../ml_porosity/registration/warp_prior.py), [sampler.py](../ml_porosity/registration/sampler.py), [tie_likelihood.py](../ml_porosity/registration/tie_likelihood.py), [smc.py](../ml_porosity/registration/smc.py) |
| 3. Ngân hàng nhãn (*Label bank*) | Mỗi mẫu warp cho một phiên bản nhãn porosity theo thời gian seismic (mục 5.6). | [labels.py](../ml_porosity/registration/labels.py) |
| 4. Huấn luyện (*Training*) | CNN–GRU nhận patch seismic, dự đoán (μ, σ), học bằng loss RML trên cả bank (mục 5.7). Số bước chọn trên realization dev; ensemble 5 seed. | [bank_train.py](../ml_porosity/models/bank_train.py), [rml.py](../ml_porosity/losses/rml.py) |
| 5. Dự đoán (*Prediction*) | Chỉ cần seismic, không cần warp: ra μ ± σ ở giếng test hoặc cả khối (mục 5.8). | [cnn_gru.py](../ml_porosity/models/cnn_gru.py) |
| 6. Đánh giá (*Evaluation*) | Chấm trên giếng mù với tham chiếu cố định, theo metric và ngưỡng đã khoá trong protocol; so với baseline và Oracle để quyết định cổng (mục 9). | [metrics.py](../ml_porosity/eval/metrics.py) |
Các baseline đi qua cùng luồng này nhưng thay giai đoạn 2–3. Ví dụ, B3b dùng một warp duy nhất (S = 1) từ marker-calibrated sonic; B3d lấy warp trung bình của posterior làm nhãn duy nhất (mục 5.9 và 8).
Dựng lại hình sau khi sửa `workflow.tex`: chạy `xelatex workflow.tex` trong `docs/figures/` rồi xuất `workflow.pdf` sang PNG (200 dpi) và SVG.
### 5.1 Warp: tham số hoá độ lệch thời gian
Gọi **τ** là thời gian sonic (tích phân DT từ một điểm neo) và **t** là thời gian seismic thật. Warp là hàm t(τ) ([warp_prior.py](../ml_porosity/registration/warp_prior.py)):
$$
t(\tau) = \tau + b + \int_{\tau_0}^{\tau}\big(e^{g(\tau')} - 1\big)\,d\tau' ,
\qquad\text{tức là}\qquad \frac{dt}{d\tau} = e^{g(\tau)} .
$$
- **b** (bulk offset): dịch chung cả giếng.
- **g(τ)** (hiệu chỉnh log-slowness): "tốc độ chạy" của đồng hồ seismic so với đồng hồ sonic.
- g = 0.05 nghĩa là thời gian seismic trôi nhanh hơn thời gian sonic khoảng 5%, tương đương vận tốc seismic chậm hơn vận tốc sonic khoảng 5%.
- Drift 66 ms trên khoảng 1000 ms ứng với g cỡ 5–6%, một độ lớn hợp lý về vật lý.
- Vì e^g > 0, t luôn tăng theo τ: **đơn điệu theo cấu trúc**. Lớp đá dưới không bao giờ bị đẩy lên trên lớp đá trên.
Dạng tương đương theo độ sâu: t(z) = t_ref + b + 2∫DT(u)·e^{g(u)} du.
### 5.2 Prior trên warp
- g ~ GP(m_g, Matérn-3/2 với σ_g, ℓ), và b ~ N(0, σ_b²).
- (m_g, σ_g, ℓ) học bằng MAP-II trên anchor của giếng train ([`fit_hyper`](../ml_porosity/registration/warp_prior.py)).
- Ví dụ, fit trên anchor của cả 4 giếng F3 ([`outputs/p2/warp_prior_f3.json`](../outputs/p2/warp_prior_f3.json)) cho m_g ≈ 0.014, σ_g ≈ 0.10, ℓ ≈ 71 ms, σ_b ≈ 19 ms.
- Kiểm tra leave-one-anchor-out: bỏ từng anchor, dự đoán lại nó từ các anchor còn lại. Kết quả: trung bình z² ≈ 0.87, độ phủ 90% ≈ 0.87, tức prior không quá tự tin.
### 5.3 Anchor
Mỗi anchor là một cặp (τ_k, t_k) với mô hình nhiễu pick:
$$
t_k = t(\tau_k) + \varepsilon_k,\qquad \varepsilon_k\sim\mathcal N(0,\sigma_a^2).
$$
Protocol P2 dùng σ_a = 7 ms, lấy từ độ lệch robust (MAD) giữa marker và horizon tại 4 giếng F3. Anchor là thứ **ghim thời gian tuyệt đối** (Mệnh đề 2).
### 5.4 Posterior warp và lấy mẫu
[sampler.py](../ml_porosity/registration/sampler.py):
1. Tính posterior Gaussian xấp xỉ của u = [b, g] bằng Gauss–Newton quanh MAP (`laplace_posterior`).
2. Dùng nó làm "prior" cho elliptical slice sampling, với likelihood là phần sai khác giữa mô hình chính xác (e^g) và bản tuyến tính hoá, cộng ràng buộc |g| ≤ g_max.
3. Lấy S = 64 mẫu warp cho mỗi giếng (`sample_warps`).
Kết quả là 64 ứng viên t⁽ˢ⁾(τ), mỗi cái đi qua các anchor trong phạm vi sai số σ_a.
### 5.5 Likelihood tie vật lý
[tie_likelihood.py](../ml_porosity/registration/tie_likelihood.py). Với mỗi mẫu warp, dựng synthetic từ log AI rồi so với seismic thật tại giếng:
$$
p(\mathbf s_w\mid g) = \mathcal N\big(\mathbf s_w;\ \alpha\,\mathbf W\,\mathbf r_w(g),\ \sigma_n^2\mathbf I\big).
$$
- **r_w(g):** reflectivity theo thời gian khi dùng warp g.
- **W:** tích chập với wavelet thống kê pha không lấy từ các trace giếng train, xoay thêm một pha hằng. Pha này chọn trên lưới 15° bằng marginal likelihood (`fit_phase`).
- **α ≥ 0:** hệ số biên độ. α và σ_n được "profile" (thay bằng giá trị tối ưu), nên log p = −(n/2)·log RSS.
- **Trọng số:** π_s ∝ p_s^γ. Trong protocol P2, γ là giá trị lớn nhất sao cho ESS ≥ S/4 (`temper`).
Có hai biến thể:
- **M1:** chỉ dùng anchor, π_s đều.
- **M2:** anchor + trọng số vật lý. Đây là phương pháp chính.
Chẩn đoán sau G-B (mục 10.3) thay bước trọng số này bằng **SMC tempering** ([smc.py](../ml_porosity/registration/smc.py); bản GPU ở [smc_torch.py](../ml_porosity/registration/smc_torch.py)), với γ chọn theo tự tương quan của phần dư.
### 5.6 Ngân hàng nhãn (label bank)
[labels.py](../ml_porosity/registration/labels.py). Với mỗi mẫu warp s:
1. Đảo ngược t⁽ˢ⁾(τ) để được τ⁽ˢ⁾(t). Phép đảo tồn tại vì warp đơn điệu.
2. Đọc log porosity tại đó:
$$
y^{(s)}(t_i) = (\mathcal A\varphi)\big(\tau^{(s)}(t_i)\big).
$$
- **𝒜** là bộ lọc thông thấp chống alias trước khi lấy mẫu 4 ms. Luận văn nội suy thẳng log bước 0.15 m xuống 4 ms nên nhãn bị alias; bước này sửa lỗi đó.
- Mẫu warp nào không phủ hết cửa sổ chính thì nhận trọng số 0.
Kết quả cho mỗi giếng là một ma trận (S × L): S phiên bản hợp lý của nhãn, kèm trọng số π_s.
### 5.7 Loss RML
[rml.py](../ml_porosity/losses/rml.py), hàm `bank_loss`. Với giếng w, cửa sổ con j (n = 64 mẫu) và ứng viên s, độ khớp của ứng viên s với dự đoán (μ, σ) là
$$
\ell_{wjs} = \sum_{i\in j}\log\mathcal N\big(y^{(s)}_{w,i};\ \mu_i,\ \sigma_i^2\big).
$$
Loss là trung bình theo (w, j) của
$$
\mathrm{RML}_\lambda = -\frac{1}{\lambda n}\log\sum_{s=1}^{S}\pi_{ws}\,e^{\lambda\,\ell_{wjs}} .
$$
**Đọc bằng lời:** trong mỗi cửa sổ, mạng không bị buộc phải khớp một nhãn cố định. Nó được chấm theo "trung bình mềm" trên mọi nhãn hợp lý, có trọng số theo độ tin cậy π của từng căn chỉnh.
**λ điều khiển độ "mềm":**
- **λ → 0:** RML bằng NLL trung bình theo π. Nghiệm μ là nhãn trung bình, tức đúng target bị làm mờ của Mệnh đề 1.
- **λ → ∞:** RML chỉ nhìn ứng viên khớp nhất (hard-min). Mạng có thể chọn căn chỉnh để khớp nhiễu.
- **λ = 1/τ_c** (mặc định):
- τ_c = 1 + 2Σ_k ρ(k)² là độ dài tương quan (tính bằng số mẫu) của nhãn train đã lọc thông cao trên 6 Hz.
- Nó hiệu chỉnh việc 64 mẫu tương quan chứa ít thông tin hơn 64 quan sát độc lập (mục 4.6).
- Trên lưới D2: τ_c ≈ 2.7 mẫu, λ ≈ 0.37.
- Đây là **heuristic**, không phải định lý (theory §3).
**Gradient** của RML là NLL có trọng số: mỗi ứng viên s nhận trọng số r_s = softmax(log π_s + λℓ_s) (theory, Bổ đề 3). Mạng tự nghiêng về những căn chỉnh khớp với dự đoán hiện tại, nhưng bị kìm bởi prior π và bởi λ. Giống một bước EM.
### 5.8 Dự đoán và bất định
- Lúc dự đoán **không cần warp**: input seismic, output (μ, σ). Registration chỉ tác động lúc huấn luyện (nhãn sắc hơn, σ không phải "gánh" sai số căn chỉnh) và lúc đánh giá.
- Bất định tổng: σ² của head cộng phương sai giữa 5 thành viên ensemble (M2-ens).
### 5.9 Các baseline là trường hợp riêng của RML
Bảng này biến ablation thành một con đường đi từ mô hình cũ tới RML (chứng minh ở theory §4, mỗi bổ đề có test trong [tests/test_losses.py](../tests/test_losses.py)):
| Phương pháp | Tương ứng trong RML |
| --- | --- |
| Tie điểm rồi hồi quy (B3) | S = 1. RML suy biến thành Gaussian NLL (Bổ đề 1) |
| Hard-min shift của luận văn (B4a) | bank = nhãn dịch ±8 mẫu, π đều, λ = ∞ (Bổ đề 2, 4) |
| Soft-min theo bulk shift (B4b) | như trên với λ hữu hạn |
| Soft-DTW (B4c) | bank = mọi đường căn chỉnh đơn điệu trong dải, π đều, λ = 2/γ = 20 (Bổ đề 5) |
| **RML (M1, M2)** | bank = mẫu posterior warp có anchor (+ trọng số vật lý), λ = 1/τ_c |
Khác biệt cốt lõi giữa RML và các loss căn chỉnh chung không nằm ở "min hay soft-min". Nó nằm ở **bank đến từ đâu**: posterior có anchor và vật lý, hay mọi dịch chuyển đều được phép như nhau.
---
## 6. Lý thuyết (tóm tắt trực giác)
Chứng minh đầy đủ ở [theory.md](theory.md).
### 6.1 Mệnh đề 1: blur
- **Giả thiết:** độ lệch δ độc lập với seismic và nhãn.
- **Kết luận:** predictor tối ưu theo MSE với nhãn lệch là predictor đúng m(t) = E[y | X] **tích chập với phân phối của δ**:
$$
\hat y^\star(t) = \int p(d)\,m(t+d)\,dd,
\qquad
\delta\sim\mathcal N(\mu_\delta,\sigma^2)\ \Rightarrow\ |P(f)| = e^{-2\pi^2\sigma^2 f^2}.
$$
**Hai hệ quả.**
1. Std ratio (độ lệch chuẩn dự đoán chia độ lệch chuẩn nhãn) và PCC trong băng seismic bị chặn trên bởi các hàm của P(f).
2. Loss khớp phương sai (L_Var) chỉ kéo được *biên độ tổng* về đúng. Nó không khôi phục được phần kết hợp pha đã mất. Tức là dự đoán to ra nhưng vẫn mờ.
**Kiểm chứng (H1).** Huấn luyện MSE với độ lệch δ biết trước, rồi đo hàm truyền thực tế. Tỉ số đo/lý thuyết r(σ) = 1.009, 1.009, 1.007 ở σ = 4, 8, 16 ms, và 1.093 ở 32 ms. Ngưỡng bác bỏ đã đăng ký trước là [0.5, 2], nên mệnh đề **không bị bác bỏ**. Hai giới hạn:
- Chỉ kiểm được dải 7–23 Hz.
- Ở F3 thật, giả thiết độc lập không đúng chặt, vì cùng log DT sinh ra cả nhãn lẫn trục thời gian.
### 6.2 Mệnh đề 2: nhận dạng (vì sao cần anchor)
Nếu dịch *cùng lúc* đầu ra của mạng thêm β và mọi warp thêm β, loss không đổi, trừ hiệu ứng biên. Lý do: mạng dùng chung cho mọi giếng và gần như bất biến với phép dịch. Vậy nếu không có gì ghim thời gian tuyệt đối, mục tiêu có một "sống núi" (ridge) phẳng theo β và nghiệm không xác định.
- **Anchor** thêm độ cong ΣK_w/σ_a² theo β. Độ bất định còn lại của dịch chung là
$$
\operatorname{sd}(\beta) \approx \Big(\frac{\sum_w K_w}{\sigma_a^2}+\frac{N}{\sigma_b^2}\Big)^{-1/2}\approx\frac{\sigma_a}{\sqrt{\sum_w K_w}} .
$$
- **Ví dụ.** 4 giếng × 16 anchor với σ_a = 7 ms cho sd(β) ≈ 0.9 ms. Chỉ có prior σ_b = 50 ms với N = 16 giếng thì sd(β) ≈ 12.5 ms. Ở 20 Hz, mức đó đủ làm hệ số cos(2πfβ) về 0.
- **Hệ quả cho B4a–d.** Các loss căn chỉnh chung không có anchor. Chúng rơi đúng vào trường hợp ridge: mạng và căn chỉnh có thể cùng trôi mà loss không phạt.
- **Likelihood tie** về nguyên tắc ghim được thời gian, vì seismic quan sát trên trục cố định. Nhưng một phép dịch nhỏ gần như đánh đổi được với pha hằng của wavelet, nên thông tin về β chỉ đến từ *độ rộng băng*.
**Kiểm chứng (H4).** Bỏ anchor (chỉ còn vật lý) làm sai số warp tăng từ khoảng 3 ms lên khoảng 31–33 ms và RMSE băng tăng gần gấp đôi. Giả thuyết "anchor là cần thiết" **không bị bác bỏ**.
### 6.3 Phạm vi của lý thuyết
- **Đã chứng minh dưới giả thiết nêu rõ:** Mệnh đề 1, 2 và Bổ đề 1–5.
- **Heuristic:** λ = 1/τ_c.
- **Chưa làm:** chẩn đoán strain energy của warp; tính nhất quán của estimator; RML-EM (M3).
---
## 7. Dữ liệu: ba lớp bằng chứng
### 7.1 D1: F3 Demo 2023 (field chính)
- Khối F3 ở phần Hà Lan của Biển Bắc, bản demo công khai của dGB/OpendTect.
- 4 giếng thẳng đứng: F02-1, F03-2, F03-4, F06-1.
- Cửa sổ chính 600–1100 ms.
- Mỗi giếng có 9–11 anchor trong cửa sổ chính (14–17 trong cửa sổ mở rộng 400–1300 ms).
**Audit dữ liệu phát hiện các lỗi khiến kết quả luận văn không dùng được làm mốc** (plan §1.1–1.2):
- Toạ độ giếng trong code sai 5–11 km. Mọi trace "tại giếng" thực ra không nằm ở giếng.
- TWT tích phân từ DT không hiệu chỉnh drift: lệch 14–66 ms so với marker.
- Giếng validation cũng là giếng train.
- Chỉ có 2 chuỗi huấn luyện.
- Nhãn bị alias.
- MSE 0.015 được báo cáo thực ra ứng với R² ≈ −9.8: tệ hơn đoán hằng số.
- Nhãn PHIE là hàm tuyến tính của sonic ở 3/4 giếng (mục 4.2).
Vì vậy mọi baseline được dựng lại từ đầu (pha P1).
### 7.2 D2: synthetic hiệu chỉnh theo F3 (nơi biết đáp án)
Trên dữ liệu thật không bao giờ biết warp đúng. D2 tạo dữ liệu mô phỏng mà warp thật được biết, để đo trực tiếp ([synth_d2.py](../ml_porosity/data/synth_d2.py), cấu hình [d2_synth.yaml](../configs/d2_synth.yaml)).
**Cách sinh.**
- **Earth model:** khung địa tầng từ 5 horizon thật của F3. Porosity = trend + offset theo đơn vị địa tầng + trường ngẫu nhiên (các quá trình OU).
- **Rock physics** đúng như F3: porosity → DT → RHOB → AI.
- **Seismic:** tích chập với wavelet F3, cộng nhiễu băng hạn SNR 10 dB.
- **Warp thật:** rút từ prior GP fit trên anchor F3, nhân hệ số **c ∈ {0, 0.5, 1, 2}**. c = 0 là không lệch; **c = 1 là mức drift giống F3**.
- **Anchor:** đặt tại biên các đơn vị địa tầng, có nhiễu pick σ_a = 7 ms.
**Lưới thí nghiệm chính của P2.**
- 8 realization (lần sinh ngẫu nhiên earth model) × 4 giá trị c × **N ∈ {2, 4, 8, 16}** giếng train, tổng 128 ô.
- 8 giếng test cố định cho mỗi realization, cách mọi giếng khác ≥ 1 km.
- Realization 900 và 901 chỉ dùng để chọn ngân sách bước huấn luyện, không bao giờ dùng cho kết quả.
- **Oracle:** mô hình huấn luyện trên nhãn với warp *thật*. Chỉ có được trên synthetic; là trần tham chiếu, không phải đối thủ.
### 7.3 D3: Volve (field thứ hai, chưa chạy)
- Mỏ Volve ở phần Na Uy của Biển Bắc, dữ liệu Equinor công bố theo giấy phép CC BY-NC-SA 4.0.
- Vai trò: porosity ở đây (PHIF) tính từ density–neutron, **độc lập với sonic**. Nó phá vỡ cấu trúc "nhãn = hàm của DT" của F3.
- Đã kiểm kê: 10 giếng có marker TWT, cube post-stack ST10010 đã tải và QC.
- Thí nghiệm dự kiến ngày 28–29/10/2026 (pha P4).
Ngoài ra, dữ liệu **NLOG** (cổng dữ liệu dầu khí Hà Lan) được dùng để kiểm tra nhãn F3 bằng RHOB đo thật (`scripts/08_d1_label_check.py`).
---
## 8. Các phương pháp được so sánh
Mọi phương pháp mạng dùng **cùng backbone, cùng input, cùng optimizer và cùng cách chọn ngân sách**. Chúng chỉ khác nhau ở nhãn và loss.
| ID | Mô tả dễ hiểu | Trả lời câu hỏi |
| --- | --- | --- |
| B0a | Đường xu hướng nén chặt theo thời gian, không dùng seismic | Seismic có thêm gì ngoài trend? |
| B0b | Ridge / random forest / GBM trên các attribute seismic (biên độ, envelope, pha và tần số tức thời, relative AI, TWT) | Baseline ML nông nhưng mạnh |
| B1 | Inversion AI cổ điển (PyLops) với LFM từ giếng train, rồi φ = a + b·AI | Baseline địa vật lý mà reviewer sẽ hỏi |
| B2 | CNN–GRU với 6 loss gốc của luận văn, pipeline đã sửa | Nối tiếp luận văn |
| B3a | Tie điểm kiểu luận văn: neo tại anchor nông nhất, không hiệu chỉnh drift | |
| B3b | Tie điểm marker-calibrated sonic | Tie "chuẩn ngành" |
| B3c | B3b + dịch cục bộ theo tương quan synthetic–seismic (như tie thủ công) | Tie điểm tốt nhất có dùng seismic |
| B3d | Một nhãn duy nhất từ warp trung bình có trọng số của posterior M2 | Dùng posterior nhưng không marginalize |
| B4a–d | Nhãn B3b + loss căn chỉnh chung: hard-min shift, soft-min shift, soft-DTW, DILATE | Có cần anchor/vật lý không, hay loss chịu lệch là đủ? |
| B5 | Ensemble 5 seed của B3b | Calibration tốt lên là nhờ mô hình registration hay chỉ nhờ ensemble? |
| **M1** | RML, bank 64 mẫu warp posterior theo anchor, trọng số đều | |
| **M2** | RML, như M1 + trọng số tie vật lý | **Phương pháp chính** |
| M2-ens | Ensemble 5 seed của M2 | So với B5 cho calibration (H3) |
| M3 | RML-EM: cập nhật cả π trong lúc huấn luyện | Hoãn |
| Oracle | Nhãn với warp thật (chỉ D2) | Trần tham chiếu |
---
## 9. Đánh giá
### 9.1 Nguyên tắc chống "gian lận vô tình"
- **Blind well:** giếng test chỉ dùng để chấm điểm. Không dùng DT, RHOB, PHIE hay marker của nó cho huấn luyện, tie, chọn hyperparameter, chọn checkpoint hay dịch hậu kiểm.
- **Tham chiếu chấm điểm cố định:** marker-calibrated sonic, chốt trước khi huấn luyện bất kỳ mô hình nào. Độ nhạy của chính phép chấm được báo cáo bằng cách chấm lại với TDR `.wlt`. Không bao giờ chọn tham chiếu "đẹp nhất".
- **Pre-registration:**
- Protocol, metric và ngưỡng ghi trong [protocol.yaml](../configs/protocol.yaml) (P1) và [protocol_p2.yaml](../configs/protocol_p2.yaml) (P2).
- Mỗi file được khoá bằng SHA-256 trước khi chạy. Script chính từ chối chạy nếu hash không khớp.
- Đổi protocol thì phải tạo version mới.
- **Thống kê trung thực:** báo cáo từng giếng rồi mới trung bình. Không tính p-value trên từng mẫu thời gian như thể chúng độc lập. Sức mạnh thống kê chủ yếu đến từ D2 (bootstrap theo realization).
### 9.2 Metric ([metrics.py](../ml_porosity/eval/metrics.py))
| Nhóm | Metric | Ý nghĩa |
| --- | --- | --- |
| Độ chính xác | RMSE, MAE (p.u.), PCC, R², skill so với B0a | Sai bao nhiêu, đúng hình dạng không |
| Theo băng | RMSE và PCC riêng ở băng thấp (< 6 Hz) và **băng seismic** (≥ 6 Hz) | Seismic có thực sự đóng góp không, hay chỉ có trend |
| Biên độ | std ratio, tỉ số phổ | Kiểm tra trực tiếp hiện tượng blur |
| Calibration | Gaussian NLL, **CRPS**, **coverage** 50/80/90/95% | Khoảng tin cậy 90% có thực sự chứa giá trị thật 90% số lần không |
| Registration | RMSE warp (ms) và coverage 90% của warp (chỉ D2); z-score leave-one-anchor-out (F3) | Bất định của chính warp có đáng tin không |
**Metric quyết định** của gate G-B là **RMSE trong băng seismic**, vì đó là phần misregistration phá hỏng (mục 2.2).
### 9.3 Giả thuyết và cổng go/no-go
| | Giả thuyết | Bác bỏ nếu |
| --- | --- | --- |
| H1 | MSE trên nhãn lệch σ_δ cho dự đoán bị làm mờ đúng như exp(−2π²σ²f²) | Tỉ số đo/lý thuyết ngoài [0.5, 2] |
| H2 | RML tốt hơn tie điểm tốt nhất và loss căn chỉnh chung khi misregistration ≳ 1/8 chu kỳ; ngang bằng khi tie đã tốt | Không có gain so với B3 tốt nhất trong vùng drift thực tế |
| H3 | Khoảng dự đoán của RML calibrate tốt hơn cùng backbone + cùng UQ nhưng không mô hình registration | Coverage chỉ tốt lên nhờ khoảng rộng ra |
| H4 | Không có anchor thì warp và mạng bù trừ nhau; anchor là cần thiết | Bỏ anchor mà kết quả tương đương |
Lộ trình nén (chốt 27/10/2026): xong toàn bộ bài trước thứ 7, 31/10/2026. Có 4 cổng:
- **G-A** (26/10, đã đánh giá): baseline tái lập được.
- **G-B** (26/10, đã đánh giá, không đạt): M2 hơn đối thủ tốt nhất trên D2 ít nhất 10% RMSE băng (hoặc +0.05 PCC băng) ở c = 1, và không kém quá 2% khi c = 0.
- **G-C** (cuối 28/10): kết quả F3 nhất quán với synthetic.
- **G-D** (cuối 29/10): field thứ hai.
Sau đó viết bài 29–30/10 (draft v1, v2), review và nộp ngày 31/10. Lịch chi tiết và thứ tự cắt phạm vi nếu trễ ở plan §6.
Trượt cổng thì chẩn đoán có thời hạn rồi chuyển hướng theo luật đã viết trước (plan §9).
---
## 10. Kết quả hiện tại (đến 26/10/2026)
### 10.1 P1: baseline trên F3 (LOWO 4 giếng, 5 seed)
Nhãn PHIE_DT, tham chiếu calibrated, trung bình 4 giếng ([outputs/p1/summary.md](../outputs/p1/summary.md)):
| | B0a (trend) | B0b-ridge | B1 (inversion) | B2 (luận văn) | B3a | B3b |
| --- | --- | --- | --- | --- | --- | --- |
| RMSE (p.u.) | **2.48** | 2.58 | 3.60 | 3.07 | 2.93 | 2.82 |
| PCC băng seismic | −0.13 | **0.24** | −0.02 | 0.15 | −0.02 | 0.15 |
Đọc kết quả:
- Với 3 giếng train, **không mô hình nào thắng đường trend về RMSE tổng**.
- Tương quan trong băng seismic yếu ở mọi phương pháp (≤ 0.24).
- Tie tốt hơn (B3b so với B3a) giúp rõ rệt.
- Khoảng tin cậy của B3 quá hẹp: coverage 90% chỉ khoảng 0.17.
G-A: điều kiện chuyển hướng không thoả, nên sang P2.
### 10.2 P2: lưới D2 chính (protocol đã khoá)
**G-B không đạt.**
- Ở c = 1, tỉ số RMSE băng M2 / đối thủ tốt nhất là 0.985–1.045. Đối thủ tốt nhất là B3c hoặc B3d. 0/4 ô đạt.
- Ở c = 0, M2 kém B3d 3.9%, vượt ngưỡng 2%.
Những điểm vẫn đáng chú ý:
- So với tie chuẩn B3b, M2 giảm RMSE băng 12–28% ở c = 1.
- Các loss căn chỉnh chung không giúp: B4c/B4d chỉ ngang B3b, còn B4a/B4b kém hơn rõ. Điều này nhất quán với Mệnh đề 2.
**Các giả thuyết.**
- H1 **không bị bác** (mục 6.1).
- H3 **bị bác**: M2-ens calibrate kém hơn B5. Ở chế độ ít giếng, mọi loss có σ học được đều làm σ co lại vì mạng nhớ nhãn train.
- H4 **không bị bác** (mục 6.2).
### 10.3 Chẩn đoán sau G-B (chỉ trên realization dev, chưa khoá)
**Nút thắt là posterior warp, không phải loss.**
- Trọng số vật lý của M2 quá nhọn: ESS ở γ = 1 chỉ ≈ 1/64. Quy tắc ESS ≥ S/4 vì vậy ép γ xuống 0.02–0.11, và mẫu warp gần như không mang thông tin seismic.
- Thay bằng SMC tempering (γ theo tự tương quan phần dư, pha ước lượng lại), sai số warp ở c = 1 giảm từ khoảng 3.3 ms xuống khoảng 0.57 ms. B3c vẫn ở 3.8–4.2 ms.
- Nhãn từ posterior SMC cho kết quả gần Oracle: RMSE băng thấp hơn B3c 22–23% ở c = 1.
**Marginalize trên bank chưa thêm được gì.** So với đối thủ dùng *cùng posterior* nhưng chỉ lấy một nhãn trung bình (B3d-S), M2-S không thắng (tỉ số 0.92–1.03). Điều này khớp Mệnh đề 1: posterior hẹp (độ rộng 90% chỉ 0.9–2.9 ms ở c ≤ 1), nên các ứng viên trong bank gần như trùng nhau và trung bình trên bank không làm mờ đáng kể.
**Hệ quả hiện tại.**
- H2 chưa được ủng hộ trước đối thủ cùng posterior. Cải thiện đo được đến từ **posterior tie** (anchor + vật lý + SMC); tie posterior tự nó không mới (Gunning & Glinsky 2006; Buland & Omre 2003), nên điều đem ra kiểm là dùng posterior làm nhãn huấn luyện.
- Cập nhật 27/10/2026: đã khoá `protocol_p2r` (H2 tách thành H2a/H2b, H3 chỉ mô tả, nhánh σ_a); chi tiết ở plan §12 mục 11.
- Việc còn lại đến hết 27/10/2026:
- học σ_a, σ_b;
- chạy lưới stress (SNR thấp, ít anchor, rock physics sai mô hình) để tìm vùng mà posterior đủ rộng cho RML có tác dụng.
- Sau đó chọn một trong hai:
- khoá `protocol_p2r` với posterior SMC và thêm B3d-S vào tập đối thủ;
- hoặc **Pivot 1** (plan §9): bài phân tích về sai số registration của nhãn, với posterior tie là phương pháp, còn RML và nhãn warp trung bình là hai cách dùng posterior đó.
---
## 11. Bản đồ code
### 11.1 Module ([ml_porosity/](../ml_porosity/))
| Khái niệm | File |
| --- | --- |
| Bin ↔ toạ độ XY từ `.survey` | [data/geometry.py](../ml_porosity/data/geometry.py) |
| Đọc LAS, SEG-Y, horizon, dữ liệu Volve | [data/las_io.py](../ml_porosity/data/las_io.py), [data/seismic_io.py](../ml_porosity/data/seismic_io.py), [data/horizons.py](../ml_porosity/data/horizons.py), [data/volve_io.py](../ml_porosity/data/volve_io.py) |
| TDR (legacy, sonic, calibrated) | [data/tdr.py](../ml_porosity/data/tdr.py) |
| Log độ sâu → thời gian có chống alias | [data/resample.py](../ml_porosity/data/resample.py) |
| Wavelet (Ricker, thống kê, xoay pha, bình phương tối thiểu) | [data/wavelet.py](../ml_porosity/data/wavelet.py) |
| Reflectivity, synthetic, dịch cục bộ | [data/synthetic.py](../ml_porosity/data/synthetic.py) |
| Bộ sinh D2 | [data/synth_d2.py](../ml_porosity/data/synth_d2.py) |
| Prior GP warp, posterior tuyến tính hoá, MAP-II, leave-one-anchor-out | [registration/warp_prior.py](../ml_porosity/registration/warp_prior.py) |
| Elliptical slice sampling, ESS, tempering | [registration/sampler.py](../ml_porosity/registration/sampler.py) |
| Likelihood tie vật lý, chọn pha | [registration/tie_likelihood.py](../ml_porosity/registration/tie_likelihood.py) |
| SMC tempering (CPU / GPU) | [registration/smc.py](../ml_porosity/registration/smc.py), [registration/smc_torch.py](../ml_porosity/registration/smc_torch.py) |
| Ngân hàng nhãn theo mẫu warp | [registration/labels.py](../ml_porosity/registration/labels.py) |
| Tie điểm B3a–d, sai số warp | [registration/ties.py](../ml_porosity/registration/ties.py) |
| Đăng ký một ô D2: ghép tất cả các bước trên | [registration/pipeline.py](../ml_porosity/registration/pipeline.py) |
| Loss RML / hard-min, λ = 1/τ_c | [losses/rml.py](../ml_porosity/losses/rml.py) |
| Soft-DTW, DILATE | [losses/softdtw.py](../ml_porosity/losses/softdtw.py) |
| 6 loss của luận văn | [losses/legacy_v2.py](../ml_porosity/losses/legacy_v2.py) |
| CNN–GRU, head heteroscedastic, huấn luyện P1 | [models/cnn_gru.py](../ml_porosity/models/cnn_gru.py), [models/train.py](../ml_porosity/models/train.py) |
| Huấn luyện chung cho mọi phương pháp P2 | [models/bank_train.py](../ml_porosity/models/bank_train.py) |
| Baseline B0b (attribute) và B1 (inversion) | [baselines/attributes.py](../ml_porosity/baselines/attributes.py), [baselines/inversion.py](../ml_porosity/baselines/inversion.py) |
| Metric điểm, theo băng, calibration | [eval/metrics.py](../ml_porosity/eval/metrics.py) |
### 11.2 Chạy
Cài đặt và bảng mô tả từng script ở [README.md](../README.md). Thứ tự:
- `scripts/run_p0.sh`: hạ tầng và test.
- `scripts/run_p1.sh`: audit F3 và baseline LOWO.
- `scripts/run_p2.sh`: prior warp, D2, lưới chính, H1, tổng hợp; chạy trên GPU `cuda:1`.
- `scripts/14_diag_posterior.py` và `scripts/15_diag_train.py`: chẩn đoán sau G-B.
Test nằm trong [tests/](../tests/). Các test quan trọng cho lý thuyết nằm ở [test_losses.py](../tests/test_losses.py) (các trường hợp riêng của RML) và [test_registration.py](../tests/test_registration.py).
---
## 12. Thuật ngữ
| Thuật ngữ | Nghĩa |
| --- | --- |
| Acoustic impedance (AI) | Mật độ × vận tốc sóng P. Thay đổi AI tạo ra phản xạ |
| Anchor | Cặp (độ sâu, thời gian) độc lập với sonic, ở đây là marker khớp horizon. Có sai số pick σ_a |
| Băng seismic / băng thấp | Phần tín hiệu ≥ 6 Hz (seismic có thông tin) / < 6 Hz (chủ yếu trend) |
| Bank (ngân hàng nhãn) | S phiên bản nhãn ứng với S mẫu warp, kèm trọng số π |
| Blind well | Giếng test hoàn toàn không đóng góp vào huấn luyện |
| Bulk shift | Dịch toàn bộ chuỗi một hằng số thời gian |
| Calibration | Mức khớp giữa bất định khai báo và sai số thực |
| Checkshot / VSP | Đo trực tiếp thời gian truyền sóng tới các độ sâu trong giếng |
| Coverage | Tỉ lệ giá trị thật nằm trong khoảng dự đoán ở một mức danh nghĩa |
| CRPS | Điểm đánh giá cả độ chính xác lẫn độ sắc của phân phối dự đoán (càng nhỏ càng tốt) |
| Cycle skipping | Tie khớp nhầm lệch đúng một chu kỳ wavelet |
| Drift | Lệch tích luỹ theo độ sâu giữa thời gian sonic và thời gian seismic |
| DT (sonic) | Slowness của sóng P, µs/m |
| ESS | (1) Elliptical slice sampling: thuật toán MCMC. (2) Effective sample size: số mẫu hiệu dụng của bộ trọng số |
| Gaussian process (GP) | Phân phối xác suất trên hàm, xác định bởi trung bình và kernel |
| Heteroscedastic | Mạng dự đoán cả độ bất định σ(t) thay đổi theo từng điểm |
| Horizon | Mặt phản xạ được dò liên tục trong cube seismic |
| Inline / crossline / bin | Hai trục của lưới khảo sát và một ô của lưới |
| λ (lambda) | Luỹ thừa trong RML, điều khiển giữa trung bình (λ → 0) và hard-min (λ → ∞) |
| LFM | Low-frequency model: mô hình phần tần số thấp, thường nội suy từ giếng theo horizon |
| LOWO | Leave-one-well-out cross-validation |
| Marginalize | Lấy tổng (tích phân) theo một biến chưa biết thay vì cố định nó ở một giá trị |
| Marker | Nóc tầng đá xác định trên log giếng |
| MD / TVD / KB | Độ sâu đo dọc lỗ khoan / độ sâu thẳng đứng / mốc đo trên giàn |
| Misregistration / registration | Sai lệch / việc căn chỉnh giữa trục thời gian của nhãn và của seismic |
| Oracle | Mô hình huấn luyện với warp thật (chỉ có trên synthetic) |
| PCC | Hệ số tương quan Pearson |
| PHIE / PHIE_DT | Porosity hiệu dụng trong LAS / nhãn chính của dự án = −0.2018 + 0.0011·DT |
| p.u. | Porosity unit = porosity × 100 |
| Phase diagram | Bản đồ kết quả theo (mức drift c × số giếng N) |
| Post-stack | Seismic đã cộng các lần thu, mỗi bin một trace |
| Pre-registration | Chốt protocol và ngưỡng trước khi chạy, khoá bằng hash |
| Realization | Một lần sinh ngẫu nhiên earth model synthetic |
| Reflectivity | Chuỗi hệ số phản xạ theo thời gian |
| RML | Registration-Marginalized Learning, phương pháp của bài |
| Rock physics | Quan hệ giữa thuộc tính đá (porosity) và log (DT, RHOB, AI) |
| SMC tempering | Lấy mẫu bằng một đám hạt, tăng dần luỹ thừa likelihood γ từ 0 tới 1 |
| Soft-DTW / DILATE | Loss căn chỉnh chuỗi khả vi, không có anchor |
| Std ratio | Độ lệch chuẩn dự đoán / độ lệch chuẩn nhãn. Nhỏ hơn 1 nghĩa là dự đoán bị co |
| Synthetic seismogram | Trace seismic nhân tạo dựng từ log giếng và wavelet |
| τ (tau) | Thời gian sonic: tích phân DT từ một điểm neo |
| Tempering (γ) | Nâng likelihood lên luỹ thừa γ ≤ 1 để bớt nhọn |
| TDR | Time–depth relationship: ánh xạ độ sâu ↔ thời gian |
| Trace | Chuỗi biên độ seismic tại một vị trí |
| TWT | Two-way time: thời gian sóng đi xuống và về (ms) |
| Type-II ML / MAP-II | Chọn hyperparameter của prior bằng cực đại marginal likelihood (có thêm hyperprior thì là MAP-II) |
| Warp | Hàm t(τ) đơn điệu biến thời gian sonic thành thời gian seismic; gồm b và g |
| Wavelet | Xung seismic có băng tần hữu hạn; tích chập với reflectivity cho trace |
| Well tie | Chỉnh TDR để synthetic khớp seismic tại giếng |
---
## 13. Đọc tiếp
- [plan.md](plan.md): kế hoạch đầy đủ, số liệu audit, thiết kế thí nghiệm, rủi ro và các hướng pivot.
- [theory.md](theory.md): chứng minh Mệnh đề 1–2, heuristic λ, Bổ đề 1–5.
- [research/porosity-research-gap-survey.md](research/porosity-research-gap-survey.md): survey literature (mã P01–P15).
- [research/porosity-references.bib](research/porosity-references.bib): tài liệu tham khảo.
- [`report.html`](../report.html): báo cáo tiến độ có hình.
- Tài liệu gốc nên đọc trước:
- Cuturi & Blondel (2017), soft-DTW;
- Murray, Adams & MacKay (2010), elliptical slice sampling;
- Buland & Omre (2003), tie Bayes;
- Lakshminarayanan et al. (2017), deep ensembles;
- Gneiting & Raftery (2007), CRPS và scoring rules.

400
docs/theory.md Normal file
View File

@@ -0,0 +1,400 @@
# Lý thuyết cho P2: Mệnh đề 1, Mệnh đề 2 và RML
Ngày 26/10/2026. Tài liệu này viết phần lý thuyết mà [plan.md](plan.md) §4.6 yêu cầu, ở dạng sẽ đưa vào phụ lục bài báo.
- Mục 1–2 là chứng minh, đúng dưới các giả thiết được nêu rõ.
- Mục 3 là **heuristic**, không phải định lý.
- Mục 4 là các bổ đề ngắn nối các baseline của plan §4.5 với RML. Mỗi bổ đề có test số tương ứng trong `tests/test_losses.py`.
- Kết quả thực nghiệm chỉ được nhắc khi nó kiểm chứng trực tiếp một mệnh đề (H1, mục 1.3). Phần còn lại nằm trong báo cáo P2.
## 0. Ký hiệu
- t: thời gian seismic (ms). X: seismic đầu vào quanh giếng. y(t): nhãn theo thời gian khi registration đúng.
- Với F3, nhãn là PHIE_DT = −0.2018 + 0.0011·DT, tức một hàm tuyến tính của DT.
- Với D2, nhãn là log sinh tổng hợp.
- δ(t): sai số registration. Nhãn quan sát là ỹ(t) = y(t + δ(t)), cùng quy ước với plan §2.3.
- m(t) = E[y(t) | X] là predictor oracle, tức predictor tối ưu MSE khi nhãn đúng. Phần dư e = y − m.
- Biến đổi Fourier: ĝ(f) = ∫ g(t) e^{−i2πft} dt. Phép dịch (T_β h)(t) = h(t − β) có đáp ứng e^{−i2πfβ}.
- Phổ: S_a là phổ của a, S_ab là phổ chéo của a và b. Trung bình theo phổ: ⟨h⟩_S = ∫ h S df / ∫ S df.
- Băng seismic:
- Toán tử B giữ phần |f| ≥ f_c, với f_c = 6 Hz. Ký hiệu a_b = B a.
- Code dùng Butterworth bậc 4 pha không. Đáp ứng của bộ lọc này thực và không âm, nên mọi công thức dưới đây vẫn đúng khi thay S bằng |H_B|² S.
- Các phát biểu theo phổ giả thiết (X, y) dừng bậc hai theo t. Đây là giả thiết làm việc, không đúng chặt cho log giếng.
- ℓ (không chỉ số) là độ dài tương quan của GP warp. ℓ_s là log-likelihood của thành viên s trong bank (mục 3–4). S (không chỉ số) là số thành viên của bank.
- c ∈ {0, 0.5, 1, 2} là hệ số drift của lưới D2. Warp thật là g = c·(m_g + σ_g ε_g) và b = c·σ_b ε_b, với ε_g là GP Matérn-3/2 chuẩn hoá (độ dài ℓ), ε_b ~ N(0, 1), và (m_g, σ_g, ℓ, σ_b) fit trên anchor F3 (`ml_porosity/data/synth_d2.py`). c = 1 là mức F3.
## 1. Mệnh đề 1 (blur)
**Giả thiết.**
- (A1) Với mọi t, δ(t) độc lập với (X, y(·)) và có phân phối p_t.
- (A2) E[y(t)²] < ∞.
**Mệnh đề 1.** Predictor tối ưu MSE cho nhãn quan sát là
\[
\hat y^\star(t)=\mathbb E[\tilde y(t)\mid X]=\int p_t(d)\,m(t+d)\,\mathrm dd .
\]
Nếu p_t ≡ p không phụ thuộc t, ŷ⋆ là m đi qua một bộ lọc tuyến tính bất biến thời gian. Đáp ứng của bộ lọc là hàm đặc trưng của δ tại 2πf:
\[
P(f)=\mathbb E\big[e^{\,i2\pi f\delta}\big],
\qquad
\delta\sim\mathcal N(\mu_\delta,\sigma^2)\ \Rightarrow\ P(f)=e^{\,i2\pi f\mu_\delta}\,e^{-2\pi^2\sigma^2 f^2}.
\]
**Chứng minh.**
1. Theo (A1), E[y(t + δ(t)) | X, δ(t) = d] = E[y(t + d) | X] = m(t + d).
2. Lấy kỳ vọng theo δ(t) ~ p_t, vốn độc lập với X, rồi đổi thứ tự tích phân (Fubini, nhờ A2), được công thức đầu.
3. Khi p_t ≡ p, ŷ⋆(t) = ∫ p(d) m(t + d) dd. Biến đổi Fourier của m(· + d) là e^{i2πfd} m̂(f), nên ŷ⋆ có biến đổi Fourier P(f) m̂(f). ∎
**Nhận xét.**
1. Chỉ phân phối biên của δ(t) tại từng t ảnh hưởng tới ŷ⋆.
- Cấu trúc tương quan của δ theo t (drift trơn hay nhiễu i.i.d.) không đổi predictor tối ưu ở mức quần thể.
- Nó vẫn ảnh hưởng tới việc học với mẫu hữu hạn và tới bank của RML. Vì vậy mức ảnh hưởng thực tế vẫn phải đo trên synthetic (plan §2.3).
2. Nếu μ_δ ≠ 0, P có thêm pha tuyến tính, tức predictor tối ưu bị dịch đi −μ_δ. Phần dịch chung này đúng là hướng không xác định được trong Mệnh đề 2.
3. (A1) là giả thiết mô hình.
- Ở F3, cùng một log DT sinh ra cả nhãn lẫn trục thời gian (plan §1.2), nên δ không độc lập với y.
- H1 kiểm mệnh đề trong điều kiện (A1) được dựng đúng.
4. Nếu phân phối biên thay đổi chậm theo t (drift tăng theo độ sâu), ŷ⋆ là một bộ lọc biến thiên theo thời gian. Về cục bộ, nó vẫn là P với σ(t).
### 1.1 Hệ quả (i): cận của std ratio và PCC trong băng
**Hai đẳng thức về phổ.** E[e(t) | X] = 0, còn m(t') là hàm của X, nên Cov(e(t), m(t')) = 0 với mọi t, t'. Do đó S_ym = S_m và S_y = S_m + S_e.
**Phương sai và hiệp phương sai trong băng.** Đặt ŷ_b = B ŷ⋆. B và bộ lọc P giao hoán. Vì δ thực nên P(−f) = P(f)*. Từ đó
\[
\operatorname{Var}\hat y_b=\int_{|f|\ge f_c}|P|^2S_m\,\mathrm df,\qquad
\operatorname{Cov}(\hat y_b,y_b)=\int_{|f|\ge f_c}\operatorname{Re}P\;S_m\,\mathrm df .
\]
**Cận.** Lấy trung bình ⟨·⟩ theo S_{m_b}:
\[
\frac{\operatorname{sd}\hat y_b}{\operatorname{sd}y_b}=\sqrt{\langle|P|^2\rangle}\;\frac{\operatorname{sd}m_b}{\operatorname{sd}y_b}\ \le\ \sqrt{\langle|P|^2\rangle}\ \le\ \sup_{|f|\ge f_c}|P(f)|,
\qquad
\operatorname{PCC}_b(\hat y^\star)=\kappa(P)\,\operatorname{PCC}_b(m),\quad
\kappa(P)=\frac{\langle\operatorname{Re}P\rangle}{\sqrt{\langle|P|^2\rangle}} .
\]
- PCC_b(m) = sd(m_b)/sd(y_b) ≤ 1, vì Cov(m_b, y_b) = Var m_b.
- Theo Cauchy–Schwarz, κ(P) ≤ ⟨|P|⟩ / √⟨|P|²⟩ ≤ 1. Dấu bằng xảy ra khi và chỉ khi P là hằng số dương trên giá của S_{m_b}.
**Diễn giải.**
- **Coherence theo từng tần số không đổi.** |S_ŷy|² / (S_ŷ S_y) = S_m / S_y ở mọi f có P(f) ≠ 0.
- Ở mức quần thể, blur không xoá thông tin. Nó dồn trọng số về tần số thấp, nên PCC tính gộp cả băng giảm theo hệ số κ(P).
- Muốn đảo ngược phải nhân với e^{+2π²σ²f²}. Điều này không làm được: σ và p chưa biết, và sai số ước lượng của ŷ ở nơi |P| ≈ 0 sẽ bị khuếch đại. Trong thực hành, phần tín hiệu đó coi như mất.
- **Cận sup |P| yếu** vì băng bắt đầu từ f_c = 6 Hz: σ = 8 ms cho sup |P| = 0.955.
- Con số có ý nghĩa là dạng trung bình theo phổ. Đó chính là cột "cả phổ" trong bảng ở plan §2.3.
- **Nếu μ_δ ≠ 0** thì Re P = e^{−2π²σ²f²} cos(2πfμ_δ), làm PCC giảm thêm.
### 1.2 Hệ quả (ii): L_Var chỉ chỉnh biên độ
**Thiết lập.** Xét mọi predictor h là hàm của X có phương sai hữu hạn; các moment lấy trung bình theo t trong cửa sổ. Mục tiêu là
\[
J(h)=\mathbb E\|h-\tilde y\|^2+\Psi(\mathbb E h,\operatorname{Var}h),
\]
với Ψ tuỳ ý, chỉ phụ thuộc trung bình và phương sai của dự đoán. Ví dụ: phạt (std ratio − 1)² của L_Var trong v2.
**Mệnh đề.** Mọi nghiệm tối ưu có dạng h⋆ − E h⋆ = a(ŷ⋆ − E ŷ⋆) với a ≥ 0.
**Chứng minh.**
1. Vì ŷ⋆ = E[ỹ | X], ta có E‖h − ỹ‖² = E‖h − ŷ⋆‖² + E‖ŷ⋆ − ỹ‖².
2. Cố định E h và Var h = v. Khi đó E‖h − ŷ⋆‖² = (E h − E ŷ⋆)² + v + Var ŷ⋆ − 2 Cov(h, ŷ⋆), nhỏ nhất khi Cov(h, ŷ⋆) lớn nhất.
3. Theo Cauchy–Schwarz, Cov(h, ŷ⋆) ≤ √(v Var ŷ⋆). Dấu bằng xảy ra khi và chỉ khi h − E h = a(ŷ⋆ − E ŷ⋆) với a = √(v / Var ŷ⋆).
4. Tối ưu tiếp theo (E h, v) chỉ chọn a và hằng số. ∎
**Hệ quả.**
- Khi a > 0, PCC và PCC_b của h⋆ bằng của ŷ⋆.
- Phổ trong băng của h⋆ vẫn có hình dạng |P|² S_m, chỉ nhân với a².
- L_Var có thể đưa std ratio toàn phần về 1. Nhưng tỉ lệ biên độ giữa băng seismic và băng thấp vẫn theo |P|, nên L_Var không khôi phục được phần kết hợp pha đã mất do blur.
- Phát biểu này ở mức quần thể, giả thiết mạng đủ năng lực. Với mạng hữu hạn, nó chỉ là xấp xỉ.
### 1.3 Kiểm chứng: H1
**Thiết kế** (`scripts/12_h1_blur.py`).
- Huấn luyện MSE (MSE0, ngân sách 500) với c = 0 và N = 16, trên nhãn bị dịch δ_wj = σ z_wj, z ~ N(0, 1).
- δ_wj không đổi trong mỗi cửa sổ 64 mẫu và độc lập với mọi thứ khác, nên (A1) đúng theo cách dựng.
**Ước lượng.** Theo Mệnh đề 1 và mục 1.1, phổ chéo giữa nhãn thật Y và dự đoán Ŷ_σ thoả E[Y* Ŷ_σ] ∝ P_σ S_m. Vì vậy
\[
\hat H_\sigma(f)=\frac{\sum\operatorname{Re}\big[Y^*(f)\,\hat Y_\sigma(f)\big]}{\sum\operatorname{Re}\big[Y^*(f)\,\hat Y_0(f)\big]}\ \longrightarrow\ P_\sigma(f)=e^{-2\pi^2\sigma^2f^2}.
\]
- Tổng chạy qua giếng test, realization và seed (cửa sổ Hann, NFFT 256).
- r(σ) là trung bình nhân của Ĥ_σ/P_σ trên các tần số thoả cả ba điều kiện: f ≥ f_c, P_σ ≥ 0.1, và S_0 ≥ 0.1·max S_0 trong băng.
- H1 bị bác bỏ nếu r ∉ [0.5, 2].
**Kết quả** (protocol đã khoá, 8 realization × 5 seed, `outputs/p2/h1/h1.json`):
| σ | r(σ) | CI 95% | Số tần số | Dải tần dùng |
| --- | --- | --- | --- | --- |
| 4 ms | 1.009 | [0.996, 1.019] | 17 | 6.8–22.5 Hz |
| 8 ms | 1.009 | [0.990, 1.025] | 17 | 6.8–22.5 Hz |
| 16 ms | 1.007 | [0.975, 1.038] | 15 | 6.8–20.5 Hz |
| 32 ms | 1.093 | [1.046, 1.143] | 4 | 6.8–9.8 Hz |
H1 không bị bác bỏ. Có hai giới hạn:
1. **Dải tần hẹp.** Điều kiện S_0 ≥ 0.1·max chỉ giữ lại 7–23 Hz. Đây là nơi predictor MSE0 có công suất kết hợp với nhãn: 72% phổ chéo trong băng. H1 kiểm định lượng Mệnh đề 1 trong dải này và không cho biết gì về phần trên khoảng 23 Hz.
2. **σ = 32 ms lệch nhẹ.** Suy giảm đo được yếu hơn lý thuyết khoảng 9%, và CI không chứa 1. Mức lệch này vẫn nằm trong ngưỡng đã đăng ký trước. Nguyên nhân chưa xác định.
### 1.4 Hệ quả cho nhãn từ posterior tie: khi nào RML có thể hơn nhãn trung bình (H2a, H2b của protocol_p2r)
**Thiết lập.** Posterior tie (SMC) cho các hạt τ_k(t). Có hai cách dùng posterior này:
- B3d-S: nhãn tại warp trung bình τ̄(t);
- M2-S: bank nhãn từ các hạt, huấn luyện bằng RML.
Gọi δ(t) = τ̄(t) − τ(t) là sai số của warp trung bình. Nếu posterior hiệu chỉnh tốt, Var δ(t) ≈ σ_post(t)², với σ_post là độ lệch chuẩn posterior của τ(t). Script dùng σ_post = (q95 − q05)/3.29, trung bình trên cửa sổ chính.
**Hệ quả.**
1. Áp Mệnh đề 1 cho B3d-S (xem (A1) là xấp xỉ). Predictor tối ưu là m làm mờ bởi P(f) ≈ e^{−2π²σ_post²f²}.
2. RML không thể làm tốt hơn Oracle (nhãn tại warp thật). Vì vậy lợi ích tối đa của M2-S so với B3d-S là phần mất mát do blur này.
3. Ở 50 Hz, P = 0.95 / 0.90 / 0.82 khi σ_post = 1 / 1.5 / 2 ms. Đây là lý do protocol_p2r lấy σ_post ≥ 1.5 ms làm ranh giới "posterior rộng".
**Cận định lượng.**
- Hệ số truyền tại một tần số không phải là con số quyết định metric. Mục 1.3 cho thấy predictor chỉ có công suất kết hợp với nhãn trong khoảng 7–23 Hz. Ở 20 Hz, σ = 1.5 ms cho P = 0.98.
- Vì vậy ta đo trực tiếp B(σ) = band_rmse(blur_σ(μ)) / band_rmse(μ), với μ là dự đoán của Oracle trên realization dev (`scripts/17_summarize_p2r_dev.py`, phần blur).
- Nếu RML khử hết blur, tỉ số M2-S/B3d-S tốt nhất là ≈ 1/B(σ_post).
- Trên dự đoán MSE0 của H1 (σ ∈ {4, 8} ms), B(σ) tính theo cách này khớp với suy giảm đo được: 1.33 so với 1.38, và 1.85 so với 1.91. Cách tính vì vậy dự báo đúng mức phạt của nhãn lệch.
- Với predictor N = 4 nhiễu, làm mờ nhẹ (σ ≲ 2.5 ms) có thể *giảm* band RMSE, vì bộ lọc cắt bớt phần dự đoán sai ở tần số cao. Khi đó lợi ích tối đa của RML bằng 0 cho tới khi σ_post vượt qua mức đó. Số liệu dev đầy đủ ở báo cáo p2rdev.
**Giới hạn.**
- δ của warp trung bình không độc lập với y. τ̄ được ước lượng từ chính seismic mà mạng dùng làm input.
- Posterior có thể đa mode (bước nhảy chu kỳ). Khi đó sai số của τ̄ có đuôi nặng hơn Gauss, và phạt thực tế lớn hơn B(σ_post). Dev c = 2 cho thấy B3d-Sa kém Oracle 13% trong khi B(RMSE warp) chỉ dự báo vài %.
- Vì vậy B(σ) là kỳ vọng định hướng, không phải cận chặt. H2b được kiểm bằng thực nghiệm.
- Dev ở SNR −5 dB vi phạm "cận" này theo chiều ngược lại. Input nhiễu làm dự đoán Oracle vốn đã mượt, nên B(σ) ≈ 1.00 tới σ = 3 ms (1/B ≈ 0.98–1.00). Dù vậy M2-Sa/B3d-Sa đo được là 0.93–0.96 ở N = 16. Phần lợi ích này không đến từ khử blur theo Mệnh đề 1. Hai giải thích ứng viên, chưa tách được trên dev: (i) bank nhãn chống cho mạng nhớ một nhãn lệch duy nhất, tức một dạng tăng cường nhãn; (ii) τ̄ lệch có hệ thống khi posterior đa mode. Vì thế báo cáo không được gán lợi ích của RML cho cơ chế blur, trừ khi có bằng chứng riêng.
## 2. Mệnh đề 2 (nhận dạng)
**Thiết lập.**
- Giếng train w = 1..N có seismic X_w, log theo độ sâu φ_w, và warp u_w = (b_w, g_w) như plan §4.1.
- Nhãn theo warp u là y^u(t) = (𝒜φ)(z_u(t)), với z_u là ánh xạ ngược của t_u và 𝒜 là bộ lọc chống alias (plan §4.3).
- e_b là hướng "cộng cùng một β vào b_w của mọi giếng".
- Mục tiêu MAP đồng thời theo (θ, u) là
\[
\Phi(\theta,\mathbf u)=\sum_w\Big[\,\mathcal L_w\big(\theta;\,y^{u_w}_w\big)+\log p(u_w)+\sum_{k}\log\mathcal N\big(t_{wk};\,t_{u_w}(z_{wk}),\sigma_a^2\big)\Big],
\]
- 𝓛_w là log-likelihood Gaussian trên các cửa sổ. Với RML, áp cùng phép dịch cho mọi mẫu warp trong bank; lập luận không đổi.
**Giả thiết (B): lớp mô hình đóng dưới phép dịch đầu ra.** Với mỗi θ và mỗi β (bội của Δt, |β| ≤ β_max), tồn tại θ' sao cho μ_θ'(X) = T_β μ_θ(X) và σ_θ'(X) = T_β σ_θ(X).
- Đúng chính xác khi lớp mô hình chứa phép dịch đầu ra. Ví dụ: mạng tích chập hoàn toàn có tầng cuối đủ rộng để dời tap kernel đi c mẫu.
- Đúng xấp xỉ với CNN–biGRU.
- Trong mọi trường hợp, chỉ đúng tới hiệu ứng biên của cửa sổ hữu hạn.
**Mệnh đề 2.** Dưới (B):
(a) **Không anchor thì có một ridge.** Giả sử không có anchor, prior của b phẳng (σ_b → ∞) và không có số hạng tie seismic. Khi đó Φ(θ', u + β e_b) = Φ(θ, u), tới hiệu ứng biên.
- Mục tiêu có một ridge theo β. Ridge này chung cho mọi giếng vì mạng dùng chung.
- Posterior theo β không proper và MAP không duy nhất.
(b) **Prior Gaussian của b.** Với b_w ~ N(0, σ_b²), Φ có thêm số hạng −Σ_w (b_w + β)² / (2σ_b²), với độ cong N/σ_b² theo β.
(c) **Anchor.** Anchor với σ_a hữu hạn thêm số hạng −Σ_{w,k} (t_wk − t_{u_w}(z_wk) − β)² / (2σ_a²), với độ cong Σ_w K_w / σ_a² theo β. K_w là số anchor của giếng w. Theo xấp xỉ bậc hai dọc ridge:
\[
\operatorname{sd}(\beta)\approx\Big(\frac{\sum_wK_w}{\sigma_a^2}+\frac{N}{\sigma_b^2}\Big)^{-1/2}\approx\frac{\sigma_a}{\sqrt{\sum_wK_w}} .
\]
- Ví dụ có anchor: 4 giếng × 16 anchor với σ_a = 7 ms cho sd(β) ≈ 0.9 ms.
- Nếu chỉ có prior σ_b = 50 ms (giá trị trong protocol P2), sd(β) ≈ 50/√N: 35 ms với N = 2 và 12.5 ms với N = 16.
- Cả hai đều lớn so với chu kỳ trong băng seismic. Theo nhận xét cuối mục 1.1, dịch chung β nhân thành phần tần số f của PCC với cos(2πfβ), và cos(2π · 20 Hz · 12.5 ms) = 0.
**Chứng minh.**
1. t_{u + β e_b}(z) = t_u(z) + β, nên z_{u + β e_b}(t) = z_u(t − β), tức y^{u + β e_b} = T_β y^u.
2. Theo (B), μ_θ' = T_β μ_θ và σ_θ' = T_β σ_θ.
3. Log-likelihood Gaussian trên cửa sổ I là tổng các số hạng log N(y(t_i − β); μ(t_i − β), σ²(t_i − β)), tức là log-likelihood của cửa sổ I − β. Lấy tổng theo các cửa sổ phủ đều chuỗi, hai giá trị chỉ khác nhau ở các mẫu biên.
4. Log-sum-exp của RML giữ tính bất biến này vì mọi thành viên bị dịch như nhau. Prior của g không đổi vì g giữ nguyên. Từ đó có (a).
5. (b) và (c) tính trực tiếp, vì t_{u + β e_b}(z_wk) = t_{u_w}(z_wk) + β. ∎
### 2.1 Số hạng tie seismic (plan §4.2)
s_w được quan sát trên trục thời gian cố định, còn synthetic α_w W_a r_w(u_w) dịch theo warp. Vì vậy likelihood seismic không bất biến theo β, và về nguyên tắc ghim được thời gian tuyệt đối.
Tuy nhiên, phép dịch gần như có thể đánh đổi với pha hằng của wavelet:
- Dịch β nhân phổ với e^{−i2πfβ}. Xoay pha ψ nhân phổ với e^{−iψ sgn f}.
- Hai phép trùng nhau tại tần số f_0 = ψ/(2πβ). Ở tần số khác chúng lệch nhau 2π(f − f_0)β.
- Vì vậy thông tin về β đến từ độ rộng băng, không đến từ tần số trung tâm. Ví dụ: với β = 4 ms, độ lệch pha tối đa trong băng ±30 Hz quanh f_0 chỉ khoảng 43°.
Hệ quả trong pipeline:
- Pha được chọn bằng marginal likelihood trên các mẫu warp đã có anchor (`fit_phase`, lưới 15°).
- Trong ablation H4 (không anchor), biến thể không anchor được cho biết pha đúng bằng 0, để hai hiệu ứng không lẫn vào nhau.
### 2.2 Hệ quả cho các phương pháp trong P2
- **M1/M2 là quy trình hai bước.**
- Bước 1: tính posterior warp từ anchor (và tie seismic, với M2), không dùng mạng.
- Bước 2: huấn luyện mạng trên bank với π cố định.
- Thời gian tuyệt đối vì vậy do posterior warp quyết định. Với K_w ≈ 16 anchor mỗi giếng (14–21 trên D2) và σ_a = 7 ms, dịch chung của mỗi giếng có sd ≈ σ_a/√K_w ≈ 1.75 ms.
- **B4a–B4d** chọn căn chỉnh theo độ khớp với chính dự đoán của mạng, và không có anchor.
- Trong phạm vi bank (±8 mẫu = ±32 ms, hoặc dải soft-DTW 8 mẫu), chúng rơi vào trường hợp (a): mục tiêu không xác định dịch chung của mạng và căn chỉnh.
- Dịch chung chỉ bị chặn bởi biên của bank, bởi hiệu ứng biên cửa sổ (soft-DTW buộc đường đi qua hai góc) và bởi khởi tạo.
- **Biến thể không anchor của M2** (H4) chỉ còn tie seismic để ghim thời gian, nên chịu sự đánh đổi với pha ở mục 2.1.
### 2.3 Warp linh hoạt
Ngoài hướng dịch chung, g còn nhiều bậc tự do. Warp có thể căn chỉnh theo noise để nhãn khớp với dự đoán hiện tại.
- Mức linh hoạt bị giới hạn bởi (σ_g, ℓ), học bằng MAP-II từ anchor của giếng train, và bởi tempering γ.
- Chẩn đoán *strain energy* mà plan yêu cầu **chưa làm** trong P2. Thay vào đó báo cáo:
- warp RMSE và độ phủ 90% so với warp thật (chỉ có trên D2);
- z-score leave-one-anchor-out trên F3 (`outputs/p2/warp_prior_f3.json`).
## 3. Chọn λ = 1/τ_c (heuristic)
**Vì sao cần λ.**
- Log-likelihood của một cửa sổ là tổng của n = 64 số hạng. Chênh lệch giữa hai thành viên bank có độ lớn O(n), nên với λ = 1, log-sum-exp gần như dồn hết trọng số vào một thành viên và RML gần với hard-min (Bổ đề 2).
- Residual lại tự tương quan, nên 64 mẫu chứa ít thông tin hơn 64 quan sát độc lập. Coi chúng là độc lập (composite likelihood) làm phân phối trên bank quá nhọn.
**Lập luận.** Chênh lệch log-likelihood giữa hai thành viên s, s' là Δ = Σ_i d_i, với
\[
d_i=\frac{(y_{s',i}-\mu_i)^2-(y_{s,i}-\mu_i)^2}{2\sigma_i^2}=\frac{(y_{s',i}-y_{s,i})\,(y_{s',i}+y_{s,i}-2\mu_i)}{2\sigma_i^2}.
\]
d_i là tích của hai quá trình. Nếu hai quá trình này Gaussian, tâm 0, độc lập với nhau và có cùng ACF ρ, thì Corr(d_i, d_{i+k}) = ρ(k)², và
\[
\operatorname{Var}\Delta\approx n\operatorname{Var}(d)\,\tau_c,\qquad \tau_c=1+2\sum_{k\ge1}\rho(k)^2 .
\]
- Với λ = 1/τ_c, λΔ có cùng trung bình và phương sai với chênh lệch log-likelihood của n/τ_c quan sát độc lập.
- Đây là dạng đơn giản nhất của *magnitude adjustment* cho composite likelihood: nâng composite likelihood lên một luỹ thừa vô hướng (Pauli, Racugno & Ventura 2011; Ribatet, Cooley & Davison 2012).
**Cài đặt** (`effective_lambda` trong `ml_porosity/losses/rml.py`).
- Residual chưa có trước khi huấn luyện, nên ρ được lấy từ ACF gộp của nhãn train đã lọc thông cao trên f_c. Đây là proxy cho residual trong băng seismic.
- Tổng được cắt ở độ trễ đầu tiên có ρ ≤ 0 (tối đa 32).
- λ được tính lại cho từng ô từ nhãn train, không dùng nhãn test.
- Trên lưới chính: τ_c ≈ 2.7 mẫu (2.4–3.5) và λ ≈ 0.37 (0.29–0.42), gần như không đổi theo c.
**Giới hạn.**
1. ρ² chỉ đúng khi d_i không có thành phần trung bình. Lệch hệ thống giữa hai thành viên, hoặc bias của μ, thêm các số hạng có ACF là ρ chứ không phải ρ², khi đó λ nên nhỏ hơn.
2. Dùng nhãn làm proxy thay cho residual là một sai khác so với plan §4.4.
3. Hai tài liệu về magnitude adjustment chưa có trong bib và chưa được đối chiếu toàn văn.
## 4. Các baseline là trường hợp riêng của RML (plan §4.5)
**Định nghĩa.** Xét một cửa sổ n mẫu và bank S thành viên, với trọng số π_s > 0 và Σπ_s = 1:
\[
\ell_s=\sum_{i=1}^{n}\log\mathcal N\big(y_{s,i};\mu_i,\sigma_i^2\big),\qquad
\mathrm{RML}_\lambda=-\frac{1}{\lambda n}\log\sum_{s}\pi_s\,e^{\lambda\ell_s},\qquad
\mathrm{RML}_\infty=-\frac{1}{n}\max_s\ell_s .
\]
Loss huấn luyện là trung bình của RML_λ theo cửa sổ và giếng (`bank_loss`; λ = None nghĩa là hard-min). Các cửa sổ cố định, bắt đầu ở 0, 2, …, 62.
### Bổ đề 1 (S = 1)
Nếu S = 1, hoặc mọi thành viên trùng nhau, thì RML_λ = −ℓ/n, tức Gaussian NLL, với mọi λ.
- Các baseline tie-then-regress B3a–B3d và Oracle là trường hợp này, mỗi cái với một warp điểm.
- Test: `test_single_or_identical_members_give_gaussian_nll`.
### Bổ đề 2 (kẹp giữa hard-min và trung bình theo π)
**Phát biểu.** Đặt M(λ) = λ⁻¹ log E_π e^{λℓ}. Khi đó RML_λ = −M(λ)/n không tăng theo λ, và
\[
-\frac1n\max_s\ell_s\ \le\ \mathrm{RML}_\lambda\ \le\ -\frac1n\sum_s\pi_s\ell_s,\qquad
\lim_{\lambda\to0}\mathrm{RML}_\lambda=-\frac1n\sum_s\pi_s\ell_s,\qquad
\lim_{\lambda\to\infty}\mathrm{RML}_\lambda=\mathrm{RML}_\infty .
\]
Với π đều, 0 ≤ RML_λ − RML_∞ ≤ log S / (λn). Cận trên đạt được trong giới hạn ℓ_s → −∞ với mọi thành viên trừ thành viên tốt nhất.
Test: `test_rml_between_hard_min_and_mixture_mean` và `test_rml_small_lambda_is_pi_weighted_nll`.
**Chứng minh.**
1. Đặt Λ(λ) = log E_π e^{λℓ} = λM(λ), và r_λ ∝ π e^{λℓ} là phân phối nghiêng. Khi đó Λ' = E_{r_λ} ℓ.
2. λΛ' − Λ = E_{r_λ}[λℓ − Λ] = KL(r_λ‖π), nên M'(λ) = (λΛ' − Λ)/λ² = KL(r_λ‖π)/λ² ≥ 0.
3. Giới hạn: Λ(λ) = λ E_π ℓ + O(λ²) khi λ → 0, và Λ(λ)/λ → max ℓ khi λ → ∞.
4. Với π đều, E_π e^{λℓ} ≥ e^{λ max ℓ}/S. ∎
**Ý nghĩa của hai giới hạn.**
- **λ → ∞, σ cố định.** Với bank gồm các dịch chuyển nguyên trong ±8 mẫu và π đều, RML_∞ bằng min theo dịch chuyển của MSE cửa sổ / (2σ²) cộng hằng số. Đó là hard-min shift L_XCorr của v2.
- B4a là trường hợp này với σ được học (heteroscedastic), tức hard-min của Gaussian NLL.
- **λ → 0.** Nghiệm theo μ là μ_i⋆ = Σ_s π_s y_{s,i}, tức nhãn trung bình theo π. Đây đúng là nhãn bị blur của Mệnh đề 1 với p = π.
- Nếu σ cũng được học thì σ_i⋆² = Var_π(y_{s,i}): độ phân tán của bank bị hấp thụ vào σ. Đây là chế độ thất bại "σ_θ phình ra" ở plan §4.8.
- λ = 1/τ_c nằm giữa hai cực này.
### Bổ đề 3 (gradient là NLL có trọng số)
\[
\nabla_\theta\,\mathrm{RML}_\lambda=-\frac1n\sum_s r_s\,\nabla_\theta\ell_s,\qquad r=\operatorname{softmax}(\log\pi+\lambda\ell).
\]
- Mỗi bước gradient là một bước M tổng quát hoá, với trọng số r là bước E tính tại θ hiện tại.
- RML-EM của plan (M3, cập nhật cả π) chưa làm.
- Test: `test_rml_gradient_is_responsibility_weighted`.
### Bổ đề 4 (B4a, B4b)
- B4b là RML với bank dịch chuyển ±8 mẫu (`shift_K` trong protocol), π đều và λ = 1/τ_c hữu hạn.
- B4a dùng cùng bank đó với λ = ∞.
### Bổ đề 5 (soft-DTW là RML trên mọi căn chỉnh)
**Định nghĩa.**
- D_ij = −log N(y_j; μ_i, σ_i²) (`nll_cost`).
- 𝒫 là tập đường căn chỉnh đơn điệu từ (0, 0) tới (n−1, n−1) nằm trong dải Sakoe–Chiba |i − j| ≤ band. (Ký hiệu 𝒜 đã dành cho bộ lọc chống alias.)
- ⟨A, D⟩_w là tổng chi phí của đường A theo trọng số bước symmetric2 (Sakoe & Chiba 1978): bước chéo ×2, bước ngang/dọc ×1, ô đầu ×2.
- Soft-DTW (Cuturi & Blondel 2017) với bước này là sDTW_γ(D) = −γ log Σ_{A∈𝒫} e^{−⟨A,D⟩_w/γ}.
**Phát biểu.**
\[
\frac{\mathrm{sDTW}_\gamma(D)}{2n}=\mathrm{RML}_{\lambda=2/\gamma}\Big[\text{bank}=\mathcal P,\ \pi\ \text{đều},\ \ell_A=-\tfrac12\langle A,D\rangle_w\Big]-\frac{\gamma}{2n}\log|\mathcal P| .
\]
- Hằng số cuối không ảnh hưởng tới gradient.
- Trên đường chéo, ℓ_A đúng bằng log-likelihood Gaussian của cửa sổ.
- Vậy B4c là RML với bank gồm mọi căn chỉnh đơn điệu trong dải, prior đều (không vật lý, không anchor), và λ = 2/γ.
- Với γ = 0.1 trong protocol, λ = 20. Như vậy B4c gần hard-min hơn nhiều so với λ ≈ 0.37 của M1/M2.
**Chứng minh.** Thay trực tiếp vào định nghĩa: RML_λ = −(λn)⁻¹ log Σ_A |𝒫|⁻¹ e^{−λ⟨A,D⟩_w/2}. Với λ = 2/γ, biểu thức này bằng −(γ/2n) log Σ_A e^{−⟨A,D⟩_w/γ} + (γ/2n) log|𝒫|. ∎
**Vì sao dùng symmetric2.**
- Mọi đường đều có tổng trọng số n + m = 2n. Cộng một hằng số vào D vì vậy dịch mọi ⟨A, D⟩_w như nhau, nên không có thiên lệch theo độ dài đường.
- Với bước chuẩn (mọi ô trọng số 1), đường dài hơn đi qua nhiều ô hơn. Vì NLL có thể âm khi σ nhỏ, soft-DTW chuẩn sẽ ưu tiên các đường dài, không chéo.
- Với band = 0 chỉ còn đường chéo, và sDTW/(2n) bằng NLL trung bình. Test: `test_band0_reduces_to_nll`.
**DILATE (B4d).**
- Loss: L = [α·sDTW_γ(D) + (1 − α)·TDI] / (2n), với TDI = ⟨A⋆, Ω⟩ và Ω_ij = ((i − j)/n)².
- A⋆ = ∇_D sDTW_γ(D) là căn chỉnh kỳ vọng, đã gồm trọng số bước: ∂R/∂D_ij = E_ij(2q_0 + q_1 + q_2).
- E_ij = ∂R_{n−1,n−1}/∂R_ij.
- q_0 là xác suất softmin của bước chéo vào ô (i, j); q_1, q_2 là của hai bước còn lại.
- Gradient ∇_D TDI = ∇²_D sDTW · Ω là một tích Hessian–vector.
- Nó được tính bằng đạo hàm forward-mode của lượt backward (Mensch & Blondel 2018), trong `dilate_loss_fast` (numba, float64).
- Kết quả được kiểm khớp với double-backprop của autograd. Test: `test_fast_matches_autograd`.
- Hai sai khác so với Le Guen & Thome (2019):
1. Chi phí là Gaussian NLL thay cho bình phương sai số.
2. Dùng bước symmetric2 thay cho bước chuẩn. Vì A⋆ gồm trọng số bước, ô đi vào bằng bước chéo được tính hai lần trong TDI.
## 5. Phạm vi
- **Đã chứng minh, dưới giả thiết đã nêu.**
- Mệnh đề 1 và hai hệ quả: ở mức quần thể, cho predictor tối ưu MSE, dưới (A1); phần phổ cần thêm giả thiết dừng.
- Mệnh đề 2: dưới (B); sd(β) là xấp xỉ bậc hai.
- Bổ đề 1–5: chính xác, có test số.
- **Heuristic.** λ = 1/τ_c (mục 3).
- **Chưa làm.**
- Tính nhất quán của estimator marginal likelihood (tuỳ chọn ở plan §4.6).
- Chẩn đoán strain energy.
- RML-EM (M3).
## Tài liệu
Đã có trong [porosity-references.bib](research/porosity-references.bib):
- Cuturi & Blondel (2017), Soft-DTW, ICML. Khoá `cuturi2017softdtw`.
- Le Guen & Thome (2019), DILATE, NeurIPS. Khoá `leguen2019dilate`.
- Murray, Adams & MacKay (2010), elliptical slice sampling, dùng trong sampler warp. Khoá `murray2010ess`.
**Chưa có trong bib/refs**; thông tin xuất bản lấy từ OpenAlex ngày 26/10/2026:
- Mensch & Blondel (2018), Differentiable dynamic programming for structured prediction and attention, ICML, PMLR 80. arXiv 1802.03676.
- Pauli, Racugno & Ventura (2011), Bayesian composite marginal likelihoods, *Statistica Sinica* 21, 149–164. **Chưa đọc toàn văn.**
- Ribatet, Cooley & Davison (2012), Bayesian inference from composite likelihoods, with an application to spatial extremes, *Statistica Sinica* 22, 813–845. arXiv 0911.5357. **Chưa đọc toàn văn.**
- Sakoe & Chiba (1978), Dynamic programming algorithm optimization for spoken word recognition, *IEEE TASSP* 26(1), 43–49. DOI 10.1109/TASSP.1978.1163055.

130
logs/index.csv Normal file
View File

@@ -0,0 +1,130 @@
run_id,parent,name,status,exit_code,start,end,wall_s,wall,device,git,dirty,code_sha,source,cmd
20261026-035632_01_build_wells,,01_build_wells,ok,,2026-10-26T03:56:32+00:00,2026-10-26T03:56:34+00:00,1.6,0:00:02,,d11b7b1,True,,backfill,.venv/bin/python scripts/01_build_wells.py
20261026-035935_run_p0,,run_p0,unknown,,2026-10-26T03:59:35+00:00,2026-10-26T03:59:53+00:00,17.4,0:00:17,,d11b7b1,True,,backfill,scripts/run_p0.sh
20261026-042407_04_wavelet_tie,,04_wavelet_tie,ok,,2026-10-26T04:24:07+00:00,2026-10-26T04:24:12+00:00,4.7,0:00:05,,d11b7b1,True,,backfill,.venv/bin/python scripts/04_wavelet_tie.py
20261026-043014_05_lowo,,05_lowo,ok,,2026-10-26T04:30:14+00:00,2026-10-26T04:30:52+00:00,37.6,0:00:38,cpu,d11b7b1,True,,backfill,".venv/bin/python scripts/05_lowo.py --only B0a,B0b,B1"
20261026-043124_05_lowo,,05_lowo,ok,,2026-10-26T04:31:24+00:00,2026-10-26T04:46:48+00:00,923,0:15:23,cuda (CUDA_VISIBLE_DEVICES=1),d11b7b1,True,,backfill,"CUDA_VISIBLE_DEVICES=1 PYTHONWARNINGS=ignore .venv/bin/python scripts/05_lowo.py --only B2,B3a,B3b --workers 12"
20261026-044655_06_summarize_p1,,06_summarize_p1,ok,,,2026-10-26T04:46:55+00:00,,,,d11b7b1,True,,backfill,.venv/bin/python scripts/06_summarize_p1.py
20261026-094732_09_fit_warp_prior_f3,,09_fit_warp_prior_f3,ok,,2026-10-26T09:47:32+00:00,2026-10-26T09:48:53+00:00,80.2,0:01:20,,a76e61398a3e,True,,backfill,.venv/bin/python scripts/09_fit_warp_prior_f3.py
20261026-103025_11_run_d2,,11_run_d2,ok,0,2026-10-26T10:30:25+00:00,2026-10-26T10:40:36+00:00,611,0:10:11,cuda:1,a76e61398a3e,True,,backfill,.venv/bin/python scripts/11_run_d2.py --dev --workers 4
20261026-104517_11_run_d2,,11_run_d2,interrupted,,2026-10-26T10:45:17+00:00,2026-10-26T10:51:24+00:00,367.0,0:06:07,cuda:1,a76e61398a3e,True,,backfill,.venv/bin/python scripts/11_run_d2.py --main --workers 6 --device cuda:1
20261026-104935_10_build_d2,,10_build_d2,ok,0,2026-10-26T10:49:35+00:00,2026-10-26T10:49:59+00:00,24.0,0:00:24,cpu,a76e61398a3e,True,,backfill,OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 .venv/bin/python scripts/10_build_d2.py
20261026-105134_11_run_d2,,11_run_d2,ok,0,2026-10-26T10:51:34+00:00,2026-10-26T12:20:30+00:00,5335,1:28:55,cuda:1,a76e61398a3e,True,,backfill,.venv/bin/python scripts/11_run_d2.py --main --workers 6 --device cuda:1
20261026-105357_12_h1_blur,,12_h1_blur,ok,0,2026-10-26T10:53:57+00:00,2026-10-26T10:59:45+00:00,348,0:05:48,cuda:1,a76e61398a3e,True,,backfill,.venv/bin/python scripts/12_h1_blur.py --workers 3 --device cuda:1
20261026-110344_13_summarize_p2,,13_summarize_p2,ok,,,2026-10-26T11:03:44+00:00,,,cpu,a76e61398a3e,True,,backfill,timeout 600 .venv/bin/python scripts/13_summarize_p2.py --mode dev --n-boot 500
20261026-122045_13_summarize_p2,,13_summarize_p2,ok,,,2026-10-26T12:20:45+00:00,,,cpu,a76e61398a3e,True,,backfill,.venv/bin/python scripts/13_summarize_p2.py --mode main
20261026-122338_pytest,,pytest,ok,0,2026-10-26T12:23:38+00:00,2026-10-26T12:23:48+00:00,8.3,0:00:08,cpu,a76e61398a3e,True,,backfill,.venv/bin/python -m pytest -q -p no:cacheprovider
20261026-145536_14_diag_posterior,,14_diag_posterior,ok,0,2026-10-26T14:55:36+00:00,2026-10-26T15:46:23+00:00,3047.0,0:50:47,cpu,a76e61398a3e,True,,backfill,CUDA_VISIBLE_DEVICES= nice -n 10 python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --particles 256 --workers 8
20261026-150533_15_diag_train,,15_diag_train,ok,0,2026-10-26T15:05:33+00:00,2026-10-26T15:08:35+00:00,182.0,0:03:02,cuda:1,a76e61398a3e,True,,backfill,nice -n 10 python scripts/15_diag_train.py --rids 900 --c 1 --n 4 --seeds 0 --workers 1 --n-boot 50 --post-dir $SP/smoke3 --out-dir $SP/train_smoke
20261026-152329_14_diag_posterior,,14_diag_posterior,ok,,2026-10-26T15:23:29+00:00,2026-10-26T15:26:14+00:00,165.0,0:02:45,cpu,a76e61398a3e,True,,backfill,CUDA_VISIBLE_DEVICES= nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 1 --n 4 --particles 64 --workers 1 --device cpu --out-dir $SP/post_cpu64
20261026-152329_14_diag_posterior-2,,14_diag_posterior,ok,,2026-10-26T15:23:29+00:00,2026-10-26T15:25:15+00:00,106.0,0:01:46,cuda:1,a76e61398a3e,True,,backfill,nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 1 --n 4 --particles 64 --workers 1 --device cuda:1 --out-dir $SP/post_gpu64
20261026-152801_14_diag_posterior,,14_diag_posterior,interrupted,,2026-10-26T15:28:01+00:00,2026-10-26T16:15:12+00:00,2831.0,0:47:11,cuda:1,a76e61398a3e,True,,backfill,nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --particles 256 --workers 6 --device cuda:1 --out-dir outputs/p2/diag/posterior_gpu
20261026-161055_14_diag_posterior,,14_diag_posterior,ok,0,2026-10-26T16:10:55+00:00,2026-10-26T16:11:47+00:00,52,0:00:52,cuda:1,a76e61398a3e,True,,backfill,nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 0 --n 4 --seeds 0 --particles 256 --workers 1 --device cuda:1 --out-dir $SP/post_new
20261026-161530_14_diag_posterior,,14_diag_posterior,ok,0,2026-10-26T16:15:30+00:00,2026-10-26T16:25:42+00:00,612,0:10:12,cuda:1,a76e61398a3e,True,,backfill,nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --particles 256 --workers 6 --device cuda:1 --out-dir outputs/p2/diag/posterior_gpu
20261026-162722_15_diag_train,,15_diag_train,ok,0,2026-10-26T16:27:22+00:00,2026-10-26T16:49:58+00:00,1356,0:22:36,cuda:1,a76e61398a3e,True,,backfill,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 1 --workers 4 --device cuda:1 --post-dir outputs/p2/diag/posterior_gpu
20261026-165756_pytest,,pytest,ok,0,2026-10-26T16:57:56+00:00,2026-10-26T16:58:19+00:00,23,0:00:23,cpu,a76e61398a3e,True,,backfill,nice -n 10 .venv/bin/python -m pytest -q -p no:cacheprovider tests
20261027-013058_pytest,,pytest,ok,0,2026-10-27T01:30:58+00:00,2026-10-27T01:31:00+00:00,2.0,0:00:02,,a76e61398a3e,True,a1b942e071be94aa,runlog,.venv/bin/python -m pytest -q -p no:cacheprovider tests/test_runlog.py
20261027-013101_gpu_smoke,,gpu_smoke,ok,0,2026-10-27T01:31:01+00:00,2026-10-27T01:31:10+00:00,9.2,0:00:09,cuda:1,a76e61398a3e,True,a1b942e071be94aa,runlog,".venv/bin/python -c ' ⏎ import torch, time ⏎ x = torch.empty(512 * 2**20, dtype=torch.uint8, device='""'""'cuda:1'""'""'); x.fill_(1); torch.cuda.synchronize() ⏎ print('""'""'cấp 512 MiB trên'""'""', x.device); time.sleep(6)' --device cuda:1"
20261027-013353_pytest_all,,pytest_all,ok,0,2026-10-27T01:33:53+00:00,2026-10-27T01:34:16+00:00,23.9,0:00:24,,a76e61398a3e,True,9d71bc0f0b0577ae,runlog,.venv/bin/python -m pytest -q -p no:cacheprovider tests
20261027-014241_diag_tie_r_d2,,diag_tie_r_d2,ok,0,2026-10-27T01:42:41+00:00,2026-10-27T01:43:40+00:00,59.0,0:00:59,,a76e61398a3e,True,9d71bc0f0b0577ae,runlog,.venv/bin/python /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/tie_r/d2_tie_r.py
20261027-020233_smoke_14_stress,,smoke_14_stress,ok,0,2026-10-27T02:02:33+00:00,2026-10-27T02:02:55+00:00,22.8,0:00:23,cuda:1,a76e61398a3e,True,0f2b49ce2df3df76,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 1 --n 4 --particles 64 --workers 1 --device cuda:1 --snr 0 --anchor-density half --smc-seeds 5 --wavelets estR true --out-dir /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/smoke14
20261027-020617_smoke_16_f3,,smoke_16_f3,ok,0,2026-10-27T02:06:17+00:00,2026-10-27T02:07:19+00:00,61.3,0:01:01,,a76e61398a3e,True,987f18a6acdd56c7,runlog,.venv/bin/python scripts/16_f3_posterior.py --particles 64 --smc-seeds 0 --settings proto --out-dir /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/smoke16
20261027-021526_smoke_15_stress,,smoke_15_stress,ok,0,2026-10-27T02:15:26+00:00,2026-10-27T02:16:31+00:00,65.0,0:01:05,,a76e61398a3e,True,9cc4f4f6a023dfad,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 --c 1 --n 4 --seeds 0 1 --workers 1 --snr 10 --anchor-density full --variants a 1 --methods Oracle B3b B3c M2-Sa B3d-Sa B3c-R --budgets-from outputs/p2/diag/train/budgets.json --save-preds --n-boot 200 --post-dir outputs/p2/diag/stress/snr10_full --out-dir /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/smoke15
20261027-020347_p3dev/01_stress_snr10_full,20261027-020347_p3dev,stress_snr10_full,ok,0,2026-10-27T02:03:48+00:00,2026-10-27T02:17:54+00:00,846.2,0:14:06,cuda:1,a76e61398a3e,True,fcb2ad2f40364941,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density full --wavelets estR true --workers 6 --out-dir outputs/p2/diag/stress/snr10_full
20261027-020347_p3dev/02_stress_snr10_half,20261027-020347_p3dev,stress_snr10_half,interrupted,-15,2026-10-27T02:17:54+00:00,2026-10-27T02:17:57+00:00,3.2,0:00:03,cuda:1,a76e61398a3e,True,15809c7c1346b142,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density half --wavelets estR true --workers 6 --out-dir outputs/p2/diag/stress/snr10_half
20261027-020347_p3dev,,p3dev,interrupted,-15,2026-10-27T02:03:47+00:00,2026-10-27T02:17:57+00:00,850.0,0:14:10,,a76e61398a3e,True,fcb2ad2f40364941,runlog,bash scripts/run_p3_dev.sh screen stability sigma_a
20261027-021728_p3dev/01_f3_posterior,20261027-021728_p3dev,f3_posterior,ok,0,2026-10-27T02:17:28+00:00,2026-10-27T02:18:50+00:00,81.7,0:01:22,cuda:1,a76e61398a3e,True,15809c7c1346b142,runlog,.venv/bin/python scripts/16_f3_posterior.py --device cuda:1
20261027-021728_p3dev,,p3dev,ok,0,2026-10-27T02:17:28+00:00,2026-10-27T02:18:50+00:00,82.0,0:01:22,,a76e61398a3e,True,15809c7c1346b142,runlog,bash scripts/run_p3_dev.sh f3
20261027-021852_p3dev/01_stress_snr10_full,20261027-021852_p3dev,stress_snr10_full,ok,0,2026-10-27T02:18:52+00:00,2026-10-27T02:18:53+00:00,0.7,0:00:01,cuda:1,a76e61398a3e,True,15809c7c1346b142,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_full
20261027-021852_p3dev/02_stress_snr10_half,20261027-021852_p3dev,stress_snr10_half,ok,0,2026-10-27T02:18:53+00:00,2026-10-27T02:28:30+00:00,577.1,0:09:37,cuda:1,a76e61398a3e,True,15809c7c1346b142,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_half
20261027-021852_p3dev/03_stress_snr10_topbottom,20261027-021852_p3dev,stress_snr10_topbottom,ok,0,2026-10-27T02:28:30+00:00,2026-10-27T02:35:02+00:00,391.4,0:06:31,cuda:1,a76e61398a3e,True,426811e9c823447f,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_topbottom
20261027-021852_p3dev/04_stress_snr5_full,20261027-021852_p3dev,stress_snr5_full,ok,0,2026-10-27T02:35:02+00:00,2026-10-27T02:43:28+00:00,506.2,0:08:26,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 5 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr5_full
20261027-021852_p3dev/05_stress_snr5_half,20261027-021852_p3dev,stress_snr5_half,ok,0,2026-10-27T02:43:28+00:00,2026-10-27T02:51:03+00:00,454.3,0:07:34,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 5 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr5_half
20261027-021852_p3dev/06_stress_snr5_topbottom,20261027-021852_p3dev,stress_snr5_topbottom,ok,0,2026-10-27T02:51:03+00:00,2026-10-27T02:55:24+00:00,261.5,0:04:21,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 5 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr5_topbottom
20261027-021852_p3dev/07_stress_snr0_full,20261027-021852_p3dev,stress_snr0_full,ok,0,2026-10-27T02:55:24+00:00,2026-10-27T03:00:05+00:00,280.9,0:04:41,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 0 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr0_full
20261027-021852_p3dev/08_stress_snr0_half,20261027-021852_p3dev,stress_snr0_half,ok,0,2026-10-27T03:00:05+00:00,2026-10-27T03:04:55+00:00,289.2,0:04:49,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 0 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr0_half
20261027-021852_p3dev/09_stress_snr0_topbottom,20261027-021852_p3dev,stress_snr0_topbottom,ok,0,2026-10-27T03:04:55+00:00,2026-10-27T03:08:23+00:00,208.7,0:03:29,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 0 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr0_topbottom
20261027-021852_p3dev/10_stress_snr-5_full,20261027-021852_p3dev,stress_snr-5_full,ok,0,2026-10-27T03:08:24+00:00,2026-10-27T03:11:30+00:00,186.5,0:03:07,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr-5_full
20261027-021852_p3dev/11_stress_snr-5_half,20261027-021852_p3dev,stress_snr-5_half,ok,0,2026-10-27T03:11:30+00:00,2026-10-27T03:14:31+00:00,180.5,0:03:01,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr-5_half
20261027-021852_p3dev/12_stress_snr-5_topbottom,20261027-021852_p3dev,stress_snr-5_topbottom,ok,0,2026-10-27T03:14:31+00:00,2026-10-27T03:16:58+00:00,147.0,0:02:27,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr-5_topbottom
20261027-021852_p3dev/13_stab_p256,20261027-021852_p3dev,stab_p256,interrupted,-15,2026-10-27T03:16:58+00:00,2026-10-27T03:17:08+00:00,9.6,0:00:10,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --smc-seeds 0 1 2 3 --wavelets estR --workers 8 --out-dir outputs/p2/diag/stability/p256
20261027-021852_p3dev,,p3dev,interrupted,-15,2026-10-27T02:18:52+00:00,2026-10-27T03:17:08+00:00,3495.8,0:58:16,,a76e61398a3e,True,15809c7c1346b142,runlog,bash scripts/run_p3_dev.sh screen stability sigma_a h3
20261027-031710_p3dev/01_train_snr-5_full,20261027-031710_p3dev,train_snr-5_full,ok,0,2026-10-27T03:17:11+00:00,2026-10-27T03:20:37+00:00,206.8,0:03:27,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr -5 --anchor-density full --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr-5_full --out-dir outputs/p2/diag/train_stress/snr-5_full
20261027-031710_p3dev/02_train_snr-5_half,20261027-031710_p3dev,train_snr-5_half,ok,0,2026-10-27T03:20:38+00:00,2026-10-27T03:24:05+00:00,207.0,0:03:27,cuda:1,a76e61398a3e,True,3f5e60f6dcaff782,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr -5 --anchor-density half --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr-5_half --out-dir outputs/p2/diag/train_stress/snr-5_half
20261027-031710_p3dev/03_train_snr-5_topbottom,20261027-031710_p3dev,train_snr-5_topbottom,ok,0,2026-10-27T03:24:05+00:00,2026-10-27T03:27:32+00:00,207.1,0:03:27,cuda:1,a76e61398a3e,True,16692972f74d8984,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr -5 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr-5_topbottom --out-dir outputs/p2/diag/train_stress/snr-5_topbottom
20261027-031710_p3dev/04_train_snr0_full,20261027-031710_p3dev,train_snr0_full,ok,0,2026-10-27T03:27:32+00:00,2026-10-27T03:30:56+00:00,203.6,0:03:24,cuda:1,a76e61398a3e,True,3f3c380a44d18b7d,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 0 --anchor-density full --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr0_full --out-dir outputs/p2/diag/train_stress/snr0_full
20261027-031710_p3dev/05_train_snr0_half,20261027-031710_p3dev,train_snr0_half,ok,0,2026-10-27T03:30:56+00:00,2026-10-27T03:34:49+00:00,233.3,0:03:53,cuda:1,a76e61398a3e,True,3f3c380a44d18b7d,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 0 --anchor-density half --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr0_half --out-dir outputs/p2/diag/train_stress/snr0_half
20261027-031710_p3dev/06_train_snr0_topbottom,20261027-031710_p3dev,train_snr0_topbottom,ok,0,2026-10-27T03:34:49+00:00,2026-10-27T03:38:15+00:00,206.0,0:03:26,cuda:1,a76e61398a3e,True,2d9467ac7c1bda14,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 0 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr0_topbottom --out-dir outputs/p2/diag/train_stress/snr0_topbottom
20261027-031710_p3dev/07_train_snr5_full,20261027-031710_p3dev,train_snr5_full,ok,0,2026-10-27T03:38:15+00:00,2026-10-27T03:40:17+00:00,121.8,0:02:02,cuda:1,a76e61398a3e,True,2d9467ac7c1bda14,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 5 --anchor-density full --c 2 --workers 4 --post-dir outputs/p2/diag/stress/snr5_full --out-dir outputs/p2/diag/train_stress/snr5_full
20261027-031710_p3dev/08_train_snr5_half,20261027-031710_p3dev,train_snr5_half,ok,0,2026-10-27T03:40:17+00:00,2026-10-27T03:42:14+00:00,117.0,0:01:57,cuda:1,a76e61398a3e,True,2d9467ac7c1bda14,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 5 --anchor-density half --c 2 --workers 4 --post-dir outputs/p2/diag/stress/snr5_half --out-dir outputs/p2/diag/train_stress/snr5_half
20261027-031710_p3dev/09_train_snr5_topbottom,20261027-031710_p3dev,train_snr5_topbottom,ok,0,2026-10-27T03:42:14+00:00,2026-10-27T03:45:42+00:00,207.4,0:03:27,cuda:1,a76e61398a3e,True,2d9467ac7c1bda14,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 5 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr5_topbottom --out-dir outputs/p2/diag/train_stress/snr5_topbottom
20261027-031710_p3dev/10_train_snr10_half,20261027-031710_p3dev,train_snr10_half,ok,0,2026-10-27T03:45:42+00:00,2026-10-27T03:47:33+00:00,110.8,0:01:51,cuda:1,a76e61398a3e,True,2d9467ac7c1bda14,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 10 --anchor-density half --c 2 --workers 4 --post-dir outputs/p2/diag/stress/snr10_half --out-dir outputs/p2/diag/train_stress/snr10_half
20261027-031710_p3dev/11_train_snr10_topbottom,20261027-031710_p3dev,train_snr10_topbottom,ok,0,2026-10-27T03:47:33+00:00,2026-10-27T03:51:02+00:00,209.1,0:03:29,cuda:1,a76e61398a3e,True,2d9467ac7c1bda14,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 10 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr10_topbottom --out-dir outputs/p2/diag/train_stress/snr10_topbottom
20261027-031710_p3dev/12_stab_p256,20261027-031710_p3dev,stab_p256,ok,0,2026-10-27T03:51:02+00:00,2026-10-27T04:18:40+00:00,1658.2,0:27:38,cuda:1,a76e61398a3e,True,2d9467ac7c1bda14,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --smc-seeds 0 1 2 3 --wavelets estR --workers 8 --out-dir outputs/p2/diag/stability/p256
20261027-031710_p3dev/13_stab_p1024,20261027-031710_p3dev,stab_p1024,ok,0,2026-10-27T04:18:41+00:00,2026-10-27T05:03:46+00:00,2706.0,0:45:06,cuda:1,a76e61398a3e,True,3d479783f0f6e711,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --particles 1024 --smc-seeds 0 1 --wavelets estR --workers 4 --gpu-mem-gb 6 --out-dir outputs/p2/diag/stability/p1024
20261027-031710_p3dev/14_stress_sa3.5,20261027-031710_p3dev,stress_sa3.5,ok,0,2026-10-27T05:03:47+00:00,2026-10-27T05:14:24+00:00,637.4,0:10:37,cuda:1,a76e61398a3e,True,c168cbbdc9de41d9,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --sigma-a-reg 3.5 --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_full_sa3.5
20261027-031710_p3dev/15_stress_sa14,20261027-031710_p3dev,stress_sa14,ok,0,2026-10-27T05:14:25+00:00,2026-10-27T05:32:47+00:00,1102.2,0:18:22,cuda:1,a76e61398a3e,True,4a5d8059ad8c4365,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --sigma-a-reg 14 --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_full_sa14
20261027-031710_p3dev/16_h3_smc,20261027-031710_p3dev,h3_smc,ok,0,2026-10-27T05:32:48+00:00,2026-10-27T05:39:51+00:00,423.6,0:07:04,cuda:1,a76e61398a3e,True,4a5d8059ad8c4365,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 2 --workers 4 --post-dir outputs/p2/diag/posterior_gpu --out-dir outputs/p2/diag/h3_smc
20261027-031710_p3dev,,p3dev,ok,0,2026-10-27T03:17:10+00:00,2026-10-27T05:39:51+00:00,8561.6,2:22:42,,a76e61398a3e,True,3f5e60f6dcaff782,runlog,bash scripts/run_p3_dev.sh train stability sigma_a h3
20261027-054003_p3dev/01_stab_p1024_snr-5,20261027-054003_p3dev,stab_p1024_snr-5,ok,0,2026-10-27T05:40:04+00:00,2026-10-27T05:51:32+00:00,688.6,0:11:29,cuda:1,a76e61398a3e,True,cf576585ccd2ff6b,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density full --particles 1024 --smc-seeds 0 1 --wavelets estR --workers 4 --gpu-mem-gb 6 --out-dir outputs/p2/diag/stability/p1024_snr-5
20261027-054003_p3dev,,p3dev,ok,0,2026-10-27T05:40:03+00:00,2026-10-27T05:51:32+00:00,688.9,0:11:29,,a76e61398a3e,True,cf576585ccd2ff6b,runlog,bash scripts/run_p3_dev.sh stability_m5
20261027-055202_p3dev/01_b3d_snr10_full,20261027-055202_p3dev,b3d_snr10_full,failed,1,2026-10-27T05:52:02+00:00,2026-10-27T05:52:43+00:00,40.5,0:00:40,cuda:1,a76e61398a3e,True,1b4c4cf8b37e183c,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods B3d --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --post-dir outputs/p2/diag/posterior_gpu --out-dir outputs/p2/diag/train_b3d/snr10_full
20261027-055202_p3dev/02_b3d_snr0_full,20261027-055202_p3dev,b3d_snr0_full,failed,1,2026-10-27T05:52:43+00:00,2026-10-27T05:53:19+00:00,36.5,0:00:36,cuda:1,a76e61398a3e,True,1b4c4cf8b37e183c,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods B3d --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --snr 0 --anchor-density full --post-dir outputs/p2/diag/stress/snr0_full --out-dir outputs/p2/diag/train_b3d/snr0_full
20261027-055202_p3dev/03_b3d_snr-5_full,20261027-055202_p3dev,b3d_snr-5_full,failed,1,2026-10-27T05:53:19+00:00,2026-10-27T05:53:56+00:00,36.9,0:00:37,cuda:1,a76e61398a3e,True,335b7ba963f4277c,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods B3d --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --snr -5 --anchor-density full --post-dir outputs/p2/diag/stress/snr-5_full --out-dir outputs/p2/diag/train_b3d/snr-5_full
20261027-055202_p3dev,,p3dev,ok,0,2026-10-27T05:52:02+00:00,2026-10-27T05:53:56+00:00,114.3,0:01:54,,a76e61398a3e,True,1b4c4cf8b37e183c,runlog,bash scripts/run_p3_dev.sh b3d_old
20261027-055413_p3dev/01_train_sa3.5,20261027-055413_p3dev,train_sa3.5,ok,0,2026-10-27T05:54:13+00:00,2026-10-27T05:57:02+00:00,169.7,0:02:50,cuda:1,a76e61398a3e,True,a7b91ac7bb476072,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --sigma-a-reg 3.5 --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --post-dir outputs/p2/diag/stress/snr10_full_sa3.5 --out-dir outputs/p2/diag/train_sa/sa3.5
20261027-055413_p3dev/02_train_sa14,20261027-055413_p3dev,train_sa14,ok,0,2026-10-27T05:57:03+00:00,2026-10-27T05:59:48+00:00,165.9,0:02:46,cuda:1,a76e61398a3e,True,75f953c96b36bae4,runlog,.venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --sigma-a-reg 14 --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --post-dir outputs/p2/diag/stress/snr10_full_sa14 --out-dir outputs/p2/diag/train_sa/sa14
20261027-055413_p3dev,,p3dev,ok,0,2026-10-27T05:54:13+00:00,2026-10-27T05:59:49+00:00,336.0,0:05:36,,a76e61398a3e,True,a7b91ac7bb476072,runlog,bash scripts/run_p3_dev.sh train_sa
20261027-064712_p2rdev_summary,,p2rdev_summary,ok,0,2026-10-27T06:47:12+00:00,2026-10-27T06:48:41+00:00,89.0,0:01:29,,cee2ff085955,True,b6a4ccdb0b2a8c48,runlog,.venv/bin/python scripts/17_summarize_p2r_dev.py
20261027-065508_p2r_main/01_p2r_post_R10,20261027-065508_p2r_main,p2r_post_R10,interrupted,-15,2026-10-27T06:55:09+00:00,2026-10-27T07:59:43+00:00,3874.4,1:04:34,cuda:1,f95123174f3f,True,c2052006feeebf10,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 4 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density full --out-dir outputs/p2r/posterior/R10
20261027-065508_p2r_main,,p2r_main,interrupted,-15,2026-10-27T06:55:08+00:00,2026-10-27T07:59:43+00:00,3875.4,1:04:35,,f95123174f3f,True,c2052006feeebf10,runlog,bash scripts/run_p2r_main.sh
20261027-080009_p2r_main/01_p2r_post_R10tb,20261027-080009_p2r_main,p2r_post_R10tb,interrupted,-15,2026-10-27T08:00:10+00:00,2026-10-27T08:21:12+00:00,1262.4,0:21:02,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density topbottom --out-dir outputs/p2r/posterior/R10tb
20261027-080009_p2r_main/03_p2r_post_R0h,20261027-080009_p2r_main,p2r_post_R0h,interrupted,-15,2026-10-27T08:00:10+00:00,2026-10-27T08:21:12+00:00,1262.4,0:21:02,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 0 --anchor-density half --out-dir outputs/p2r/posterior/R0h
20261027-080009_p2r_main/03_p2r_post_R10_sa3.5,20261027-080009_p2r_main,p2r_post_R10_sa3.5,ok,0,2026-10-27T08:00:10+00:00,2026-10-27T09:33:58+00:00,5628.0,1:33:48,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 1 --snr 10 --anchor-density full --sigma-a-reg 3.5 --out-dir outputs/p2r/posterior/R10_sa3.5
20261027-080009_p2r_main/05_p2r_post_R10,20261027-080009_p2r_main,p2r_post_R10,ok,0,2026-10-27T08:00:10+00:00,2026-10-27T09:42:57+00:00,6167.2,1:42:47,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density full --out-dir outputs/p2r/posterior/R10
20261027-094720_p2r_main/01_p2r_post_R10_sa3.5,20261027-094720_p2r_main,p2r_post_R10_sa3.5,ok,0,2026-10-27T09:47:20+00:00,2026-10-27T09:47:21+00:00,0.8,0:00:01,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 1 --snr 10 --anchor-density full --sigma-a-reg 3.5 --out-dir outputs/p2r/posterior/R10_sa3.5
20261027-094722_p2r_main/01_p2r_post_R10,20261027-094722_p2r_main,p2r_post_R10,ok,0,2026-10-27T09:47:22+00:00,2026-10-27T09:47:23+00:00,0.9,0:00:01,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density full --out-dir outputs/p2r/posterior/R10
20261027-094724_p2r_main/01_p2r_post_Rm5,20261027-094724_p2r_main,p2r_post_Rm5,ok,0,2026-10-27T09:47:24+00:00,2026-10-27T09:55:01+00:00,456.5,0:07:37,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:0 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr -5 --anchor-density full --out-dir outputs/p2r/posterior/Rm5
20261027-094720_p2r_main/02_p2r_train_R10_sa3.5,20261027-094720_p2r_main,p2r_train_R10_sa3.5,ok,0,2026-10-27T09:47:21+00:00,2026-10-27T09:57:31+00:00,609.6,0:10:10,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 3.5 --post-dir outputs/p2r/posterior/R10_sa3.5 --out-dir outputs/p2r/train/R10_sa3.5
20261027-094726_p2r_main/01_p2r_post_R0h,20261027-094726_p2r_main,p2r_post_R0h,ok,0,2026-10-27T09:47:26+00:00,2026-10-27T09:58:42+00:00,675.5,0:11:16,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:0 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 0 --anchor-density half --out-dir outputs/p2r/posterior/R0h
20261027-102553_p2r_finish/01_p2r_train_R10_sa14_pass1,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass1,ok,0,2026-10-27T10:25:53+00:00,2026-10-27T10:29:44+00:00,231.4,0:03:51,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-094724_p2r_main/02_p2r_train_Rm5,20261027-094724_p2r_main,p2r_train_Rm5,ok,0,2026-10-27T09:55:01+00:00,2026-10-27T10:29:45+00:00,2084.0,0:34:44,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr -5 --anchor-density full --post-dir outputs/p2r/posterior/Rm5 --out-dir outputs/p2r/train/Rm5
20261027-094724_p2r_main,,p2r_main,ok,0,2026-10-27T09:47:24+00:00,2026-10-27T10:29:45+00:00,2541.0,0:42:21,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,bash scripts/run_p2r_main.sh Rm5
20261027-102553_p2r_finish/04_p2r_train_R10_sa14_pass2,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass2,ok,0,2026-10-27T10:29:45+00:00,2026-10-27T10:32:37+00:00,172.4,0:02:52,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-094726_p2r_main/02_p2r_train_R0h,20261027-094726_p2r_main,p2r_train_R0h,ok,0,2026-10-27T09:58:42+00:00,2026-10-27T10:36:20+00:00,2257.6,0:37:38,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density half --post-dir outputs/p2r/posterior/R0h --out-dir outputs/p2r/train/R0h
20261027-094726_p2r_main,,p2r_main,ok,0,2026-10-27T09:47:26+00:00,2026-10-27T10:36:20+00:00,2933.5,0:48:54,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,bash scripts/run_p2r_main.sh R0h
20261027-102553_p2r_finish/05_p2r_train_R10_sa14_pass3,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass3,ok,0,2026-10-27T10:34:37+00:00,2026-10-27T10:36:57+00:00,140.1,0:02:20,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/02_p2r_train_R0_pass1,20261027-102553_p2r_finish,p2r_train_R0_pass1,ok,0,2026-10-27T10:25:53+00:00,2026-10-27T10:43:57+00:00,1083.9,0:18:04,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/06_p2r_train_R0_pass2,20261027-102553_p2r_finish,p2r_train_R0_pass2,ok,0,2026-10-27T10:43:57+00:00,2026-10-27T10:47:54+00:00,236.6,0:03:57,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/07_p2r_train_R0_pass3,20261027-102553_p2r_finish,p2r_train_R0_pass3,ok,0,2026-10-27T10:47:54+00:00,2026-10-27T10:50:25+00:00,151.4,0:02:31,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/08_p2r_train_R0_pass4,20261027-102553_p2r_finish,p2r_train_R0_pass4,ok,0,2026-10-27T10:50:25+00:00,2026-10-27T10:51:52+00:00,86.4,0:01:26,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/09_p2r_train_R0_pass5,20261027-102553_p2r_finish,p2r_train_R0_pass5,ok,0,2026-10-27T10:52:52+00:00,2026-10-27T10:54:20+00:00,87.6,0:01:28,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/10_p2r_train_R0_pass6,20261027-102553_p2r_finish,p2r_train_R0_pass6,ok,0,2026-10-27T10:54:20+00:00,2026-10-27T10:55:44+00:00,83.9,0:01:24,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/11_p2r_train_R0_pass7,20261027-102553_p2r_finish,p2r_train_R0_pass7,ok,0,2026-10-27T10:55:44+00:00,2026-10-27T10:56:57+00:00,72.8,0:01:13,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-094722_p2r_main/02_p2r_train_R10,20261027-094722_p2r_main,p2r_train_R10,ok,0,2026-10-27T09:47:23+00:00,2026-10-27T10:57:14+00:00,4190.8,1:09:51,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 10 --anchor-density full --post-dir outputs/p2r/posterior/R10 --out-dir outputs/p2r/train/R10
20261027-094722_p2r_main,,p2r_main,ok,0,2026-10-27T09:47:22+00:00,2026-10-27T10:57:14+00:00,4192.1,1:09:52,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,bash scripts/run_p2r_main.sh R10
20261027-102553_p2r_finish/12_p2r_train_R0_pass8,20261027-102553_p2r_finish,p2r_train_R0_pass8,ok,0,2026-10-27T10:56:57+00:00,2026-10-27T10:58:12+00:00,75.5,0:01:15,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/13_p2r_train_R0_pass9,20261027-102553_p2r_finish,p2r_train_R0_pass9,ok,0,2026-10-27T10:58:13+00:00,2026-10-27T10:59:35+00:00,82.1,0:01:22,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/14_p2r_train_R0_pass10,20261027-102553_p2r_finish,p2r_train_R0_pass10,ok,0,2026-10-27T10:59:35+00:00,2026-10-27T11:01:02+00:00,87.0,0:01:27,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-094716_p2r_main/01_p2r_post_R0,20261027-094716_p2r_main,p2r_post_R0,ok,0,2026-10-27T09:47:16+00:00,2026-10-27T11:01:56+00:00,4480.0,1:14:40,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 5 --gpu-mem-gb 6 --c 0 1 2 --snr 0 --anchor-density full --out-dir outputs/p2r/posterior/R0
20261027-102553_p2r_finish/15_p2r_train_R0_pass11,20261027-102553_p2r_finish,p2r_train_R0_pass11,ok,0,2026-10-27T11:01:02+00:00,2026-10-27T11:02:27+00:00,85.1,0:01:25,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/16_p2r_train_R0_pass12,20261027-102553_p2r_finish,p2r_train_R0_pass12,ok,0,2026-10-27T11:02:27+00:00,2026-10-27T11:03:55+00:00,88.0,0:01:28,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
20261027-102553_p2r_finish/17_p2r_train_R10_sa14_pass4,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass4,ok,0,2026-10-27T11:02:59+00:00,2026-10-27T11:04:16+00:00,77.0,0:01:17,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/18_p2r_train_R10_sa14_pass5,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass5,ok,0,2026-10-27T11:04:16+00:00,2026-10-27T11:05:41+00:00,85.6,0:01:26,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-094718_p2r_main/01_p2r_post_R10tb,20261027-094718_p2r_main,p2r_post_R10tb,ok,0,2026-10-27T09:47:18+00:00,2026-10-27T11:06:07+00:00,4729.1,1:18:49,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 4 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density topbottom --out-dir outputs/p2r/posterior/R10tb
20261027-102553_p2r_finish/03_p2r_train_R10tb_pass1,20261027-102553_p2r_finish,p2r_train_R10tb_pass1,ok,0,2026-10-27T10:25:53+00:00,2026-10-27T11:06:55+00:00,2461.6,0:41:02,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 10 --anchor-density topbottom --post-dir outputs/p2r/posterior/R10tb --out-dir outputs/p2r/train/R10tb
20261027-102553_p2r_finish/19_p2r_train_R10_sa14_pass6,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass6,ok,0,2026-10-27T11:05:42+00:00,2026-10-27T11:07:08+00:00,86.2,0:01:26,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/21_p2r_train_R10_sa14_pass7,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass7,ok,0,2026-10-27T11:10:08+00:00,2026-10-27T11:11:21+00:00,73.2,0:01:13,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/20_p2r_train_R10tb_pass2,20261027-102553_p2r_finish,p2r_train_R10tb_pass2,ok,0,2026-10-27T11:06:55+00:00,2026-10-27T11:16:00+00:00,545.4,0:09:05,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 10 --anchor-density topbottom --post-dir outputs/p2r/posterior/R10tb --out-dir outputs/p2r/train/R10tb
20261027-102553_p2r_finish/22_p2r_train_R10_sa14_pass8,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass8,ok,0,2026-10-27T11:15:22+00:00,2026-10-27T11:16:37+00:00,75.4,0:01:15,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/23_p2r_train_R10_sa14_pass9,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass9,ok,0,2026-10-27T11:18:37+00:00,2026-10-27T11:19:55+00:00,77.9,0:01:18,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/24_p2r_train_R10_sa14_pass10,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass10,ok,0,2026-10-27T11:19:55+00:00,2026-10-27T11:21:25+00:00,89.5,0:01:30,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/25_p2r_train_R10_sa14_pass11,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass11,ok,0,2026-10-27T11:21:25+00:00,2026-10-27T11:22:52+00:00,86.7,0:01:27,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-094720_p2r_main/03_p2r_post_R10_sa14,20261027-094720_p2r_main,p2r_post_R10_sa14,ok,0,2026-10-27T09:57:31+00:00,2026-10-27T11:23:05+00:00,5133.7,1:25:34,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,.venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --out-dir outputs/p2r/posterior/R10_sa14
20261027-102553_p2r_finish/26_p2r_train_R10_sa14_pass12,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass12,ok,0,2026-10-27T11:22:52+00:00,2026-10-27T11:24:14+00:00,82.5,0:01:22,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-102553_p2r_finish/27_p2r_train_R10_sa14_pass13,20261027-102553_p2r_finish,p2r_train_R10_sa14_pass13,ok,0,2026-10-27T11:24:15+00:00,2026-10-27T11:25:34+00:00,79.6,0:01:20,cuda:0,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
20261027-094716_p2r_main,,p2r_main,interrupted,-9,2026-10-27T09:47:16+00:00,2026-10-27T11:25:34+00:00,5898.3,1:38:18,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,bash scripts/run_p2r_main.sh R0
20261027-094718_p2r_main,,p2r_main,interrupted,-9,2026-10-27T09:47:18+00:00,2026-10-27T11:25:34+00:00,5896.3,1:38:16,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,bash scripts/run_p2r_main.sh R10tb
20261027-094720_p2r_main,,p2r_main,interrupted,-9,2026-10-27T09:47:20+00:00,2026-10-27T11:25:34+00:00,5894.3,1:38:14,cuda:1,f95123174f3f,True,99a0098b80c105f1,runlog,bash scripts/run_p2r_main.sh sigma_a
20261027-102553_p2r_finish/28_p2r_summary,20261027-102553_p2r_finish,p2r_summary,ok,0,2026-10-27T11:26:04+00:00,2026-10-27T11:29:30+00:00,205.7,0:03:26,,f95123174f3f,True,99a0098b80c105f1,runlog,nice -n 10 .venv/bin/python scripts/18_summarize_p2r.py
20261027-102553_p2r_finish,,p2r_finish,ok,0,2026-10-27T10:25:53+00:00,2026-10-27T11:29:30+00:00,3817.6,1:03:38,,f95123174f3f,True,99a0098b80c105f1,runlog,bash /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/finish_p2r.sh /home/jovyan/lamlvh/ML-Porosity/logs/p2r_resume_20261027-094716
1 run_id parent name status exit_code start end wall_s wall device git dirty code_sha source cmd
2 20261026-035632_01_build_wells 01_build_wells ok 2026-10-26T03:56:32+00:00 2026-10-26T03:56:34+00:00 1.6 0:00:02 d11b7b1 True backfill .venv/bin/python scripts/01_build_wells.py
3 20261026-035935_run_p0 run_p0 unknown 2026-10-26T03:59:35+00:00 2026-10-26T03:59:53+00:00 17.4 0:00:17 d11b7b1 True backfill scripts/run_p0.sh
4 20261026-042407_04_wavelet_tie 04_wavelet_tie ok 2026-10-26T04:24:07+00:00 2026-10-26T04:24:12+00:00 4.7 0:00:05 d11b7b1 True backfill .venv/bin/python scripts/04_wavelet_tie.py
5 20261026-043014_05_lowo 05_lowo ok 2026-10-26T04:30:14+00:00 2026-10-26T04:30:52+00:00 37.6 0:00:38 cpu d11b7b1 True backfill .venv/bin/python scripts/05_lowo.py --only B0a,B0b,B1
6 20261026-043124_05_lowo 05_lowo ok 2026-10-26T04:31:24+00:00 2026-10-26T04:46:48+00:00 923 0:15:23 cuda (CUDA_VISIBLE_DEVICES=1) d11b7b1 True backfill CUDA_VISIBLE_DEVICES=1 PYTHONWARNINGS=ignore .venv/bin/python scripts/05_lowo.py --only B2,B3a,B3b --workers 12
7 20261026-044655_06_summarize_p1 06_summarize_p1 ok 2026-10-26T04:46:55+00:00 d11b7b1 True backfill .venv/bin/python scripts/06_summarize_p1.py
8 20261026-094732_09_fit_warp_prior_f3 09_fit_warp_prior_f3 ok 2026-10-26T09:47:32+00:00 2026-10-26T09:48:53+00:00 80.2 0:01:20 a76e61398a3e True backfill .venv/bin/python scripts/09_fit_warp_prior_f3.py
9 20261026-103025_11_run_d2 11_run_d2 ok 0 2026-10-26T10:30:25+00:00 2026-10-26T10:40:36+00:00 611 0:10:11 cuda:1 a76e61398a3e True backfill .venv/bin/python scripts/11_run_d2.py --dev --workers 4
10 20261026-104517_11_run_d2 11_run_d2 interrupted 2026-10-26T10:45:17+00:00 2026-10-26T10:51:24+00:00 367.0 0:06:07 cuda:1 a76e61398a3e True backfill .venv/bin/python scripts/11_run_d2.py --main --workers 6 --device cuda:1
11 20261026-104935_10_build_d2 10_build_d2 ok 0 2026-10-26T10:49:35+00:00 2026-10-26T10:49:59+00:00 24.0 0:00:24 cpu a76e61398a3e True backfill OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 .venv/bin/python scripts/10_build_d2.py
12 20261026-105134_11_run_d2 11_run_d2 ok 0 2026-10-26T10:51:34+00:00 2026-10-26T12:20:30+00:00 5335 1:28:55 cuda:1 a76e61398a3e True backfill .venv/bin/python scripts/11_run_d2.py --main --workers 6 --device cuda:1
13 20261026-105357_12_h1_blur 12_h1_blur ok 0 2026-10-26T10:53:57+00:00 2026-10-26T10:59:45+00:00 348 0:05:48 cuda:1 a76e61398a3e True backfill .venv/bin/python scripts/12_h1_blur.py --workers 3 --device cuda:1
14 20261026-110344_13_summarize_p2 13_summarize_p2 ok 2026-10-26T11:03:44+00:00 cpu a76e61398a3e True backfill timeout 600 .venv/bin/python scripts/13_summarize_p2.py --mode dev --n-boot 500
15 20261026-122045_13_summarize_p2 13_summarize_p2 ok 2026-10-26T12:20:45+00:00 cpu a76e61398a3e True backfill .venv/bin/python scripts/13_summarize_p2.py --mode main
16 20261026-122338_pytest pytest ok 0 2026-10-26T12:23:38+00:00 2026-10-26T12:23:48+00:00 8.3 0:00:08 cpu a76e61398a3e True backfill .venv/bin/python -m pytest -q -p no:cacheprovider
17 20261026-145536_14_diag_posterior 14_diag_posterior ok 0 2026-10-26T14:55:36+00:00 2026-10-26T15:46:23+00:00 3047.0 0:50:47 cpu a76e61398a3e True backfill CUDA_VISIBLE_DEVICES= nice -n 10 python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --particles 256 --workers 8
18 20261026-150533_15_diag_train 15_diag_train ok 0 2026-10-26T15:05:33+00:00 2026-10-26T15:08:35+00:00 182.0 0:03:02 cuda:1 a76e61398a3e True backfill nice -n 10 python scripts/15_diag_train.py --rids 900 --c 1 --n 4 --seeds 0 --workers 1 --n-boot 50 --post-dir $SP/smoke3 --out-dir $SP/train_smoke
19 20261026-152329_14_diag_posterior 14_diag_posterior ok 2026-10-26T15:23:29+00:00 2026-10-26T15:26:14+00:00 165.0 0:02:45 cpu a76e61398a3e True backfill CUDA_VISIBLE_DEVICES= nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 1 --n 4 --particles 64 --workers 1 --device cpu --out-dir $SP/post_cpu64
20 20261026-152329_14_diag_posterior-2 14_diag_posterior ok 2026-10-26T15:23:29+00:00 2026-10-26T15:25:15+00:00 106.0 0:01:46 cuda:1 a76e61398a3e True backfill nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 1 --n 4 --particles 64 --workers 1 --device cuda:1 --out-dir $SP/post_gpu64
21 20261026-152801_14_diag_posterior 14_diag_posterior interrupted 2026-10-26T15:28:01+00:00 2026-10-26T16:15:12+00:00 2831.0 0:47:11 cuda:1 a76e61398a3e True backfill nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --particles 256 --workers 6 --device cuda:1 --out-dir outputs/p2/diag/posterior_gpu
22 20261026-161055_14_diag_posterior 14_diag_posterior ok 0 2026-10-26T16:10:55+00:00 2026-10-26T16:11:47+00:00 52 0:00:52 cuda:1 a76e61398a3e True backfill nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 0 --n 4 --seeds 0 --particles 256 --workers 1 --device cuda:1 --out-dir $SP/post_new
23 20261026-161530_14_diag_posterior 14_diag_posterior ok 0 2026-10-26T16:15:30+00:00 2026-10-26T16:25:42+00:00 612 0:10:12 cuda:1 a76e61398a3e True backfill nice -n 10 .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --particles 256 --workers 6 --device cuda:1 --out-dir outputs/p2/diag/posterior_gpu
24 20261026-162722_15_diag_train 15_diag_train ok 0 2026-10-26T16:27:22+00:00 2026-10-26T16:49:58+00:00 1356 0:22:36 cuda:1 a76e61398a3e True backfill nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 1 --workers 4 --device cuda:1 --post-dir outputs/p2/diag/posterior_gpu
25 20261026-165756_pytest pytest ok 0 2026-10-26T16:57:56+00:00 2026-10-26T16:58:19+00:00 23 0:00:23 cpu a76e61398a3e True backfill nice -n 10 .venv/bin/python -m pytest -q -p no:cacheprovider tests
26 20261027-013058_pytest pytest ok 0 2026-10-27T01:30:58+00:00 2026-10-27T01:31:00+00:00 2.0 0:00:02 a76e61398a3e True a1b942e071be94aa runlog .venv/bin/python -m pytest -q -p no:cacheprovider tests/test_runlog.py
27 20261027-013101_gpu_smoke gpu_smoke ok 0 2026-10-27T01:31:01+00:00 2026-10-27T01:31:10+00:00 9.2 0:00:09 cuda:1 a76e61398a3e True a1b942e071be94aa runlog .venv/bin/python -c ' ⏎ import torch, time ⏎ x = torch.empty(512 * 2**20, dtype=torch.uint8, device='"'"'cuda:1'"'"'); x.fill_(1); torch.cuda.synchronize() ⏎ print('"'"'cấp 512 MiB trên'"'"', x.device); time.sleep(6)' --device cuda:1
28 20261027-013353_pytest_all pytest_all ok 0 2026-10-27T01:33:53+00:00 2026-10-27T01:34:16+00:00 23.9 0:00:24 a76e61398a3e True 9d71bc0f0b0577ae runlog .venv/bin/python -m pytest -q -p no:cacheprovider tests
29 20261027-014241_diag_tie_r_d2 diag_tie_r_d2 ok 0 2026-10-27T01:42:41+00:00 2026-10-27T01:43:40+00:00 59.0 0:00:59 a76e61398a3e True 9d71bc0f0b0577ae runlog .venv/bin/python /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/tie_r/d2_tie_r.py
30 20261027-020233_smoke_14_stress smoke_14_stress ok 0 2026-10-27T02:02:33+00:00 2026-10-27T02:02:55+00:00 22.8 0:00:23 cuda:1 a76e61398a3e True 0f2b49ce2df3df76 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 --c 1 --n 4 --particles 64 --workers 1 --device cuda:1 --snr 0 --anchor-density half --smc-seeds 5 --wavelets estR true --out-dir /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/smoke14
31 20261027-020617_smoke_16_f3 smoke_16_f3 ok 0 2026-10-27T02:06:17+00:00 2026-10-27T02:07:19+00:00 61.3 0:01:01 a76e61398a3e True 987f18a6acdd56c7 runlog .venv/bin/python scripts/16_f3_posterior.py --particles 64 --smc-seeds 0 --settings proto --out-dir /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/smoke16
32 20261027-021526_smoke_15_stress smoke_15_stress ok 0 2026-10-27T02:15:26+00:00 2026-10-27T02:16:31+00:00 65.0 0:01:05 a76e61398a3e True 9cc4f4f6a023dfad runlog .venv/bin/python scripts/15_diag_train.py --rids 900 --c 1 --n 4 --seeds 0 1 --workers 1 --snr 10 --anchor-density full --variants a 1 --methods Oracle B3b B3c M2-Sa B3d-Sa B3c-R --budgets-from outputs/p2/diag/train/budgets.json --save-preds --n-boot 200 --post-dir outputs/p2/diag/stress/snr10_full --out-dir /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/smoke15
33 20261027-020347_p3dev/01_stress_snr10_full 20261027-020347_p3dev stress_snr10_full ok 0 2026-10-27T02:03:48+00:00 2026-10-27T02:17:54+00:00 846.2 0:14:06 cuda:1 a76e61398a3e True fcb2ad2f40364941 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density full --wavelets estR true --workers 6 --out-dir outputs/p2/diag/stress/snr10_full
34 20261027-020347_p3dev/02_stress_snr10_half 20261027-020347_p3dev stress_snr10_half interrupted -15 2026-10-27T02:17:54+00:00 2026-10-27T02:17:57+00:00 3.2 0:00:03 cuda:1 a76e61398a3e True 15809c7c1346b142 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density half --wavelets estR true --workers 6 --out-dir outputs/p2/diag/stress/snr10_half
35 20261027-020347_p3dev p3dev interrupted -15 2026-10-27T02:03:47+00:00 2026-10-27T02:17:57+00:00 850.0 0:14:10 a76e61398a3e True fcb2ad2f40364941 runlog bash scripts/run_p3_dev.sh screen stability sigma_a
36 20261027-021728_p3dev/01_f3_posterior 20261027-021728_p3dev f3_posterior ok 0 2026-10-27T02:17:28+00:00 2026-10-27T02:18:50+00:00 81.7 0:01:22 cuda:1 a76e61398a3e True 15809c7c1346b142 runlog .venv/bin/python scripts/16_f3_posterior.py --device cuda:1
37 20261027-021728_p3dev p3dev ok 0 2026-10-27T02:17:28+00:00 2026-10-27T02:18:50+00:00 82.0 0:01:22 a76e61398a3e True 15809c7c1346b142 runlog bash scripts/run_p3_dev.sh f3
38 20261027-021852_p3dev/01_stress_snr10_full 20261027-021852_p3dev stress_snr10_full ok 0 2026-10-27T02:18:52+00:00 2026-10-27T02:18:53+00:00 0.7 0:00:01 cuda:1 a76e61398a3e True 15809c7c1346b142 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_full
39 20261027-021852_p3dev/02_stress_snr10_half 20261027-021852_p3dev stress_snr10_half ok 0 2026-10-27T02:18:53+00:00 2026-10-27T02:28:30+00:00 577.1 0:09:37 cuda:1 a76e61398a3e True 15809c7c1346b142 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_half
40 20261027-021852_p3dev/03_stress_snr10_topbottom 20261027-021852_p3dev stress_snr10_topbottom ok 0 2026-10-27T02:28:30+00:00 2026-10-27T02:35:02+00:00 391.4 0:06:31 cuda:1 a76e61398a3e True 426811e9c823447f runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 10 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_topbottom
41 20261027-021852_p3dev/04_stress_snr5_full 20261027-021852_p3dev stress_snr5_full ok 0 2026-10-27T02:35:02+00:00 2026-10-27T02:43:28+00:00 506.2 0:08:26 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 5 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr5_full
42 20261027-021852_p3dev/05_stress_snr5_half 20261027-021852_p3dev stress_snr5_half ok 0 2026-10-27T02:43:28+00:00 2026-10-27T02:51:03+00:00 454.3 0:07:34 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 5 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr5_half
43 20261027-021852_p3dev/06_stress_snr5_topbottom 20261027-021852_p3dev stress_snr5_topbottom ok 0 2026-10-27T02:51:03+00:00 2026-10-27T02:55:24+00:00 261.5 0:04:21 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 5 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr5_topbottom
44 20261027-021852_p3dev/07_stress_snr0_full 20261027-021852_p3dev stress_snr0_full ok 0 2026-10-27T02:55:24+00:00 2026-10-27T03:00:05+00:00 280.9 0:04:41 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 0 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr0_full
45 20261027-021852_p3dev/08_stress_snr0_half 20261027-021852_p3dev stress_snr0_half ok 0 2026-10-27T03:00:05+00:00 2026-10-27T03:04:55+00:00 289.2 0:04:49 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 0 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr0_half
46 20261027-021852_p3dev/09_stress_snr0_topbottom 20261027-021852_p3dev stress_snr0_topbottom ok 0 2026-10-27T03:04:55+00:00 2026-10-27T03:08:23+00:00 208.7 0:03:29 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr 0 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr0_topbottom
47 20261027-021852_p3dev/10_stress_snr-5_full 20261027-021852_p3dev stress_snr-5_full ok 0 2026-10-27T03:08:24+00:00 2026-10-27T03:11:30+00:00 186.5 0:03:07 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density full --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr-5_full
48 20261027-021852_p3dev/11_stress_snr-5_half 20261027-021852_p3dev stress_snr-5_half ok 0 2026-10-27T03:11:30+00:00 2026-10-27T03:14:31+00:00 180.5 0:03:01 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density half --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr-5_half
49 20261027-021852_p3dev/12_stress_snr-5_topbottom 20261027-021852_p3dev stress_snr-5_topbottom ok 0 2026-10-27T03:14:31+00:00 2026-10-27T03:16:58+00:00 147.0 0:02:27 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density topbottom --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr-5_topbottom
50 20261027-021852_p3dev/13_stab_p256 20261027-021852_p3dev stab_p256 interrupted -15 2026-10-27T03:16:58+00:00 2026-10-27T03:17:08+00:00 9.6 0:00:10 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --smc-seeds 0 1 2 3 --wavelets estR --workers 8 --out-dir outputs/p2/diag/stability/p256
51 20261027-021852_p3dev p3dev interrupted -15 2026-10-27T02:18:52+00:00 2026-10-27T03:17:08+00:00 3495.8 0:58:16 a76e61398a3e True 15809c7c1346b142 runlog bash scripts/run_p3_dev.sh screen stability sigma_a h3
52 20261027-031710_p3dev/01_train_snr-5_full 20261027-031710_p3dev train_snr-5_full ok 0 2026-10-27T03:17:11+00:00 2026-10-27T03:20:37+00:00 206.8 0:03:27 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr -5 --anchor-density full --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr-5_full --out-dir outputs/p2/diag/train_stress/snr-5_full
53 20261027-031710_p3dev/02_train_snr-5_half 20261027-031710_p3dev train_snr-5_half ok 0 2026-10-27T03:20:38+00:00 2026-10-27T03:24:05+00:00 207.0 0:03:27 cuda:1 a76e61398a3e True 3f5e60f6dcaff782 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr -5 --anchor-density half --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr-5_half --out-dir outputs/p2/diag/train_stress/snr-5_half
54 20261027-031710_p3dev/03_train_snr-5_topbottom 20261027-031710_p3dev train_snr-5_topbottom ok 0 2026-10-27T03:24:05+00:00 2026-10-27T03:27:32+00:00 207.1 0:03:27 cuda:1 a76e61398a3e True 16692972f74d8984 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr -5 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr-5_topbottom --out-dir outputs/p2/diag/train_stress/snr-5_topbottom
55 20261027-031710_p3dev/04_train_snr0_full 20261027-031710_p3dev train_snr0_full ok 0 2026-10-27T03:27:32+00:00 2026-10-27T03:30:56+00:00 203.6 0:03:24 cuda:1 a76e61398a3e True 3f3c380a44d18b7d runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 0 --anchor-density full --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr0_full --out-dir outputs/p2/diag/train_stress/snr0_full
56 20261027-031710_p3dev/05_train_snr0_half 20261027-031710_p3dev train_snr0_half ok 0 2026-10-27T03:30:56+00:00 2026-10-27T03:34:49+00:00 233.3 0:03:53 cuda:1 a76e61398a3e True 3f3c380a44d18b7d runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 0 --anchor-density half --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr0_half --out-dir outputs/p2/diag/train_stress/snr0_half
57 20261027-031710_p3dev/06_train_snr0_topbottom 20261027-031710_p3dev train_snr0_topbottom ok 0 2026-10-27T03:34:49+00:00 2026-10-27T03:38:15+00:00 206.0 0:03:26 cuda:1 a76e61398a3e True 2d9467ac7c1bda14 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 0 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr0_topbottom --out-dir outputs/p2/diag/train_stress/snr0_topbottom
58 20261027-031710_p3dev/07_train_snr5_full 20261027-031710_p3dev train_snr5_full ok 0 2026-10-27T03:38:15+00:00 2026-10-27T03:40:17+00:00 121.8 0:02:02 cuda:1 a76e61398a3e True 2d9467ac7c1bda14 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 5 --anchor-density full --c 2 --workers 4 --post-dir outputs/p2/diag/stress/snr5_full --out-dir outputs/p2/diag/train_stress/snr5_full
59 20261027-031710_p3dev/08_train_snr5_half 20261027-031710_p3dev train_snr5_half ok 0 2026-10-27T03:40:17+00:00 2026-10-27T03:42:14+00:00 117.0 0:01:57 cuda:1 a76e61398a3e True 2d9467ac7c1bda14 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 5 --anchor-density half --c 2 --workers 4 --post-dir outputs/p2/diag/stress/snr5_half --out-dir outputs/p2/diag/train_stress/snr5_half
60 20261027-031710_p3dev/09_train_snr5_topbottom 20261027-031710_p3dev train_snr5_topbottom ok 0 2026-10-27T03:42:14+00:00 2026-10-27T03:45:42+00:00 207.4 0:03:27 cuda:1 a76e61398a3e True 2d9467ac7c1bda14 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 5 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr5_topbottom --out-dir outputs/p2/diag/train_stress/snr5_topbottom
61 20261027-031710_p3dev/10_train_snr10_half 20261027-031710_p3dev train_snr10_half ok 0 2026-10-27T03:45:42+00:00 2026-10-27T03:47:33+00:00 110.8 0:01:51 cuda:1 a76e61398a3e True 2d9467ac7c1bda14 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 10 --anchor-density half --c 2 --workers 4 --post-dir outputs/p2/diag/stress/snr10_half --out-dir outputs/p2/diag/train_stress/snr10_half
62 20261027-031710_p3dev/11_train_snr10_topbottom 20261027-031710_p3dev train_snr10_topbottom ok 0 2026-10-27T03:47:33+00:00 2026-10-27T03:51:02+00:00 209.1 0:03:29 cuda:1 a76e61398a3e True 2d9467ac7c1bda14 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --snr 10 --anchor-density topbottom --c 1 2 --workers 4 --post-dir outputs/p2/diag/stress/snr10_topbottom --out-dir outputs/p2/diag/train_stress/snr10_topbottom
63 20261027-031710_p3dev/12_stab_p256 20261027-031710_p3dev stab_p256 ok 0 2026-10-27T03:51:02+00:00 2026-10-27T04:18:40+00:00 1658.2 0:27:38 cuda:1 a76e61398a3e True 2d9467ac7c1bda14 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --smc-seeds 0 1 2 3 --wavelets estR --workers 8 --out-dir outputs/p2/diag/stability/p256
64 20261027-031710_p3dev/13_stab_p1024 20261027-031710_p3dev stab_p1024 ok 0 2026-10-27T04:18:41+00:00 2026-10-27T05:03:46+00:00 2706.0 0:45:06 cuda:1 a76e61398a3e True 3d479783f0f6e711 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --particles 1024 --smc-seeds 0 1 --wavelets estR --workers 4 --gpu-mem-gb 6 --out-dir outputs/p2/diag/stability/p1024
65 20261027-031710_p3dev/14_stress_sa3.5 20261027-031710_p3dev stress_sa3.5 ok 0 2026-10-27T05:03:47+00:00 2026-10-27T05:14:24+00:00 637.4 0:10:37 cuda:1 a76e61398a3e True c168cbbdc9de41d9 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --sigma-a-reg 3.5 --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_full_sa3.5
66 20261027-031710_p3dev/15_stress_sa14 20261027-031710_p3dev stress_sa14 ok 0 2026-10-27T05:14:25+00:00 2026-10-27T05:32:47+00:00 1102.2 0:18:22 cuda:1 a76e61398a3e True 4a5d8059ad8c4365 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --sigma-a-reg 14 --wavelets estR true --workers 8 --out-dir outputs/p2/diag/stress/snr10_full_sa14
67 20261027-031710_p3dev/16_h3_smc 20261027-031710_p3dev h3_smc ok 0 2026-10-27T05:32:48+00:00 2026-10-27T05:39:51+00:00 423.6 0:07:04 cuda:1 a76e61398a3e True 4a5d8059ad8c4365 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device cuda:1 --variants a 1 --methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 2 --workers 4 --post-dir outputs/p2/diag/posterior_gpu --out-dir outputs/p2/diag/h3_smc
68 20261027-031710_p3dev p3dev ok 0 2026-10-27T03:17:10+00:00 2026-10-27T05:39:51+00:00 8561.6 2:22:42 a76e61398a3e True 3f5e60f6dcaff782 runlog bash scripts/run_p3_dev.sh train stability sigma_a h3
69 20261027-054003_p3dev/01_stab_p1024_snr-5 20261027-054003_p3dev stab_p1024_snr-5 ok 0 2026-10-27T05:40:04+00:00 2026-10-27T05:51:32+00:00 688.6 0:11:29 cuda:1 a76e61398a3e True cf576585ccd2ff6b runlog .venv/bin/python scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device cuda:1 --snr -5 --anchor-density full --particles 1024 --smc-seeds 0 1 --wavelets estR --workers 4 --gpu-mem-gb 6 --out-dir outputs/p2/diag/stability/p1024_snr-5
70 20261027-054003_p3dev p3dev ok 0 2026-10-27T05:40:03+00:00 2026-10-27T05:51:32+00:00 688.9 0:11:29 a76e61398a3e True cf576585ccd2ff6b runlog bash scripts/run_p3_dev.sh stability_m5
71 20261027-055202_p3dev/01_b3d_snr10_full 20261027-055202_p3dev b3d_snr10_full failed 1 2026-10-27T05:52:02+00:00 2026-10-27T05:52:43+00:00 40.5 0:00:40 cuda:1 a76e61398a3e True 1b4c4cf8b37e183c runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods B3d --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --post-dir outputs/p2/diag/posterior_gpu --out-dir outputs/p2/diag/train_b3d/snr10_full
72 20261027-055202_p3dev/02_b3d_snr0_full 20261027-055202_p3dev b3d_snr0_full failed 1 2026-10-27T05:52:43+00:00 2026-10-27T05:53:19+00:00 36.5 0:00:36 cuda:1 a76e61398a3e True 1b4c4cf8b37e183c runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods B3d --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --snr 0 --anchor-density full --post-dir outputs/p2/diag/stress/snr0_full --out-dir outputs/p2/diag/train_b3d/snr0_full
73 20261027-055202_p3dev/03_b3d_snr-5_full 20261027-055202_p3dev b3d_snr-5_full failed 1 2026-10-27T05:53:19+00:00 2026-10-27T05:53:56+00:00 36.9 0:00:37 cuda:1 a76e61398a3e True 335b7ba963f4277c runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods B3d --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --snr -5 --anchor-density full --post-dir outputs/p2/diag/stress/snr-5_full --out-dir outputs/p2/diag/train_b3d/snr-5_full
74 20261027-055202_p3dev p3dev ok 0 2026-10-27T05:52:02+00:00 2026-10-27T05:53:56+00:00 114.3 0:01:54 a76e61398a3e True 1b4c4cf8b37e183c runlog bash scripts/run_p3_dev.sh b3d_old
75 20261027-055413_p3dev/01_train_sa3.5 20261027-055413_p3dev train_sa3.5 ok 0 2026-10-27T05:54:13+00:00 2026-10-27T05:57:02+00:00 169.7 0:02:50 cuda:1 a76e61398a3e True a7b91ac7bb476072 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --sigma-a-reg 3.5 --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --post-dir outputs/p2/diag/stress/snr10_full_sa3.5 --out-dir outputs/p2/diag/train_sa/sa3.5
76 20261027-055413_p3dev/02_train_sa14 20261027-055413_p3dev train_sa14 ok 0 2026-10-27T05:57:03+00:00 2026-10-27T05:59:48+00:00 165.9 0:02:46 cuda:1 a76e61398a3e True 75f953c96b36bae4 runlog .venv/bin/python scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device cuda:1 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --sigma-a-reg 14 --budgets-from outputs/p2/diag/train/budgets.json --workers 4 --post-dir outputs/p2/diag/stress/snr10_full_sa14 --out-dir outputs/p2/diag/train_sa/sa14
77 20261027-055413_p3dev p3dev ok 0 2026-10-27T05:54:13+00:00 2026-10-27T05:59:49+00:00 336.0 0:05:36 a76e61398a3e True a7b91ac7bb476072 runlog bash scripts/run_p3_dev.sh train_sa
78 20261027-064712_p2rdev_summary p2rdev_summary ok 0 2026-10-27T06:47:12+00:00 2026-10-27T06:48:41+00:00 89.0 0:01:29 cee2ff085955 True b6a4ccdb0b2a8c48 runlog .venv/bin/python scripts/17_summarize_p2r_dev.py
79 20261027-065508_p2r_main/01_p2r_post_R10 20261027-065508_p2r_main p2r_post_R10 interrupted -15 2026-10-27T06:55:09+00:00 2026-10-27T07:59:43+00:00 3874.4 1:04:34 cuda:1 f95123174f3f True c2052006feeebf10 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 4 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density full --out-dir outputs/p2r/posterior/R10
80 20261027-065508_p2r_main p2r_main interrupted -15 2026-10-27T06:55:08+00:00 2026-10-27T07:59:43+00:00 3875.4 1:04:35 f95123174f3f True c2052006feeebf10 runlog bash scripts/run_p2r_main.sh
81 20261027-080009_p2r_main/01_p2r_post_R10tb 20261027-080009_p2r_main p2r_post_R10tb interrupted -15 2026-10-27T08:00:10+00:00 2026-10-27T08:21:12+00:00 1262.4 0:21:02 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density topbottom --out-dir outputs/p2r/posterior/R10tb
82 20261027-080009_p2r_main/03_p2r_post_R0h 20261027-080009_p2r_main p2r_post_R0h interrupted -15 2026-10-27T08:00:10+00:00 2026-10-27T08:21:12+00:00 1262.4 0:21:02 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 0 --anchor-density half --out-dir outputs/p2r/posterior/R0h
83 20261027-080009_p2r_main/03_p2r_post_R10_sa3.5 20261027-080009_p2r_main p2r_post_R10_sa3.5 ok 0 2026-10-27T08:00:10+00:00 2026-10-27T09:33:58+00:00 5628.0 1:33:48 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 1 --snr 10 --anchor-density full --sigma-a-reg 3.5 --out-dir outputs/p2r/posterior/R10_sa3.5
84 20261027-080009_p2r_main/05_p2r_post_R10 20261027-080009_p2r_main p2r_post_R10 ok 0 2026-10-27T08:00:10+00:00 2026-10-27T09:42:57+00:00 6167.2 1:42:47 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density full --out-dir outputs/p2r/posterior/R10
85 20261027-094720_p2r_main/01_p2r_post_R10_sa3.5 20261027-094720_p2r_main p2r_post_R10_sa3.5 ok 0 2026-10-27T09:47:20+00:00 2026-10-27T09:47:21+00:00 0.8 0:00:01 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 1 --snr 10 --anchor-density full --sigma-a-reg 3.5 --out-dir outputs/p2r/posterior/R10_sa3.5
86 20261027-094722_p2r_main/01_p2r_post_R10 20261027-094722_p2r_main p2r_post_R10 ok 0 2026-10-27T09:47:22+00:00 2026-10-27T09:47:23+00:00 0.9 0:00:01 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density full --out-dir outputs/p2r/posterior/R10
87 20261027-094724_p2r_main/01_p2r_post_Rm5 20261027-094724_p2r_main p2r_post_Rm5 ok 0 2026-10-27T09:47:24+00:00 2026-10-27T09:55:01+00:00 456.5 0:07:37 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:0 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr -5 --anchor-density full --out-dir outputs/p2r/posterior/Rm5
88 20261027-094720_p2r_main/02_p2r_train_R10_sa3.5 20261027-094720_p2r_main p2r_train_R10_sa3.5 ok 0 2026-10-27T09:47:21+00:00 2026-10-27T09:57:31+00:00 609.6 0:10:10 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 3.5 --post-dir outputs/p2r/posterior/R10_sa3.5 --out-dir outputs/p2r/train/R10_sa3.5
89 20261027-094726_p2r_main/01_p2r_post_R0h 20261027-094726_p2r_main p2r_post_R0h ok 0 2026-10-27T09:47:26+00:00 2026-10-27T09:58:42+00:00 675.5 0:11:16 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:0 --workers 3 --gpu-mem-gb 6 --c 0 1 2 --snr 0 --anchor-density half --out-dir outputs/p2r/posterior/R0h
90 20261027-102553_p2r_finish/01_p2r_train_R10_sa14_pass1 20261027-102553_p2r_finish p2r_train_R10_sa14_pass1 ok 0 2026-10-27T10:25:53+00:00 2026-10-27T10:29:44+00:00 231.4 0:03:51 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
91 20261027-094724_p2r_main/02_p2r_train_Rm5 20261027-094724_p2r_main p2r_train_Rm5 ok 0 2026-10-27T09:55:01+00:00 2026-10-27T10:29:45+00:00 2084.0 0:34:44 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr -5 --anchor-density full --post-dir outputs/p2r/posterior/Rm5 --out-dir outputs/p2r/train/Rm5
92 20261027-094724_p2r_main p2r_main ok 0 2026-10-27T09:47:24+00:00 2026-10-27T10:29:45+00:00 2541.0 0:42:21 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog bash scripts/run_p2r_main.sh Rm5
93 20261027-102553_p2r_finish/04_p2r_train_R10_sa14_pass2 20261027-102553_p2r_finish p2r_train_R10_sa14_pass2 ok 0 2026-10-27T10:29:45+00:00 2026-10-27T10:32:37+00:00 172.4 0:02:52 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
94 20261027-094726_p2r_main/02_p2r_train_R0h 20261027-094726_p2r_main p2r_train_R0h ok 0 2026-10-27T09:58:42+00:00 2026-10-27T10:36:20+00:00 2257.6 0:37:38 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density half --post-dir outputs/p2r/posterior/R0h --out-dir outputs/p2r/train/R0h
95 20261027-094726_p2r_main p2r_main ok 0 2026-10-27T09:47:26+00:00 2026-10-27T10:36:20+00:00 2933.5 0:48:54 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog bash scripts/run_p2r_main.sh R0h
96 20261027-102553_p2r_finish/05_p2r_train_R10_sa14_pass3 20261027-102553_p2r_finish p2r_train_R10_sa14_pass3 ok 0 2026-10-27T10:34:37+00:00 2026-10-27T10:36:57+00:00 140.1 0:02:20 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
97 20261027-102553_p2r_finish/02_p2r_train_R0_pass1 20261027-102553_p2r_finish p2r_train_R0_pass1 ok 0 2026-10-27T10:25:53+00:00 2026-10-27T10:43:57+00:00 1083.9 0:18:04 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
98 20261027-102553_p2r_finish/06_p2r_train_R0_pass2 20261027-102553_p2r_finish p2r_train_R0_pass2 ok 0 2026-10-27T10:43:57+00:00 2026-10-27T10:47:54+00:00 236.6 0:03:57 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
99 20261027-102553_p2r_finish/07_p2r_train_R0_pass3 20261027-102553_p2r_finish p2r_train_R0_pass3 ok 0 2026-10-27T10:47:54+00:00 2026-10-27T10:50:25+00:00 151.4 0:02:31 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
100 20261027-102553_p2r_finish/08_p2r_train_R0_pass4 20261027-102553_p2r_finish p2r_train_R0_pass4 ok 0 2026-10-27T10:50:25+00:00 2026-10-27T10:51:52+00:00 86.4 0:01:26 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
101 20261027-102553_p2r_finish/09_p2r_train_R0_pass5 20261027-102553_p2r_finish p2r_train_R0_pass5 ok 0 2026-10-27T10:52:52+00:00 2026-10-27T10:54:20+00:00 87.6 0:01:28 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
102 20261027-102553_p2r_finish/10_p2r_train_R0_pass6 20261027-102553_p2r_finish p2r_train_R0_pass6 ok 0 2026-10-27T10:54:20+00:00 2026-10-27T10:55:44+00:00 83.9 0:01:24 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
103 20261027-102553_p2r_finish/11_p2r_train_R0_pass7 20261027-102553_p2r_finish p2r_train_R0_pass7 ok 0 2026-10-27T10:55:44+00:00 2026-10-27T10:56:57+00:00 72.8 0:01:13 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
104 20261027-094722_p2r_main/02_p2r_train_R10 20261027-094722_p2r_main p2r_train_R10 ok 0 2026-10-27T09:47:23+00:00 2026-10-27T10:57:14+00:00 4190.8 1:09:51 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 10 --anchor-density full --post-dir outputs/p2r/posterior/R10 --out-dir outputs/p2r/train/R10
105 20261027-094722_p2r_main p2r_main ok 0 2026-10-27T09:47:22+00:00 2026-10-27T10:57:14+00:00 4192.1 1:09:52 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog bash scripts/run_p2r_main.sh R10
106 20261027-102553_p2r_finish/12_p2r_train_R0_pass8 20261027-102553_p2r_finish p2r_train_R0_pass8 ok 0 2026-10-27T10:56:57+00:00 2026-10-27T10:58:12+00:00 75.5 0:01:15 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
107 20261027-102553_p2r_finish/13_p2r_train_R0_pass9 20261027-102553_p2r_finish p2r_train_R0_pass9 ok 0 2026-10-27T10:58:13+00:00 2026-10-27T10:59:35+00:00 82.1 0:01:22 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
108 20261027-102553_p2r_finish/14_p2r_train_R0_pass10 20261027-102553_p2r_finish p2r_train_R0_pass10 ok 0 2026-10-27T10:59:35+00:00 2026-10-27T11:01:02+00:00 87.0 0:01:27 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
109 20261027-094716_p2r_main/01_p2r_post_R0 20261027-094716_p2r_main p2r_post_R0 ok 0 2026-10-27T09:47:16+00:00 2026-10-27T11:01:56+00:00 4480.0 1:14:40 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 5 --gpu-mem-gb 6 --c 0 1 2 --snr 0 --anchor-density full --out-dir outputs/p2r/posterior/R0
110 20261027-102553_p2r_finish/15_p2r_train_R0_pass11 20261027-102553_p2r_finish p2r_train_R0_pass11 ok 0 2026-10-27T11:01:02+00:00 2026-10-27T11:02:27+00:00 85.1 0:01:25 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
111 20261027-102553_p2r_finish/16_p2r_train_R0_pass12 20261027-102553_p2r_finish p2r_train_R0_pass12 ok 0 2026-10-27T11:02:27+00:00 2026-10-27T11:03:55+00:00 88.0 0:01:28 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 0 --anchor-density full --post-dir outputs/p2r/posterior/R0 --out-dir outputs/p2r/train/R0
112 20261027-102553_p2r_finish/17_p2r_train_R10_sa14_pass4 20261027-102553_p2r_finish p2r_train_R10_sa14_pass4 ok 0 2026-10-27T11:02:59+00:00 2026-10-27T11:04:16+00:00 77.0 0:01:17 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
113 20261027-102553_p2r_finish/18_p2r_train_R10_sa14_pass5 20261027-102553_p2r_finish p2r_train_R10_sa14_pass5 ok 0 2026-10-27T11:04:16+00:00 2026-10-27T11:05:41+00:00 85.6 0:01:26 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
114 20261027-094718_p2r_main/01_p2r_post_R10tb 20261027-094718_p2r_main p2r_post_R10tb ok 0 2026-10-27T09:47:18+00:00 2026-10-27T11:06:07+00:00 4729.1 1:18:49 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 4 --gpu-mem-gb 6 --c 0 1 2 --snr 10 --anchor-density topbottom --out-dir outputs/p2r/posterior/R10tb
115 20261027-102553_p2r_finish/03_p2r_train_R10tb_pass1 20261027-102553_p2r_finish p2r_train_R10tb_pass1 ok 0 2026-10-27T10:25:53+00:00 2026-10-27T11:06:55+00:00 2461.6 0:41:02 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 3 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 10 --anchor-density topbottom --post-dir outputs/p2r/posterior/R10tb --out-dir outputs/p2r/train/R10tb
116 20261027-102553_p2r_finish/19_p2r_train_R10_sa14_pass6 20261027-102553_p2r_finish p2r_train_R10_sa14_pass6 ok 0 2026-10-27T11:05:42+00:00 2026-10-27T11:07:08+00:00 86.2 0:01:26 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
117 20261027-102553_p2r_finish/21_p2r_train_R10_sa14_pass7 20261027-102553_p2r_finish p2r_train_R10_sa14_pass7 ok 0 2026-10-27T11:10:08+00:00 2026-10-27T11:11:21+00:00 73.2 0:01:13 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
118 20261027-102553_p2r_finish/20_p2r_train_R10tb_pass2 20261027-102553_p2r_finish p2r_train_R10tb_pass2 ok 0 2026-10-27T11:06:55+00:00 2026-10-27T11:16:00+00:00 545.4 0:09:05 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:1 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 0 1 2 --snr 10 --anchor-density topbottom --post-dir outputs/p2r/posterior/R10tb --out-dir outputs/p2r/train/R10tb
119 20261027-102553_p2r_finish/22_p2r_train_R10_sa14_pass8 20261027-102553_p2r_finish p2r_train_R10_sa14_pass8 ok 0 2026-10-27T11:15:22+00:00 2026-10-27T11:16:37+00:00 75.4 0:01:15 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
120 20261027-102553_p2r_finish/23_p2r_train_R10_sa14_pass9 20261027-102553_p2r_finish p2r_train_R10_sa14_pass9 ok 0 2026-10-27T11:18:37+00:00 2026-10-27T11:19:55+00:00 77.9 0:01:18 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
121 20261027-102553_p2r_finish/24_p2r_train_R10_sa14_pass10 20261027-102553_p2r_finish p2r_train_R10_sa14_pass10 ok 0 2026-10-27T11:19:55+00:00 2026-10-27T11:21:25+00:00 89.5 0:01:30 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
122 20261027-102553_p2r_finish/25_p2r_train_R10_sa14_pass11 20261027-102553_p2r_finish p2r_train_R10_sa14_pass11 ok 0 2026-10-27T11:21:25+00:00 2026-10-27T11:22:52+00:00 86.7 0:01:27 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
123 20261027-094720_p2r_main/03_p2r_post_R10_sa14 20261027-094720_p2r_main p2r_post_R10_sa14 ok 0 2026-10-27T09:57:31+00:00 2026-10-27T11:23:05+00:00 5133.7 1:25:34 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog .venv/bin/python scripts/14_diag_posterior.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 --particles 1024 --wavelets estR --device cuda:1 --workers 3 --gpu-mem-gb 6 --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --out-dir outputs/p2r/posterior/R10_sa14
124 20261027-102553_p2r_finish/26_p2r_train_R10_sa14_pass12 20261027-102553_p2r_finish p2r_train_R10_sa14_pass12 ok 0 2026-10-27T11:22:52+00:00 2026-10-27T11:24:14+00:00 82.5 0:01:22 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
125 20261027-102553_p2r_finish/27_p2r_train_R10_sa14_pass13 20261027-102553_p2r_finish p2r_train_R10_sa14_pass13 ok 0 2026-10-27T11:24:15+00:00 2026-10-27T11:25:34+00:00 79.6 0:01:20 cuda:0 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/15_diag_train.py --rids 8 9 10 11 12 13 14 15 --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device cuda:0 --workers 7 --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from outputs/p2/diag/train/budgets.json --save-preds --c 1 --snr 10 --anchor-density full --sigma-a-reg 14 --post-dir outputs/p2r/posterior/R10_sa14 --out-dir outputs/p2r/train/R10_sa14
126 20261027-094716_p2r_main p2r_main interrupted -9 2026-10-27T09:47:16+00:00 2026-10-27T11:25:34+00:00 5898.3 1:38:18 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog bash scripts/run_p2r_main.sh R0
127 20261027-094718_p2r_main p2r_main interrupted -9 2026-10-27T09:47:18+00:00 2026-10-27T11:25:34+00:00 5896.3 1:38:16 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog bash scripts/run_p2r_main.sh R10tb
128 20261027-094720_p2r_main p2r_main interrupted -9 2026-10-27T09:47:20+00:00 2026-10-27T11:25:34+00:00 5894.3 1:38:14 cuda:1 f95123174f3f True 99a0098b80c105f1 runlog bash scripts/run_p2r_main.sh sigma_a
129 20261027-102553_p2r_finish/28_p2r_summary 20261027-102553_p2r_finish p2r_summary ok 0 2026-10-27T11:26:04+00:00 2026-10-27T11:29:30+00:00 205.7 0:03:26 f95123174f3f True 99a0098b80c105f1 runlog nice -n 10 .venv/bin/python scripts/18_summarize_p2r.py
130 20261027-102553_p2r_finish p2r_finish ok 0 2026-10-27T10:25:53+00:00 2026-10-27T11:29:30+00:00 3817.6 1:03:38 f95123174f3f True 99a0098b80c105f1 runlog bash /home/huypq49/tmp/claude-41778/-home-jovyan-lamlvh-ML-Porosity/7df0d403-40c8-45d9-9908-3755738bbf2f/scratchpad/finish_p2r.sh /home/jovyan/lamlvh/ML-Porosity/logs/p2r_resume_20261027-094716

View File

@@ -1,4 +1,4 @@
"""Attribute seismic cho B0b, tính trên trace đầy đủ (cửa sổ mở rộng) rồi mới cắt cửa sổ chính.""" """Seismic attributes for B0b, computed on the full trace (extended window) before cropping to the main window."""
from __future__ import annotations from __future__ import annotations
@@ -9,17 +9,17 @@ FEATURES = ("amplitude", "envelope", "cos_phase", "sin_phase", "inst_freq", "rel
def trace_attributes(trace: np.ndarray, times_ms: np.ndarray, dt_ms: float = 4.0) -> np.ndarray: def trace_attributes(trace: np.ndarray, times_ms: np.ndarray, dt_ms: float = 4.0) -> np.ndarray:
"""Ma trận (L, 7) theo thứ tự FEATURES.""" """(L, 7) matrix in the order of FEATURES."""
s = np.asarray(trace, dtype=float) s = np.asarray(trace, dtype=float)
a = signal.hilbert(s) a = signal.hilbert(s)
env = np.abs(a) env = np.abs(a)
ph = np.unwrap(np.angle(a)) ph = np.unwrap(np.angle(a))
f_inst = np.gradient(ph) / (2 * np.pi * dt_ms / 1000.0) f_inst = np.gradient(ph) / (2 * np.pi * dt_ms / 1000.0)
# tần số tức thời trọng số theo envelope rồi làm trơn 5 mẫu để bớt gai # envelope-weighted instantaneous frequency, smoothed over 5 samples to suppress spikes
k = np.ones(5) k = np.ones(5)
f_inst = np.convolve(f_inst * env**2, k, "same") / (np.convolve(env**2, k, "same") + 1e-12) f_inst = np.convolve(f_inst * env**2, k, "same") / (np.convolve(env**2, k, "same") + 1e-12)
f_inst = np.clip(f_inst, 0.0, 500.0 / dt_ms) f_inst = np.clip(f_inst, 0.0, 500.0 / dt_ms)
# relative AI: tích phân trace, bỏ xu hướng < 5 Hz # relative AI: integrated trace with the < 5 Hz trend removed
rai = np.cumsum(s) rai = np.cumsum(s)
sos = signal.butter(4, 5.0, btype="highpass", fs=1000.0 / dt_ms, output="sos") sos = signal.butter(4, 5.0, btype="highpass", fs=1000.0 / dt_ms, output="sos")
rai = signal.sosfiltfilt(sos, rai) rai = signal.sosfiltfilt(sos, rai)

View File

@@ -1,4 +1,4 @@
"""B1: post-stack model-based AI inversion (PyLops) với LFM nội suy theo horizon, rồi φ = a + b·AI.""" """B1: post-stack model-based AI inversion (PyLops) with a horizon-guided interpolated LFM, followed by φ = a + b·AI."""
from __future__ import annotations from __future__ import annotations
@@ -10,7 +10,7 @@ from ml_porosity.data.wavelet import estimate_wavelet_ls
def fill_edges(x: np.ndarray) -> np.ndarray: def fill_edges(x: np.ndarray) -> np.ndarray:
"""Thay NaN bằng nội suy tuyến tính, giữ hằng ở hai đầu.""" """Replace NaNs by linear interpolation, holding values constant at both ends."""
x = np.asarray(x, dtype=float).copy() x = np.asarray(x, dtype=float).copy()
ok = np.isfinite(x) ok = np.isfinite(x)
x[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), x[ok]) x[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), x[ok])
@@ -23,8 +23,8 @@ def lowpass(x: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) ->
def strat_map(t: np.ndarray, h_from: np.ndarray, h_to: np.ndarray) -> np.ndarray: def strat_map(t: np.ndarray, h_from: np.ndarray, h_to: np.ndarray) -> np.ndarray:
"""Ánh xạ thời gian ở giếng đích sang thời gian tương đương địa tầng ở giếng nguồn: nội suy """Map times at the target well to stratigraphically equivalent times at the source well: piecewise-linear
tuyến tính từng đoạn qua các cặp horizon (h_from → h_to), ngoài cùng thì dịch song song.""" interpolation through the horizon pairs (h_from → h_to), with a parallel shift beyond the outermost horizons."""
ok = np.isfinite(h_from) & np.isfinite(h_to) ok = np.isfinite(h_from) & np.isfinite(h_to)
a, b = h_from[ok], h_to[ok] a, b = h_from[ok], h_to[ok]
order = np.argsort(a) order = np.argsort(a)
@@ -38,7 +38,7 @@ def strat_map(t: np.ndarray, h_from: np.ndarray, h_to: np.ndarray) -> np.ndarray
def build_lfm(t, target_h, target_xy, wells: dict, f_c_hz: float = 6.0, power: float = 2.0) -> np.ndarray: def build_lfm(t, target_h, target_xy, wells: dict, f_c_hz: float = 6.0, power: float = 2.0) -> np.ndarray:
"""wells[name] = {"logai": (L,), "h": (H,), "xy": (2,)} trên cùng trục t. Trả về LFM của log(AI).""" """wells[name] = {"logai": (L,), "h": (H,), "xy": (2,)} on a common t axis. Returns the LFM of log(AI)."""
num = np.zeros_like(t, dtype=float) num = np.zeros_like(t, dtype=float)
den = 0.0 den = 0.0
for w in wells.values(): for w in wells.values():
@@ -53,7 +53,7 @@ def build_lfm(t, target_h, target_xy, wells: dict, f_c_hz: float = 6.0, power: f
def operator_reflectivity(logai: np.ndarray, nspike: int = 33) -> np.ndarray: def operator_reflectivity(logai: np.ndarray, nspike: int = 33) -> np.ndarray:
"""Reflectivity theo đúng quy ước của PoststackLinearModelling (wavelet xung đơn vị).""" """Reflectivity following the exact convention of PoststackLinearModelling (unit-spike wavelet)."""
spike = np.zeros(nspike) spike = np.zeros(nspike)
spike[nspike // 2] = 1.0 spike[nspike // 2] = 1.0
G0 = PoststackLinearModelling(spike, len(logai), explicit=True).A G0 = PoststackLinearModelling(spike, len(logai), explicit=True).A
@@ -67,7 +67,7 @@ def estimate_wavelet(train_logai: list[np.ndarray], train_seis: list[np.ndarray]
def invert(seis: np.ndarray, wav: np.ndarray, lfm: np.ndarray, e: float) -> np.ndarray: def invert(seis: np.ndarray, wav: np.ndarray, lfm: np.ndarray, e: float) -> np.ndarray:
"""log(AI) nghịch đảo: Tikhonov về LFM với epsI = e·trace(GᵀG)/n.""" """Inverted log(AI): Tikhonov regularisation towards the LFM with epsI = e·trace(GᵀG)/n."""
G = PoststackLinearModelling(wav, len(seis), explicit=True).A G = PoststackLinearModelling(wav, len(seis), explicit=True).A
eps = e * np.trace(G.T @ G) / len(seis) eps = e * np.trace(G.T @ G) / len(seis)
m, _ = PoststackInversion(seis, wav, m0=lfm, explicit=True, epsI=eps, simultaneous=False) m, _ = PoststackInversion(seis, wav, m0=lfm, explicit=True, epsI=eps, simultaneous=False)

View File

@@ -1,9 +1,9 @@
"""Biến đổi bin (inline/crossline) ↔ XY theo file `.survey` của OpendTect. """Bin (inline/crossline) ↔ XY transformation from the OpendTect `.survey` file.
`.survey` lưu phép biến đổi affine `.survey` stores the affine transformation
X = x0 + a_x·IL + b_x·XL X = x0 + a_x·IL + b_x·XL
Y = y0 + a_y·IL + b_y·XL Y = y0 + a_y·IL + b_y·XL
trong các dòng `Coord-X-BinID: x0`a_x`b_x` và `Coord-Y-BinID: y0`a_y`b_y`. in the lines `Coord-X-BinID: x0`a_x`b_x` and `Coord-Y-BinID: y0`a_y`b_y`.
""" """
from __future__ import annotations from __future__ import annotations
@@ -62,7 +62,7 @@ class SurveyGeometry:
@classmethod @classmethod
def from_points(cls, il, xl, x, y, z_range=(np.nan, np.nan, np.nan), epsg: int | None = None) -> SurveyGeometry: def from_points(cls, il, xl, x, y, z_range=(np.nan, np.nan, np.nan), epsg: int | None = None) -> SurveyGeometry:
"""Khớp affine bình phương tối thiểu từ các điểm (IL, XL, X, Y), ví dụ các nút của một horizon.""" """Least-squares affine fit from (IL, XL, X, Y) points, e.g. the nodes of a horizon."""
il, xl, x, y = (np.asarray(v, dtype=float).ravel() for v in (il, xl, x, y)) il, xl, x, y = (np.asarray(v, dtype=float).ravel() for v in (il, xl, x, y))
A = np.c_[np.ones_like(il), il, xl] A = np.c_[np.ones_like(il), il, xl]
cx, *_ = np.linalg.lstsq(A, x, rcond=None) cx, *_ = np.linalg.lstsq(A, x, rcond=None)
@@ -87,7 +87,7 @@ class SurveyGeometry:
return x, y return x, y
def xy_to_bin(self, x, y): def xy_to_bin(self, x, y):
"""Bin (thực, chưa làm tròn) tương ứng với XY.""" """Real-valued (unrounded) bin corresponding to XY."""
x = np.asarray(x, dtype=float) x = np.asarray(x, dtype=float)
y = np.asarray(y, dtype=float) y = np.asarray(y, dtype=float)
rhs = np.stack([x - self.x_coef[0], y - self.y_coef[0]]) rhs = np.stack([x - self.x_coef[0], y - self.y_coef[0]])
@@ -99,7 +99,7 @@ class SurveyGeometry:
return int(np.rint(il)), int(np.rint(xl)) return int(np.rint(il)), int(np.rint(xl))
def bin_spacing(self) -> tuple[float, float]: def bin_spacing(self) -> tuple[float, float]:
"""Khoảng cách (m) giữa hai inline liên tiếp và hai crossline liên tiếp.""" """Spacing (m) between consecutive inlines and between consecutive crosslines."""
m = self._matrix() m = self._matrix()
return float(np.hypot(*m[:, 0])), float(np.hypot(*m[:, 1])) return float(np.hypot(*m[:, 0])), float(np.hypot(*m[:, 1]))

View File

@@ -1,4 +1,4 @@
"""Horizon F3 dạng ASCII (X, Y, TWT ms) trong Rawdata/Surface_data/.""" """F3 horizons in ASCII format (X, Y, TWT ms) under Rawdata/Surface_data/."""
from __future__ import annotations from __future__ import annotations
@@ -9,7 +9,7 @@ import numpy as np
from ml_porosity.data.geometry import SurveyGeometry from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.paths import f3_root from ml_porosity.paths import f3_root
# Thứ tự từ nông đến sâu tại khu vực giếng. # Ordered from shallow to deep in the well area.
F3_HORIZONS = ("Shallow", "FS8", "FS7", "Truncation", "Top-Foresets", "FS6", "MFS4") F3_HORIZONS = ("Shallow", "FS8", "FS7", "Truncation", "Top-Foresets", "FS6", "MFS4")
@@ -18,7 +18,7 @@ def horizon_path(name: str) -> Path:
def load_horizon_bins(name: str, geom: SurveyGeometry) -> dict[tuple[int, int], float]: def load_horizon_bins(name: str, geom: SurveyGeometry) -> dict[tuple[int, int], float]:
"""Ánh xạ (IL, XL) → TWT (ms). Mỗi dòng XY được gán về bin gần nhất.""" """Map (IL, XL) → TWT (ms). Each XY row is assigned to the nearest bin."""
a = np.loadtxt(horizon_path(name)) a = np.loadtxt(horizon_path(name))
il, xl = geom.xy_to_bin(a[:, 0], a[:, 1]) il, xl = geom.xy_to_bin(a[:, 0], a[:, 1])
il, xl = np.rint(il).astype(int), np.rint(xl).astype(int) il, xl = np.rint(il).astype(int), np.rint(xl).astype(int)
@@ -26,8 +26,8 @@ def load_horizon_bins(name: str, geom: SurveyGeometry) -> dict[tuple[int, int],
def horizon_at(name: str, geom: SurveyGeometry, bins: list[tuple[int, int]], radius: int = 2) -> np.ndarray: def horizon_at(name: str, geom: SurveyGeometry, bins: list[tuple[int, int]], radius: int = 2) -> np.ndarray:
"""TWT của horizon tại từng bin; nếu bin không có pick thì lấy trung bình các pick trong """Horizon TWT at each bin; if a bin has no pick, the mean of the picks within the
ô (2r+1)², NaN nếu ô cũng trống.""" (2r+1)² window is used, or NaN if the window is also empty."""
h = load_horizon_bins(name, geom) h = load_horizon_bins(name, geom)
out = [] out = []
for il, xl in bins: for il, xl in bins:

View File

@@ -1,7 +1,7 @@
"""Đọc dữ liệu giếng F3: LAS, marker, checkshot, track và các mô hình TD. """Readers for F3 well data: LAS, markers, checkshots, tracks and TD models.
Quy ước độ sâu: MD tính từ KB (m). Bốn giếng F3 đều thẳng đứng nên MD = TVD + 0 Depth convention: MD is measured from KB (m). All four F3 wells are vertical, so MD = TVD + 0
so với KB; TVDSS = MD − KB. relative to KB; TVDSS = MD − KB.
""" """
from __future__ import annotations from __future__ import annotations
@@ -17,7 +17,7 @@ from ml_porosity.paths import f3_root, f3_wells_dir
F3_WELLS = ("F02-1", "F03-2", "F03-4", "F06-1") F3_WELLS = ("F02-1", "F03-2", "F03-4", "F06-1")
# Vị trí IL/XL mà luận văn dùng (test 2/prepare_data.py:17–21); chỉ để audit, không dùng. # IL/XL locations used in the thesis (test 2/prepare_data.py:17–21); for auditing only, not used.
LEGACY_IL_XL = {"F03-4": (362, 821), "F02-1": (418, 608), "F06-1": (283, 842)} LEGACY_IL_XL = {"F03-4": (362, 821), "F02-1": (418, 608), "F06-1": (283, 842)}
@@ -27,10 +27,10 @@ class Well:
x: float x: float
y: float y: float
kb: float kb: float
logs: pd.DataFrame # index = MD (m), cột = mnemonic, NaN thay cho NULL logs: pd.DataFrame # index = MD (m), columns = mnemonics, NaN in place of NULL
units: dict[str, str] = field(default_factory=dict) units: dict[str, str] = field(default_factory=dict)
markers: pd.DataFrame | None = None # cột: md, name markers: pd.DataFrame | None = None # columns: md, name
checkshot: pd.DataFrame | None = None # cột: md, twt_ms (marker TD, xem plan mục 1.2e) checkshot: pd.DataFrame | None = None # columns: md, twt_ms (marker TD, see plan §1.2e)
@property @property
def md(self) -> np.ndarray: def md(self) -> np.ndarray:
@@ -50,8 +50,8 @@ def read_las(path: str | Path) -> tuple[pd.DataFrame, dict[str, str], lasio.LASF
def read_two_columns(path: str | Path, skip_header: bool = False) -> np.ndarray: def read_two_columns(path: str | Path, skip_header: bool = False) -> np.ndarray:
"""Đọc file hai cột số (depth, value). `skip_header=True` cho file OpendTect """Read a two-column numeric file (depth, value). `skip_header=True` for OpendTect files
(.wlt, .csmdl) có phần đầu kết thúc bằng dòng `!` thứ hai.""" (.wlt, .csmdl) whose header ends at the second `!` line."""
lines = Path(path).read_text(errors="replace").splitlines() lines = Path(path).read_text(errors="replace").splitlines()
if skip_header: if skip_header:
bangs = [i for i, s in enumerate(lines) if s.strip() == "!"] bangs = [i for i, s in enumerate(lines) if s.strip() == "!"]
@@ -79,7 +79,7 @@ def read_markers(path: str | Path) -> pd.DataFrame:
def read_track(path: str | Path) -> np.ndarray: def read_track(path: str | Path) -> np.ndarray:
"""Cột: X, Y, TVDSS (m), MD (m).""" """Columns: X, Y, TVDSS (m), MD (m)."""
return np.loadtxt(path) return np.loadtxt(path)
@@ -91,7 +91,7 @@ def load_well(name: str, wells_dir: Path | None = None) -> Well:
kb = float(las.well["EKB"].value) kb = float(las.well["EKB"].value)
markers = read_markers(d / "Tops" / f"{name}_markers.txt") markers = read_markers(d / "Tops" / f"{name}_markers.txt")
# File checkshot có dòng trùng (nhiều marker cùng độ sâu) và không theo thứ tự (F03-2, F03-4). # Checkshot files contain duplicate rows (several markers at the same depth) and are unsorted (F03-2, F03-4).
cs = read_two_columns(d / "Checkshot" / f"{name}_TD.txt") cs = read_two_columns(d / "Checkshot" / f"{name}_TD.txt")
checkshot = ( checkshot = (
pd.DataFrame({"md": cs[:, 0], "twt_ms": cs[:, 1] * 1000.0}) pd.DataFrame({"md": cs[:, 0], "twt_ms": cs[:, 1] * 1000.0})
@@ -102,12 +102,12 @@ def load_well(name: str, wells_dir: Path | None = None) -> Well:
def load_td_source(name: str, source: str) -> np.ndarray: def load_td_source(name: str, source: str) -> np.ndarray:
"""Cặp (MD m, TWT ms) từ một nguồn TD. """(MD m, TWT ms) pairs from a TD source.
source: source:
"checkshot" – Checkshot/*_TD.txt (thời gian marker đã tie với horizon, giây) "checkshot" – Checkshot/*_TD.txt (marker times tied to horizons, seconds)
"dt_model" – DT_model/*_TD.txt (ms; nguồn gốc chưa rõ, lệch checkshot, plan mục 1.2c) "dt_model" – DT_model/*_TD.txt (ms; unknown provenance, offset from checkshot, plan §1.2c)
"wlt" – WellInfo/*.wlt (Depth2Time model của OpendTect, giây) "wlt" – WellInfo/*.wlt (OpendTect Depth2Time model, seconds)
""" """
d = f3_wells_dir() d = f3_wells_dir()
if source == "checkshot": if source == "checkshot":
@@ -118,4 +118,4 @@ def load_td_source(name: str, source: str) -> np.ndarray:
if source == "wlt": if source == "wlt":
a = read_two_columns(f3_root() / "WellInfo" / f"{name}.wlt", skip_header=True) a = read_two_columns(f3_root() / "WellInfo" / f"{name}.wlt", skip_header=True)
return np.column_stack([a[:, 0], a[:, 1] * 1000.0]) return np.column_stack([a[:, 0], a[:, 1] * 1000.0])
raise ValueError(f"nguồn TD không hợp lệ: {source}") raise ValueError(f"invalid TD source: {source}")

View File

@@ -1,8 +1,9 @@
"""Chuyển log từ miền độ sâu sang trục thời gian seismic, có lọc chống alias. """Depth-to-time conversion of logs onto the seismic time axis, with anti-alias filtering.
Luận văn nội suy điểm log 0.15 m xuống 4 ms (prepare_data.py:203–204), gây alias The thesis point-interpolates 0.15 m log samples directly to 4 ms (prepare_data.py:203–204),
(plan mục 1.1 #8). Ở đây log được đưa lên lưới thời gian mịn, lọc thông thấp which causes aliasing (plan §1.1 #8). Here the log is first mapped onto a fine time grid,
Butterworth pha không (sosfiltfilt) ở `cutoff_frac`·Nyquist của lưới đích, rồi mới lấy mẫu. low-pass filtered with a zero-phase Butterworth filter (sosfiltfilt) at `cutoff_frac`·Nyquist
of the target grid, and only then resampled.
""" """
from __future__ import annotations from __future__ import annotations
@@ -22,10 +23,10 @@ def log_to_time(
cutoff_frac: float = 0.8, cutoff_frac: float = 0.8,
order: int = 6, order: int = 6,
) -> np.ndarray: ) -> np.ndarray:
"""Giá trị log tại `t_out_ms` (lưới đều). NaN ở nơi log không phủ tới. """Log values at `t_out_ms` (regular grid). NaN where the log has no coverage.
Khoảng trống bên trong log được nội suy tuyến tính trước khi lọc rồi đặt lại NaN Internal gaps in the log are linearly interpolated before filtering, and target
ở những mẫu đích rơi vào khoảng trống.""" samples falling inside a gap are reset to NaN afterwards."""
md = np.asarray(md, dtype=float) md = np.asarray(md, dtype=float)
v = np.asarray(values, dtype=float) v = np.asarray(values, dtype=float)
ok = np.isfinite(v) ok = np.isfinite(v)
@@ -46,7 +47,7 @@ def log_to_time(
out = np.interp(t_out_ms, t_fine, v_fine, left=np.nan, right=np.nan) out = np.interp(t_out_ms, t_fine, v_fine, left=np.nan, right=np.nan)
# Đánh dấu NaN tại mẫu đích nằm trong khoảng trống log dài hơn một mẫu đích. # Set to NaN the target samples lying in log gaps longer than one target sample.
gaps = np.flatnonzero(np.diff(t_log) > dt_out) gaps = np.flatnonzero(np.diff(t_log) > dt_out)
for g in gaps: for g in gaps:
out[(t_out_ms > t_log[g]) & (t_out_ms < t_log[g + 1])] = np.nan out[(t_out_ms > t_log[g]) & (t_out_ms < t_log[g + 1])] = np.nan

View File

@@ -1,11 +1,12 @@
"""Đọc trace từ SEG-Y post-stack theo (IL, XL) mà không nạp cả cube. """Read traces from a post-stack SEG-Y by (IL, XL) without loading the whole cube.
Lưu ý F3_entire.segy: DelayRecordingTime = 4 ms nên mẫu đầu ở 4 ms (segyio đã tính), Note on F3_entire.segy: DelayRecordingTime = 4 ms, so the first sample is at 4 ms (handled by segyio),
trong khi `.survey` ghi Z range bắt đầu từ 0. whereas `.survey` gives a Z range starting at 0.
Lưu ý stack ST10010 của Volve: (1) thiếu 26 trace ở rìa nên segyio không mở được ở chế độ strict, phải tra Note on the Volve ST10010 stack: (1) 26 edge traces are missing, so segyio cannot open it in strict mode and
trace theo header; (2) byte 215 (scalar cho các trường thời gian) = 3, không phải luỹ thừa của 10, nhưng segyio traces must be looked up from the headers; (2) byte 215 (scalar for the time fields) = 3, which is not a power
vẫn nhân DelayRecordingTime = 4 với 3, khiến mẫu đầu thành 12 ms thay vì 4 ms như textual header ghi. of 10, yet segyio still multiplies DelayRecordingTime = 4 by 3, placing the first sample at 12 ms instead of
the 4 ms stated in the textual header.
""" """
from __future__ import annotations from __future__ import annotations
@@ -17,7 +18,7 @@ import segyio
from ml_porosity.paths import f3_segy from ml_porosity.paths import f3_segy
# Giá trị hợp lệ của scalar thời gian (byte 215) theo SEG-Y rev 1; 0 nghĩa là không áp dụng # Valid values of the time scalar (byte 215) per SEG-Y rev 1; 0 means not applied
_TIME_SCALARS = {0, 1, -1, 10, -10, 100, -100, 1000, -1000, 10000, -10000} _TIME_SCALARS = {0, 1, -1, 10, -10, 100, -100, 1000, -1000, 10000, -10000}
@@ -28,13 +29,13 @@ class SeismicCube:
try: try:
self._f = segyio.open(str(self.path), "r") self._f = segyio.open(str(self.path), "r")
if self._f.sorting != segyio.TraceSortingFormat.INLINE_SORTING: if self._f.sorting != segyio.TraceSortingFormat.INLINE_SORTING:
raise ValueError("chỉ hỗ trợ SEG-Y sắp xếp theo inline") raise ValueError("only inline-sorted SEG-Y is supported")
self.ilines = np.asarray(self._f.ilines) self.ilines = np.asarray(self._f.ilines)
self.xlines = np.asarray(self._f.xlines) self.xlines = np.asarray(self._f.xlines)
except ValueError as e: except ValueError as e:
if "sắp xếp" in str(e): if "inline-sorted" in str(e):
raise raise
# lưới không đủ trace: tra chỉ số trace theo header IL/XL # incomplete grid: look up trace indices from the IL/XL headers
self._f = segyio.open(str(self.path), "r", ignore_geometry=True) self._f = segyio.open(str(self.path), "r", ignore_geometry=True)
il = self._f.attributes(segyio.TraceField.INLINE_3D)[:] il = self._f.attributes(segyio.TraceField.INLINE_3D)[:]
xl = self._f.attributes(segyio.TraceField.CROSSLINE_3D)[:] xl = self._f.attributes(segyio.TraceField.CROSSLINE_3D)[:]
@@ -58,16 +59,16 @@ class SeismicCube:
def _index(self, il: int, xl: int) -> int: def _index(self, il: int, xl: int) -> int:
if self._lut is not None: if self._lut is not None:
if (il, xl) not in self._lut: if (il, xl) not in self._lut:
raise KeyError(f"bin ({il}, {xl}) không có trace trong cube") raise KeyError(f"bin ({il}, {xl}) has no trace in the cube")
return self._lut[(il, xl)] return self._lut[(il, xl)]
i = np.searchsorted(self.ilines, il) i = np.searchsorted(self.ilines, il)
j = np.searchsorted(self.xlines, xl) j = np.searchsorted(self.xlines, xl)
if i >= len(self.ilines) or self.ilines[i] != il or j >= len(self.xlines) or self.xlines[j] != xl: if i >= len(self.ilines) or self.ilines[i] != il or j >= len(self.xlines) or self.xlines[j] != xl:
raise KeyError(f"bin ({il}, {xl}) nằm ngoài cube") raise KeyError(f"bin ({il}, {xl}) lies outside the cube")
return int(i * len(self.xlines) + j) return int(i * len(self.xlines) + j)
def coords(self, il: int, xl: int) -> tuple[float, float]: def coords(self, il: int, xl: int) -> tuple[float, float]:
"""Toạ độ CDP (byte 181/185) của bin, đã áp scalar ở byte 71.""" """CDP coordinates (bytes 181/185) of the bin, with the byte-71 scalar applied."""
h = self._f.header[self._index(il, xl)] h = self._f.header[self._index(il, xl)]
sc = h[segyio.TraceField.SourceGroupScalar] sc = h[segyio.TraceField.SourceGroupScalar]
mul = 1 / abs(sc) if sc < 0 else (sc or 1) mul = 1 / abs(sc) if sc < 0 else (sc or 1)
@@ -77,8 +78,8 @@ class SeismicCube:
return np.asarray(self._f.trace[self._index(il, xl)], dtype=np.float32) return np.asarray(self._f.trace[self._index(il, xl)], dtype=np.float32)
def patch(self, il: int, xl: int, radius: int) -> np.ndarray: def patch(self, il: int, xl: int, radius: int) -> np.ndarray:
"""Các trace trong ô (2r+1)×(2r+1) quanh (il, xl), thứ tự IL rồi XL: shape (C, nt). """Traces in the (2r+1)×(2r+1) window around (il, xl), ordered by IL then XL: shape (C, nt).
Khác luận văn: không kẹp chỉ số ở biên mà báo lỗi nếu ô vượt ra ngoài cube.""" Unlike the thesis, indices are not clamped at the edges; an error is raised if the window extends outside the cube."""
return np.stack( return np.stack(
[ [
self.trace(il + di, xl + dx) self.trace(il + di, xl + dx)
@@ -88,5 +89,5 @@ class SeismicCube:
) )
def window(self, t0_ms: float, t1_ms: float) -> np.ndarray: def window(self, t0_ms: float, t1_ms: float) -> np.ndarray:
"""Mặt nạ boolean cho các mẫu trong [t0, t1].""" """Boolean mask of the samples within [t0, t1]."""
return (self.times_ms >= t0_ms) & (self.times_ms <= t1_ms) return (self.times_ms >= t0_ms) & (self.times_ms <= t1_ms)

View File

@@ -0,0 +1,267 @@
"""D2: F3-calibrated synthetic dataset with known ground-truth registration (plan §5.1, §5.5).
Earth model in true time t: a stratigraphic framework from 5 laterally extensive F3 horizons (Shallow, FS8,
FS7, Truncation, MFS4), subdivided into sub-units of thickness ≈ `sub_unit_ms` (proportional sub-surfaces
between horizons, parallel above Shallow and below MFS4). Porosity
φ(t) = φ0 + slope·(t − 850) + o_u(x, y) + GRF(s(t)),
where s is the stratigraphic coordinate (strat_map onto the median horizon times), o_u is a per-unit offset
(with a linear lateral gradient), and GRF is a sum of OU processes in s, independent across pseudo-wells
(spaced ≥ 500 m apart). Exact F3 rock physics: DT = (φ + 0.2018)/0.0011, RHOB = 2650 − 1600φ,
AI = RHOB·10⁶/DT. Seismic: 3×3 patch (using the horizons of neighbouring bins), forward model
tie_likelihood.forward_fine with the F3 wavelet, and band-limited noise scaled to the target SNR.
Registration: logs lie on the τ axis (sonic time). True warp t(τ) = τ + b + ∫(e^g − 1) with
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.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
from ml_porosity.baselines.inversion import strat_map
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
def phi_to_ai(phi: np.ndarray) -> np.ndarray:
dt = (phi - PHI_DT_A) / PHI_DT_B # µs/m
return (2650.0 - 1600.0 * phi) * 1e6 / dt
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)
x = np.empty(n)
x[0] = sd * rng.standard_normal()
for i in range(1, n):
x[i] = rho * x[i - 1] + e[i]
return x
@dataclass
class HorizonGrid:
h: np.ndarray # (H, nIL, nXL) TWT ms, NaN if missing
il0: int
xl0: int
geom: object
def at(self, il: int, xl: int) -> np.ndarray:
return self.h[:, il - self.il0, xl - self.xl0]
def valid_mask(self, min_gap_ms: float = 8.0, radius: int = 1) -> np.ndarray:
ok = np.all(np.isfinite(self.h), 0)
ok[ok] &= np.all(np.diff(self.h[:, ok], axis=0) >= min_gap_ms, 0)
out = ok.copy()
for di in range(-radius, radius + 1):
for dj in range(-radius, radius + 1):
out &= np.roll(np.roll(ok, di, 0), dj, 1)
out[:radius], out[-radius:], out[:, :radius], out[:, -radius:] = False, False, False, False
return out
@dataclass
class D2Well:
name: str
il: int
xl: int
x: float
y: float
seis_clean: np.ndarray # (9, L_ext) noise-free
noise_unit: np.ndarray # (9, L_ext) band-limited noise, unit variance on the centre trace
phi_t: np.ndarray # φ of the centre trace on t_fine
z_g: np.ndarray # (n_grid,) standard normal draws for g
z_b: float
boundaries_t: np.ndarray # unit boundaries (true time) within the extended window
eps_a: np.ndarray # standard normal pick noise, same length as boundaries_t
extra: dict = field(default_factory=dict)
class D2Realization:
"""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):
self.cfg, self.rid, self.drift = cfg, rid, drift
rng = np.random.default_rng([int(rid), 20261026])
f = cfg["fine_dt_ms"]
self.dt = cfg["dt_ms"]
self.t_fine = np.arange(cfg["model_t_ms"][0], cfg["model_t_ms"][1] + f / 2, f)
self.tau_fine = np.arange(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1] + f / 2, f)
self.grid = WarpGrid(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1], cfg["warp_dtau_ms"])
e0, e1 = cfg["ext_window_ms"]
m0, m1 = cfg["main_window_ms"]
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)))
# Stratigraphic framework
valid = hg.valid_mask(cfg["min_gap_ms"], cfg["patch_radius"])
H = hg.h[:, valid]
self.h_ref = np.median(H, axis=1)
self.S_ref = self._unit_surfaces(self.h_ref, cfg["sub_unit_ms"], *cfg["model_t_ms"])
self.hg = hg
# Well locations: test wells first, then the training pool (nested by order)
ii, jj = np.nonzero(valid)
il_all, xl_all = ii + hg.il0, jj + hg.xl0
xy = np.column_stack(hg.geom.bin_to_xy(il_all, xl_all))
order = rng.permutation(len(il_all))
W = cfg["wells"]
test, train = [], []
for k in order:
p = xy[k]
if len(test) < W["n_test"]:
if all(np.hypot(*(p - xy[q])) >= W["min_dist_test_m"] for q in test):
test.append(k)
elif len(train) < W["n_train_pool"]:
if all(np.hypot(*(p - xy[q])) >= W["min_dist_test_m"] for q in test) and \
all(np.hypot(*(p - xy[q])) >= W["min_dist_train_m"] for q in train):
train.append(k)
else:
break
if len(train) < W["n_train_pool"]:
raise RuntimeError("not enough pseudo-well locations satisfying the spacing constraints")
# Realization-level properties
P = cfg["property"]
self.phi0 = P["phi0"] + P["phi0_sd"] * rng.standard_normal()
nu = len(self.S_ref) + 1
self.unit_off = P["unit_offset_sd"] * rng.standard_normal(nu)
self.unit_grad = P["unit_lateral_sd"] * rng.standard_normal((nu, 2))
xy_all = xy
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.wells: list[D2Well] = []
for tag, idx in [("T", test), ("P", train)]:
for n, k in enumerate(idx):
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"]:]
# ------------------------------------------------------------ earth model
@staticmethod
def _unit_surfaces(h_ref, sub_ms, t0, t1) -> np.ndarray:
s = [h_ref[0] - k * sub_ms for k in range(int((h_ref[0] - t0) // sub_ms), 0, -1)]
for a, b in zip(h_ref[:-1], h_ref[1:]):
n = max(1, int(round((b - a) / sub_ms)))
s += list(a + (b - a) * np.arange(n) / n)
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):
s = strat_map(self.t_fine, h_bin, self.h_ref)
unit = np.searchsorted(self.S_ref, s)
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
phi = phi + np.interp(s, s_axis, grf_s)
return np.clip(phi, *self.cfg["property"]["clip"])
def _make_well(self, name, il, xl, rng) -> D2Well:
P, r = self.cfg["property"], self.cfg["patch_radius"]
f = self.cfg["fine_dt_ms"]
s_axis = np.arange(self.t_fine[0] - 200, self.t_fine[-1] + 200 + f / 2, f)
grf = sum(ou_process(len(s_axis), f, c["sd"], c["ell_ms"], rng) for c in P["grf"])
traces, phi_c = [], None
for di in range(-r, r + 1):
for dj in range(-r, r + 1):
h = self.hg.at(il + di, xl + dj)
xy = np.array(self.hg.geom.bin_to_xy(il + di, xl + dj), dtype=float).ravel()
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)]
for wn in white])
noise /= noise[len(traces) // 2].std()
h0 = self.hg.at(il, xl)
bt = strat_map(self.S_ref, self.h_ref, h0)
bt = bt[(bt >= self.t_ext[0]) & (bt <= self.t_ext[-1])]
x, y = (float(v) for v in np.ravel(self.hg.geom.bin_to_xy(il, xl)))
return D2Well(name, il, xl, x, y, seis, noise, phi_c, rng.standard_normal(self.grid.n),
float(rng.standard_normal()), bt, rng.standard_normal(len(bt)))
# ------------------------------------------------------------ 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
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 = 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})")
phi_log = np.interp(t_tau, self.t_fine, w.phi_t)
seis = w.seis_clean.copy()
if snr_db is not None and np.isfinite(snr_db):
ps = np.mean(w.seis_clean[len(seis) // 2] ** 2)
seis = seis + np.sqrt(ps / 10 ** (snr_db / 10)) * w.noise_unit
tau_k = np.interp(w.boundaries_t, t_tau, self.tau_fine)
t_k = w.boundaries_t + sigma_a_ms * w.eps_a
keep = self._anchor_subset(len(tau_k), anchor_density)
f = self.cfg["fine_dt_ms"]
y_true = np.interp(self.t_main, self.t_fine, antialias(w.phi_t, f, self.dt))
return {"name": w.name, "seis": seis.astype(np.float32), "tau_fine": self.tau_fine, "phi_log": phi_log,
"ai_log": phi_to_ai(phi_log), "tau_k": tau_k[keep], "t_k": t_k[keep], "b": b, "g": g,
"t_of_tau_true": t_tau, "y_true": y_true, "xy": (w.x, w.y)}
@staticmethod
def _anchor_subset(n: int, density: str) -> np.ndarray:
if density == "full":
return np.arange(n)
if density == "half":
return np.arange(0, n, 2)
if density == "topbottom":
return np.array([0, n - 1]) if n > 1 else np.arange(n)
if density == "none":
return np.arange(0)
raise ValueError(density)
def true_tau_at(self, obs: dict, t: np.ndarray) -> np.ndarray:
return invert_warps(obs["t_of_tau_true"], self.tau_fine, t)[0]
def load_horizon_grid(names, cache) -> HorizonGrid:
"""IL×XL grid of the F3 horizons (cached as npz because the ASCII files are large)."""
from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.data.horizons import horizon_path
from ml_porosity.paths import f3_root
geom = SurveyGeometry.from_survey(f3_root())
il0, il1, _ = geom.il_range
xl0, xl1, _ = geom.xl_range
if cache is not None and cache.exists():
z = np.load(cache)
if list(z["names"]) == list(names):
return HorizonGrid(z["h"], il0, xl0, geom)
h = np.full((len(names), il1 - il0 + 1, xl1 - xl0 + 1), np.nan)
for k, nm in enumerate(names):
a = np.loadtxt(horizon_path(nm))
il, xl = geom.xy_to_bin(a[:, 0], a[:, 1])
il, xl = np.rint(il).astype(int), np.rint(xl).astype(int)
ok = (il >= il0) & (il <= il1) & (xl >= xl0) & (xl <= xl1)
h[k, il[ok] - il0, xl[ok] - xl0] = a[ok, 2]
if cache is not None:
cache.parent.mkdir(parents=True, exist_ok=True)
np.savez_compressed(cache, h=h, names=np.array(names))
return HorizonGrid(h, il0, xl0, geom)

View File

@@ -1,4 +1,4 @@
"""Synthetic seismogram và đo lệch thời gian giữa synthetic và seismic.""" """Synthetic seismograms and time-shift measurement between synthetic and seismic."""
from __future__ import annotations from __future__ import annotations
@@ -6,7 +6,7 @@ import numpy as np
def reflectivity_from_ai(ai: np.ndarray) -> np.ndarray: def reflectivity_from_ai(ai: np.ndarray) -> np.ndarray:
"""r[i] = (AI[i+1] − AI[i]) / (AI[i+1] + AI[i]), đặt tại mẫu i; mẫu cuối = 0.""" """r[i] = (AI[i+1] − AI[i]) / (AI[i+1] + AI[i]), placed at sample i; the last sample is 0."""
ai = np.asarray(ai, dtype=float) ai = np.asarray(ai, dtype=float)
r = np.zeros_like(ai) r = np.zeros_like(ai)
r[:-1] = (ai[1:] - ai[:-1]) / (ai[1:] + ai[:-1]) r[:-1] = (ai[1:] - ai[:-1]) / (ai[1:] + ai[:-1])
@@ -14,7 +14,7 @@ def reflectivity_from_ai(ai: np.ndarray) -> np.ndarray:
def shift_signal(x: np.ndarray, shift_ms: float, dt_ms: float) -> np.ndarray: def shift_signal(x: np.ndarray, shift_ms: float, dt_ms: float) -> np.ndarray:
"""Dịch chuỗi theo thời gian (dương = muộn hơn) bằng nội suy tuyến tính; ngoài biên = 0.""" """Time-shift a series (positive = later) by linear interpolation; zero outside the support."""
t = np.arange(len(x)) * dt_ms t = np.arange(len(x)) * dt_ms
return np.interp(t - shift_ms, t, x, left=0.0, right=0.0) return np.interp(t - shift_ms, t, x, left=0.0, right=0.0)
@@ -27,7 +27,7 @@ def ncc(a: np.ndarray, b: np.ndarray) -> float:
def best_shift(syn: np.ndarray, seis: np.ndarray, dt_ms: float, max_ms: float, step_ms: float = 0.5): def best_shift(syn: np.ndarray, seis: np.ndarray, dt_ms: float, max_ms: float, step_ms: float = 0.5):
"""Dịch synthetic trong ±max_ms để cực đại tương quan với seismic. Trả về (shift_ms, r).""" """Shift the synthetic within ±max_ms to maximise its correlation with the seismic. Returns (shift_ms, r)."""
shifts = np.arange(-max_ms, max_ms + step_ms / 2, step_ms) shifts = np.arange(-max_ms, max_ms + step_ms / 2, step_ms)
rs = np.array([ncc(shift_signal(syn, s, dt_ms), seis) for s in shifts]) rs = np.array([ncc(shift_signal(syn, s, dt_ms), seis) for s in shifts])
k = int(np.nanargmax(rs)) k = int(np.nanargmax(rs))
@@ -42,8 +42,8 @@ def local_shifts(
hop_ms: float = 20.0, hop_ms: float = 20.0,
max_ms: float = 16.0, max_ms: float = 16.0,
): ):
"""Lệch thời gian cục bộ trong cửa sổ trượt (taper Hann). Trả về (tâm cửa sổ theo chỉ số """Local time shifts in a sliding window (Hann taper). Returns (window centres as sample
mẫu, shift_ms, r). Dương nghĩa là synthetic cần dịch muộn hơn để khớp seismic.""" indices, shift_ms, r). Positive means the synthetic must be shifted later to match the seismic."""
n = int(round(win_ms / dt_ms)) n = int(round(win_ms / dt_ms))
hop = max(1, int(round(hop_ms / dt_ms))) hop = max(1, int(round(hop_ms / dt_ms)))
taper = np.hanning(n) taper = np.hanning(n)

View File

@@ -1,12 +1,13 @@
"""Quan hệ thời gian–độ sâu (TDR): MD (m, từ KB) ↔ TWT (ms, từ datum seismic). """Time–depth relationship (TDR): MD (m, from KB) ↔ TWT (ms, from the seismic datum).
Ba cách dựng TDR: Three ways of constructing a TDR:
* `legacy_sonic_tdr` – tái hiện cách của luận văn (prepare_data.py:110): tích phân DT * `legacy_sonic_tdr` – reproduces the thesis approach (prepare_data.py:110): integrates DT
với t = 0 tại mẫu LAS đầu tiên, không hiệu chỉnh drift. Chỉ dùng để audit. with t = 0 at the first LAS sample, without drift correction. For auditing only.
* `sonic_tdr` – tích phân DT bắt đầu từ một điểm neo (md0, t0). * `sonic_tdr` – integrates DT starting from an anchor point (md0, t0).
* `calibrate_to_anchors` – hiệu chỉnh drift: co giãn thời gian sonic trong từng khoảng * `calibrate_to_anchors` – drift correction: stretches/squeezes the sonic time within each
giữa hai anchor để đi qua đúng mọi anchor. Vì hệ số co giãn interval between consecutive anchors so that every anchor is honoured
của mỗi khoảng dương, TDR kết quả luôn đơn điệu tăng. exactly. Since each interval's stretch factor is positive, the resulting
TDR is always monotonically increasing.
""" """
from __future__ import annotations from __future__ import annotations
@@ -21,26 +22,26 @@ US_PER_M_TO_S_PER_M = 1e-6
@dataclass(frozen=True) @dataclass(frozen=True)
class TDR: class TDR:
md: np.ndarray # (N,) tăng nghiêm ngặt md: np.ndarray # (N,) strictly increasing
twt_ms: np.ndarray # (N,) tăng nghiêm ngặt twt_ms: np.ndarray # (N,) strictly increasing
name: str = "" name: str = ""
def __post_init__(self): def __post_init__(self):
md = np.asarray(self.md, dtype=float) md = np.asarray(self.md, dtype=float)
t = np.asarray(self.twt_ms, dtype=float) t = np.asarray(self.twt_ms, dtype=float)
if md.shape != t.shape or md.ndim != 1 or md.size < 2: if md.shape != t.shape or md.ndim != 1 or md.size < 2:
raise ValueError("md và twt_ms phải là mảng 1D cùng độ dài ≥ 2") raise ValueError("md and twt_ms must be 1-D arrays of equal length ≥ 2")
if np.any(np.diff(md) <= 0): if np.any(np.diff(md) <= 0):
raise ValueError(f"TDR {self.name!r}: MD không tăng nghiêm ngặt") raise ValueError(f"TDR {self.name!r}: MD is not strictly increasing")
if np.any(np.diff(t) <= 0): if np.any(np.diff(t) <= 0):
raise ValueError(f"TDR {self.name!r}: TWT không tăng nghiêm ngặt") raise ValueError(f"TDR {self.name!r}: TWT is not strictly increasing")
object.__setattr__(self, "md", md) object.__setattr__(self, "md", md)
object.__setattr__(self, "twt_ms", t) object.__setattr__(self, "twt_ms", t)
@classmethod @classmethod
def from_pairs(cls, pairs: np.ndarray, name: str = "", drop_flat: bool = False) -> TDR: def from_pairs(cls, pairs: np.ndarray, name: str = "", drop_flat: bool = False) -> TDR:
"""`drop_flat=True` bỏ các điểm không tăng thời gian so với điểm giữ lại trước đó """`drop_flat=True` drops points whose time does not increase relative to the previously kept point
(ví dụ F02-1.wlt có hai cặp MD khác nhau cùng TWT 700 và 800 ms).""" (e.g. F02-1.wlt contains two pairs with different MD but the same TWT of 700 and 800 ms)."""
pairs = np.asarray(pairs, dtype=float) pairs = np.asarray(pairs, dtype=float)
pairs = pairs[np.argsort(pairs[:, 0], kind="stable")] pairs = pairs[np.argsort(pairs[:, 0], kind="stable")]
if drop_flat: if drop_flat:
@@ -52,14 +53,14 @@ class TDR:
return cls(pairs[:, 0], pairs[:, 1], name) return cls(pairs[:, 0], pairs[:, 1], name)
def time_at(self, md) -> np.ndarray: def time_at(self, md) -> np.ndarray:
"""TWT (ms) tại MD; ngoài phạm vi thì ngoại suy tuyến tính theo khoảng đầu/cuối.""" """TWT (ms) at MD; outside the range, linearly extrapolated from the first/last interval."""
return _interp_extrap(md, self.md, self.twt_ms) return _interp_extrap(md, self.md, self.twt_ms)
def depth_at(self, twt_ms) -> np.ndarray: def depth_at(self, twt_ms) -> np.ndarray:
return _interp_extrap(twt_ms, self.twt_ms, self.md) return _interp_extrap(twt_ms, self.twt_ms, self.md)
def interval_velocity(self) -> np.ndarray: def interval_velocity(self) -> np.ndarray:
"""Vận tốc khoảng (m/s) giữa các nút liên tiếp.""" """Interval velocity (m/s) between consecutive nodes."""
return 2000.0 * np.diff(self.md) / np.diff(self.twt_ms) return 2000.0 * np.diff(self.md) / np.diff(self.twt_ms)
@@ -75,26 +76,26 @@ def _interp_extrap(x, xp, fp) -> np.ndarray:
def fill_nan(a: np.ndarray) -> np.ndarray: def fill_nan(a: np.ndarray) -> np.ndarray:
"""Nội suy tuyến tính chỗ NaN theo chỉ số, giữ giá trị biên ở hai đầu (như luận văn).""" """Linearly interpolate NaNs by index, holding the edge values at both ends (as in the thesis)."""
a = np.asarray(a, dtype=float).copy() a = np.asarray(a, dtype=float).copy()
ok = np.isfinite(a) ok = np.isfinite(a)
if not ok.any(): if not ok.any():
raise ValueError("toàn bộ giá trị là NaN") raise ValueError("all values are NaN")
a[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), a[ok]) a[~ok] = np.interp(np.flatnonzero(~ok), np.flatnonzero(ok), a[ok])
return a return a
def legacy_sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray) -> TDR: def legacy_sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray) -> TDR:
"""TWT = 2·∫DT dz với t = 0 tại mẫu LAS đầu tiên (prepare_data.py:110).""" """TWT = 2·∫DT dz with t = 0 at the first LAS sample (prepare_data.py:110)."""
dt = fill_nan(np.where(np.asarray(dt_us_per_m) < 0, np.nan, dt_us_per_m)) dt = fill_nan(np.where(np.asarray(dt_us_per_m) < 0, np.nan, dt_us_per_m))
owt_s = integrate.cumulative_trapezoid(dt * US_PER_M_TO_S_PER_M, md, initial=0.0) owt_s = integrate.cumulative_trapezoid(dt * US_PER_M_TO_S_PER_M, md, initial=0.0)
return TDR(md, 2000.0 * owt_s, "legacy_sonic") return TDR(md, 2000.0 * owt_s, "legacy_sonic")
def sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray, md0: float, t0_ms: float) -> TDR: def sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray, md0: float, t0_ms: float) -> TDR:
"""Tích phân DT đi qua điểm neo (md0, t0_ms). Chỉ dùng mẫu DT hợp lệ, nên khoảng thiếu """Integrated DT passing through the anchor point (md0, t0_ms). Only valid DT samples are used, so
được tích phân như DT tuyến tính giữa hai đầu; nếu md0 nằm trên mẫu DT đầu tiên thì gaps are integrated as DT varying linearly between their ends; if md0 lies above the first DT
đoạn md0 → mẫu đầu dùng DT của mẫu đầu.""" sample, the segment from md0 to the first sample uses the DT of the first sample."""
md = np.asarray(md, dtype=float) md = np.asarray(md, dtype=float)
dt = np.asarray(dt_us_per_m, dtype=float) dt = np.asarray(dt_us_per_m, dtype=float)
ok = np.isfinite(dt) & (dt > 0) ok = np.isfinite(dt) & (dt > 0)
@@ -108,19 +109,19 @@ def sonic_tdr(md: np.ndarray, dt_us_per_m: np.ndarray, md0: float, t0_ms: float)
def calibrate_to_anchors(base: TDR, anchor_md, anchor_twt_ms, name: str = "calibrated") -> TDR: def calibrate_to_anchors(base: TDR, anchor_md, anchor_twt_ms, name: str = "calibrated") -> TDR:
"""Hiệu chỉnh drift theo khoảng: giữa hai anchor liên tiếp (z_i, t_i), (z_{i+1}, t_{i+1}) """Interval-wise drift correction: between consecutive anchors (z_i, t_i), (z_{i+1}, t_{i+1})
t(z) = t_i + (t_b(z) − t_b(z_i)) · (t_{i+1} − t_i) / (t_b(z_{i+1}) − t_b(z_i)) t(z) = t_i + (t_b(z) − t_b(z_i)) · (t_{i+1} − t_i) / (t_b(z_{i+1}) − t_b(z_i))
với t_b là TDR gốc (sonic). Ngoài phạm vi anchor: dịch đều (bulk) theo anchor gần nhất. where t_b is the base (sonic) TDR. Outside the anchor range: bulk shift to the nearest anchor.
Kết quả đi qua đúng mọi anchor và đơn điệu nếu anchor tăng nghiêm ngặt theo cả z và t. The result honours every anchor exactly and is monotonic if the anchors are strictly increasing in both z and t.
""" """
za = np.asarray(anchor_md, dtype=float) za = np.asarray(anchor_md, dtype=float)
ta = np.asarray(anchor_twt_ms, dtype=float) ta = np.asarray(anchor_twt_ms, dtype=float)
order = np.argsort(za) order = np.argsort(za)
za, ta = za[order], ta[order] za, ta = za[order], ta[order]
if np.any(np.diff(za) <= 0) or np.any(np.diff(ta) <= 0): if np.any(np.diff(za) <= 0) or np.any(np.diff(ta) <= 0):
raise ValueError("anchor phải tăng nghiêm ngặt theo MD và TWT") raise ValueError("anchors must be strictly increasing in MD and TWT")
z = np.union1d(base.md, za) z = np.union1d(base.md, za)
tb = base.time_at(z) tb = base.time_at(z)
@@ -138,5 +139,5 @@ def calibrate_to_anchors(base: TDR, anchor_md, anchor_twt_ms, name: str = "calib
def misfit_at_anchors(tdr: TDR, anchor_md, anchor_twt_ms) -> np.ndarray: def misfit_at_anchors(tdr: TDR, anchor_md, anchor_twt_ms) -> np.ndarray:
"""TWT theo TDR trừ TWT của anchor (ms). Âm nghĩa là TDR sớm hơn anchor.""" """TDR-predicted TWT minus anchor TWT (ms). Negative means the TDR is earlier than the anchor."""
return tdr.time_at(anchor_md) - np.asarray(anchor_twt_ms, dtype=float) return tdr.time_at(anchor_md) - np.asarray(anchor_twt_ms, dtype=float)

View File

@@ -1,8 +1,8 @@
"""Đọc dữ liệu Volve: horizon xuất từ OpenWorks, well picks (cột cố định) và checkshot VSP. """Readers for Volve data: horizons exported from OpenWorks, well picks (fixed-width columns) and VSP checkshots.
Quy ước: MD tính từ RKB (54.9 m trên MSL), TVDSS và TWT tính từ MSL, toạ độ ED50 / UTM 31N. Conventions: MD is measured from RKB (54.9 m above MSL), TVDSS and TWT from MSL; coordinates are ED50 / UTM 31N.
Lưới horizon là lưới ST10010 (12.5 × 12.5 m). Các file ghi ST0202 cũng đánh số IL/XL theo lưới này The horizon grid is the ST10010 grid (12.5 × 12.5 m). Files labelled ST0202 also number IL/XL on this grid
(affine lệch < 0.11 m trong ROI giếng). (affine discrepancy < 0.11 m within the well ROI).
""" """
from __future__ import annotations from __future__ import annotations
@@ -19,7 +19,7 @@ from ml_porosity.data.geometry import SurveyGeometry
VOLVE_RKB_M = 54.9 VOLVE_RKB_M = 54.9
VOLVE_EPSG = 23031 VOLVE_EPSG = 23031
# 9 giếng có PHIF (D3) và F-15 A (không có PHIF nhưng có VSP checkshot), như ROI ở docs/research/volve-inventory.md # The 9 wells with PHIF (D3) plus F-15 A (no PHIF but a VSP checkshot), matching the ROI in docs/research/volve-inventory.md
VOLVE_KEY_WELLS = ("NO 15/9-F-1", "NO 15/9-F-1 A", "NO 15/9-F-1 B", "NO 15/9-F-1 C", "NO 15/9-F-11 A", VOLVE_KEY_WELLS = ("NO 15/9-F-1", "NO 15/9-F-1 A", "NO 15/9-F-1 B", "NO 15/9-F-1 C", "NO 15/9-F-11 A",
"NO 15/9-F-11 B", "NO 15/9-F-11 T2", "NO 15/9-F-12", "NO 15/9-F-15 A", "NO 15/9-F-15 D") "NO 15/9-F-11 B", "NO 15/9-F-11 T2", "NO 15/9-F-12", "NO 15/9-F-15 A", "NO 15/9-F-15 D")
@@ -28,7 +28,7 @@ VOLVE_KEY_WELLS = ("NO 15/9-F-1", "NO 15/9-F-1 A", "NO 15/9-F-1 B", "NO 15/9-F-1
class Horizon: class Horizon:
survey: str survey: str
name: str name: str
domain: str # "TIME" (TWT ms) hoặc "DEPTH" (m) domain: str # "TIME" (TWT ms) or "DEPTH" (m)
il: np.ndarray il: np.ndarray
xl: np.ndarray xl: np.ndarray
x: np.ndarray x: np.ndarray
@@ -43,7 +43,7 @@ class Horizon:
return {(int(i), int(j)): float(v) for i, j, v in zip(self.il, self.xl, self.z)} return {(int(i), int(j)): float(v) for i, j, v in zip(self.il, self.xl, self.z)}
def at(self, il: float, xl: float, radius: int = 1) -> float: def at(self, il: float, xl: float, radius: int = 1) -> float:
"""Trung vị z của các nút trong cửa sổ (2·radius+1)² quanh bin gần nhất; NaN nếu không có nút.""" """Median z of the nodes within the (2·radius+1)² window around the nearest bin; NaN if there are no nodes."""
i0, j0 = int(np.rint(il)), int(np.rint(xl)) i0, j0 = int(np.rint(il)), int(np.rint(xl))
vals = [self.lut[k] for di in range(-radius, radius + 1) for dj in range(-radius, radius + 1) vals = [self.lut[k] for di in range(-radius, radius + 1) for dj in range(-radius, radius + 1)
if (k := (i0 + di, j0 + dj)) in self.lut] if (k := (i0 + di, j0 + dj)) in self.lut]
@@ -51,8 +51,8 @@ class Horizon:
def read_horizon(path: str | Path) -> Horizon: def read_horizon(path: str | Path) -> Horizon:
"""File `*.dat` dạng: các dòng chú thích `#`, 4 dòng metadata (survey, tên, người minh giải, miền), """`*.dat` file layout: `#` comment lines, 4 metadata lines (survey, name, interpreter, domain),
sau đó mỗi dòng `IL,XL,X,Y,Z`. Một số file để trống dòng survey (chỉ có `=`).""" followed by one `IL,XL,X,Y,Z` row per line. Some files leave the survey line empty (only `=`)."""
meta, rows = [], [] meta, rows = [], []
with open(path, errors="replace") as fh: with open(path, errors="replace") as fh:
for line in fh: for line in fh:
@@ -78,7 +78,7 @@ PICK_COLUMNS = {"Well name": "well", "Surface name": "surface", "Obs#": "obs", "
def read_well_picks(path: str | Path) -> pd.DataFrame: def read_well_picks(path: str | Path) -> pd.DataFrame:
"""`Well_picks_Volve_v1.dat`: mỗi giếng có một dòng tiêu đề và một dòng gạch `---` xác định độ rộng cột. """`Well_picks_Volve_v1.dat`: each well has a header line and a `---` dash line that defines the column widths.
Qlf: ER eroded, FP faulted pick, FO faulted out, NL not logged, NR not reached.""" Qlf: ER eroded, FP faulted pick, FO faulted out, NL not logged, NR not reached."""
lines = Path(path).read_text(errors="replace").splitlines() lines = Path(path).read_text(errors="replace").splitlines()
spans, rows = None, [] spans, rows = None, []
@@ -105,8 +105,8 @@ def read_well_picks(path: str | Path) -> pd.DataFrame:
def read_checkshot(path: str | Path) -> pd.DataFrame: def read_checkshot(path: str | Path) -> pd.DataFrame:
"""`TZV_TIME_CHECKSHOT_*.ASC` (3 cột MD, TVD-MSL, TWT ms). F-11 T2 ghi MD từ RKB, F-15 A ghi MD từ MSL """`TZV_TIME_CHECKSHOT_*.ASC` (3 columns: MD, TVD-MSL, TWT ms). F-11 T2 records MD from RKB and F-15 A
(`MDMSL`), nên MD được quy về RKB. Trả về cột md (RKB), tvdss (dương xuống) và twt_ms.""" from MSL (`MDMSL`), so MD is referred to RKB. Returns columns md (RKB), tvdss (positive down) and twt_ms."""
text = Path(path).read_text(errors="replace") text = Path(path).read_text(errors="replace")
rows = [] rows = []
for ln in text.splitlines(): for ln in text.splitlines():

View File

@@ -1,6 +1,6 @@
"""Wavelet: Ricker, wavelet thống kê pha không, xoay pha hằng và ước lượng từ giếng. """Wavelets: Ricker, zero-phase statistical wavelet, constant phase rotation, and well-based estimation.
Mọi wavelet có số mẫu lẻ, tâm ở giữa, bước `dt_ms`. All wavelets have an odd number of samples, are centred, and are sampled at `dt_ms`.
""" """
from __future__ import annotations from __future__ import annotations
@@ -18,15 +18,15 @@ def ricker(f_peak_hz: float, dt_ms: float = 4.0, length_ms: float = 128.0) -> np
def rotate_phase(w: np.ndarray, phase_deg: float) -> np.ndarray: def rotate_phase(w: np.ndarray, phase_deg: float) -> np.ndarray:
"""Xoay pha hằng: w·cos φ − H[w]·sin φ (H: biến đổi Hilbert).""" """Constant phase rotation: w·cos φ − H[w]·sin φ (H: Hilbert transform)."""
h = np.imag(signal.hilbert(w)) h = np.imag(signal.hilbert(w))
p = np.deg2rad(phase_deg) p = np.deg2rad(phase_deg)
return w * np.cos(p) - h * np.sin(p) return w * np.cos(p) - h * np.sin(p)
def statistical_wavelet(traces: np.ndarray, dt_ms: float = 4.0, length_ms: float = 128.0) -> np.ndarray: def statistical_wavelet(traces: np.ndarray, dt_ms: float = 4.0, length_ms: float = 128.0) -> np.ndarray:
"""Wavelet pha không có phổ biên độ bằng trung bình phổ của các trace (taper Hann), """Zero-phase wavelet whose amplitude spectrum equals the mean spectrum of the traces
chuẩn hoá đỉnh = 1.""" (Hann taper), normalised to unit peak."""
traces = np.atleast_2d(traces) traces = np.atleast_2d(traces)
nt = traces.shape[1] nt = traces.shape[1]
nfft = int(2 ** np.ceil(np.log2(4 * nt))) nfft = int(2 ** np.ceil(np.log2(4 * nt)))
@@ -45,10 +45,10 @@ def estimate_wavelet_ls(
length_ms: float = 128.0, length_ms: float = 128.0,
damping: float = 0.05, damping: float = 0.05,
) -> np.ndarray: ) -> np.ndarray:
"""Wavelet (biên độ theo đơn vị seismic) cực tiểu Σ‖s − w∗r‖² + ε‖w‖² trên nhiều giếng. """Wavelet (amplitude in seismic units) minimising Σ‖s − w∗r‖² + ε‖w‖² over multiple wells.
Hệ chuẩn tắc dạng Toeplitz từ tự tương quan của r và tương quan chéo r–s; ε tính tương đối Toeplitz normal equations built from the autocorrelation of r and the r–s cross-correlation;
theo đường chéo. Chuỗi phải hữu hạn và cùng độ dài theo từng cặp.""" ε is relative to the diagonal. Series must be finite and pairwise of equal length."""
n = int(round(length_ms / dt_ms)) // 2 n = int(round(length_ms / dt_ms)) // 2
m = 2 * n + 1 m = 2 * n + 1
R = np.zeros(m) R = np.zeros(m)

View File

@@ -0,0 +1,35 @@
"""Matplotlib style for the P2 figures: reference palette of the dataviz skill (light mode), checked with validate_palette.
- Categorical (≤ 3 groups per figure): blue, orange, aqua — passes all-pairs (CVD ΔE ≥ 9.2); aqua is < 3:1, so always labelled directly.
- Ordinal (drift factor c): a single blue hue, light → dark.
- Diverging (M2/competitor ratio around 1): blue ↔ red, with a neutral grey midpoint.
"""
from __future__ import annotations
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm
SURFACE, INK, INK2, MUTED, GRID, AXIS = "#fcfcfb", "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7"
BLUE, ORANGE, AQUA = "#2a78d6", "#eb6834", "#1baf7a"
ORDINAL_BLUE = ["#86b6ef", "#2a78d6", "#104281"]
GOOD, CRITICAL = "#0ca30c", "#d03b3b"
DIVERGING = LinearSegmentedColormap.from_list(
"blue_gray_red", ["#104281", "#2a78d6", "#86b6ef", "#f0efec", "#ec8a89", "#d23f3e", "#8f2626"])
def diverging_norm(vmin: float, vcenter: float, vmax: float) -> TwoSlopeNorm:
return TwoSlopeNorm(vcenter, vmin, vmax)
def apply() -> None:
mpl.rcParams.update({
"figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE,
"axes.edgecolor": AXIS, "axes.labelcolor": INK2, "axes.titlecolor": INK, "text.color": INK,
"axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.6, "axes.axisbelow": True,
"axes.spines.top": False, "axes.spines.right": False,
"xtick.color": AXIS, "ytick.color": AXIS, "xtick.labelcolor": INK2, "ytick.labelcolor": INK2,
"font.size": 9, "axes.titlesize": 10, "axes.titleweight": "regular", "axes.titlelocation": "left",
"lines.linewidth": 1.5, "lines.markersize": 5, "legend.frameon": False, "legend.fontsize": 8,
"axes.prop_cycle": mpl.cycler(color=[BLUE, ORANGE, AQUA]),
})

View File

@@ -1,4 +1,4 @@
"""Metric điểm cơ bản; bỏ qua mẫu NaN ở cả hai phía.""" """Basic pointwise metrics; samples that are NaN on either side are ignored."""
from __future__ import annotations from __future__ import annotations
@@ -27,7 +27,7 @@ def point_metrics(y_true, y_pred) -> dict[str, float]:
def split_bands(y: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) -> tuple[np.ndarray, np.ndarray]: def split_bands(y: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) -> tuple[np.ndarray, np.ndarray]:
"""Tách chuỗi thành băng thấp (< f_c, Butterworth pha không) và phần còn lại (băng seismic).""" """Split a series into a low band (< f_c, zero-phase Butterworth) and the remainder (seismic band)."""
from scipy import signal from scipy import signal
y = np.asarray(y, dtype=float) y = np.asarray(y, dtype=float)
@@ -46,7 +46,7 @@ def band_metrics(y_true, y_pred, f_c_hz: float = 6.0, dt_ms: float = 4.0) -> dic
def gaussian_metrics(y_true, mu, sigma) -> dict[str, float]: def gaussian_metrics(y_true, mu, sigma) -> dict[str, float]:
"""NLL, CRPS (dạng đóng của Gaussian) và coverage của khoảng trung tâm.""" """NLL, CRPS (Gaussian closed form) and coverage of central intervals."""
from scipy import stats from scipy import stats
y, mu, s = (np.asarray(a, dtype=float) for a in (y_true, mu, sigma)) y, mu, s = (np.asarray(a, dtype=float) for a in (y_true, mu, sigma))

View File

@@ -1,6 +1,6 @@
"""Các loss của luận văn (`test 2/train_open_patch_v2.py`), chuyển nguyên trạng để dựng baseline B0. """Losses from the thesis (`test 2/train_open_patch_v2.py`), ported verbatim to build baseline B0.
Lưu ý (plan mục 1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L nên chỉ có 5 ràng buộc độc lập. Note (plan §1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L, so there are only 5 independent constraints.
""" """
from __future__ import annotations from __future__ import annotations
@@ -37,7 +37,7 @@ def var_match_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
def crosscorr_loss(pred: torch.Tensor, target: torch.Tensor, max_shift: int = 8) -> torch.Tensor: def crosscorr_loss(pred: torch.Tensor, target: torch.Tensor, max_shift: int = 8) -> torch.Tensor:
"""MSE nhỏ nhất trên dải shift [-max_shift, max_shift].""" """Minimum MSE over the shift range [-max_shift, max_shift]."""
x = pred.squeeze(1); y = target.squeeze(1) x = pred.squeeze(1); y = target.squeeze(1)
L = x.shape[1] L = x.shape[1]
losses = [] losses = []

87
ml_porosity/losses/rml.py Normal file
View File

@@ -0,0 +1,87 @@
"""Sub-window losses on the "label bank" (plan §4.4–4.5).
Each training well w has S candidate labels Y_w (S, L) and log-weights log π_w (S). For each sub-window j:
ℓ_wjs = Σ_{i ∈ j} log N(y_ws,i; μ_i, σ_i²)
RML: −(1/(λ n_j)) · log Σ_s π_ws exp(λ ℓ_wjs)
hard-min: −(1/n_j) · max_s ℓ_wjs (λ → ∞, uniform π; B4a)
S = 1 gives the mean Gaussian NLL (B3, point tie). A bank of ±K-sample shifts of a single label with
uniform π gives soft-min/hard-min over bulk shifts (B4b/B4a). The same windowing mechanism is used for all methods.
"""
from __future__ import annotations
import math
import numpy as np
import torch
LOG_2PI = math.log(2 * math.pi)
def window_starts(n_wells: int, L: int, win: int, J: int, margin: int, gen: torch.Generator, device) -> torch.Tensor:
hi = L - win - margin
return torch.randint(margin, hi + 1, (n_wells, J), generator=gen, device="cpu").to(device)
def gather_windows(x: torch.Tensor, starts: torch.Tensor, win: int) -> torch.Tensor:
"""x (B, ..., L), starts (B, J) → (B, J, ..., win)."""
idx = starts[..., None] + torch.arange(win, device=x.device) # (B, J, win)
B = x.shape[0]
mid = x.shape[1:-1]
xe = x.unsqueeze(1).expand(B, idx.shape[1], *mid, x.shape[-1])
ie = idx.view(B, idx.shape[1], *([1] * len(mid)), win).expand(B, idx.shape[1], *mid, win)
return torch.gather(xe, -1, ie)
def window_loglik(mu, sigma, Y, starts, win):
"""mu, sigma (B, L); Y (B, S, L) → ℓ (B, J, S)."""
m = gather_windows(mu, starts, win)[:, :, None, :]
s = gather_windows(sigma, starts, win)[:, :, None, :]
y = gather_windows(Y, starts, win)
return (-torch.log(s) - 0.5 * ((y - m) / s) ** 2 - 0.5 * LOG_2PI).sum(-1)
def bank_loss(mu, sigma, Y, logpi, starts, win: int, lam: float | None):
"""lam = None → hard-min (max ℓ); otherwise RML with power λ."""
ll = window_loglik(mu, sigma, Y, starts, win)
if lam is None:
return -(ll.max(-1).values / win).mean()
v = torch.logsumexp(logpi[:, None, :] + lam * ll, dim=-1)
return -(v / (lam * win)).mean()
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, :]
y = gather_windows(Y, starts, win)
return ((y - m) ** 2).mean()
def shift_bank(y: np.ndarray, max_shift: int) -> np.ndarray:
"""(2K+1, L): y shifted by k samples (label y_{i+k}), NaN outside the boundaries."""
L = len(y)
out = np.full((2 * max_shift + 1, L), np.nan)
for n, k in enumerate(range(-max_shift, max_shift + 1)):
lo, hi = max(0, -k), min(L, L - k)
out[n, lo:hi] = y[lo + k: hi + k]
return out
def effective_lambda(labels: list[np.ndarray], f_c_hz: float = 6.0, dt_ms: float = 4.0, max_lag: int = 32) -> tuple[float, float]:
"""λ = 1/τ_c with τ_c = 1 + 2 Σ_k ρ(k)², where ρ is the pooled ACF of the training labels high-pass filtered
above f_c (a proxy for the residual in the seismic band). Σ runs up to the first lag with ρ ≤ 0 (at most
max_lag). Returns (λ, τ_c)."""
from ml_porosity.eval.metrics import split_bands
acc = np.zeros(max_lag + 1)
for y in labels:
hi = split_bands(np.asarray(y, dtype=float), f_c_hz, dt_ms)[1]
hi = hi - hi.mean()
a = np.correlate(hi, hi, "full")[len(hi) - 1: len(hi) + max_lag]
acc += a
rho = acc / acc[0]
k = np.argmax(rho[1:] <= 0) + 1 if np.any(rho[1:] <= 0) else max_lag + 1
tau_c = 1.0 + 2.0 * float(np.sum(rho[1:k] ** 2))
return 1.0 / tau_c, tau_c

View File

@@ -0,0 +1,175 @@
"""Soft-DTW (Cuturi & Blondel 2017) and DILATE (Le Guen & Thome 2019) for B4c/B4d.
The cost of cell (i, j) is the Gaussian NLL of label j under prediction (μ_i, σ_i); Sakoe–Chiba band constraint
|i − j| ≤ band. The NLL can be negative, so a weighted symmetric step pattern is used (diagonal step ×2,
horizontal/vertical ×1; Sakoe & Chiba 1978): every path from (0, 0) to (n−1, m−1) has total weight n + m, so
shifting the cost by a constant does not bias the choice of path length. The result is divided by n + m. The DP
runs along anti-diagonals, vectorised over the batch, with gradients via autograd.
"""
from __future__ import annotations
import math
import torch
BIG = 1e8
def soft_dtw(D: torch.Tensor, gamma: float, band: int | None = None) -> torch.Tensor:
"""D (B, n, m) → R(n−1, m−1) (B,) with R(i, j) = softmin_γ(R(i−1, j−1) + 2D_ij, R(i−1, j) + D_ij, R(i, j−1) + D_ij),
R(−1, −1) = 0. R is stored per anti-diagonal k = i + j, indexed by i; cells outside the band = BIG."""
B, n, m = D.shape
big = torch.full((B, 1), BIG, device=D.device, dtype=D.dtype)
prev2 = prev1 = torch.full((B, n), BIG, device=D.device, dtype=D.dtype)
for k in range(n + m - 1):
i0, i1 = max(0, k - m + 1), min(k, n - 1)
i = torch.arange(i0, i1 + 1, device=D.device)
d = D[:, i, k - i]
sh2 = torch.cat([torch.zeros_like(big) if k == 0 else big, prev2[:, :-1]], 1) # sh2[:, i] = R(i−1, j−1)
sh1 = torch.cat([big, prev1[:, :-1]], 1) # sh1[:, i] = R(i−1, j)
r = torch.stack([sh2[:, i] + 2 * d, sh1[:, i] + d, prev1[:, i] + d], 0) # prev1[:, i] = R(i, j−1)
val = -gamma * torch.logsumexp(-r / gamma, 0)
if band is not None:
val = torch.where(((2 * i - k).abs() <= band)[None, :], val, torch.full_like(val, BIG))
prev2, prev1 = prev1, torch.cat([big.expand(B, i0), val, big.expand(B, n - 1 - i1)], 1)
return prev1[:, n - 1]
def nll_cost(mu: torch.Tensor, sigma: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""mu, sigma, y (B, n) → D (B, n, n), D_ij = −log N(y_j; μ_i, σ_i²)."""
return torch.log(sigma)[:, :, None] + 0.5 * ((y[:, None, :] - mu[:, :, None]) / sigma[:, :, None]) ** 2 \
+ 0.5 * math.log(2 * math.pi)
def softdtw_loss(mu, sigma, y, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
"""mu, sigma, y (B, n): batch mean of soft-DTW/(2n)."""
n = mu.shape[-1]
return (soft_dtw(nll_cost(mu, sigma, y), gamma, band) / (2 * n)).mean()
def dilate_loss(mu, sigma, y, alpha: float = 0.5, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
"""α·soft-DTW/(2n) + (1 − α)·TDI, TDI = ⟨A*, Ω⟩/(2n), A* = ∂R/∂D (step-weighted expected alignment),
Ω_ij = ((i − j)/n)² penalises temporal distortion (Le Guen & Thome 2019)."""
n = mu.shape[-1]
D = nll_cost(mu, sigma, y)
if not D.requires_grad:
D.requires_grad_(True)
v = soft_dtw(D, gamma, band)
A = torch.autograd.grad(v.sum(), D, create_graph=True)[0]
idx = torch.arange(n, device=mu.device, dtype=mu.dtype)
omega = ((idx[:, None] - idx[None, :]) / n) ** 2
tdi = (A * omega).sum((1, 2))
return ((alpha * v + (1 - alpha) * tdi) / (2 * n)).mean()
# ---------------------------------------------------------------- fast version (numba, analytic gradient)
#
# Same recursion as soft_dtw above. Backward: E(i, j) = ∂R_end/∂R(i, j) = Σ_s E(s)·q_{(i,j)}(s), where q is the
# softmax weight of the predecessor in the softmin of cell s; ∂R_end/∂D_ij = E(i, j)·Σ_p w_p q_p(i, j). DILATE
# additionally needs ∇_D TDI = H·Ω (Hessian–vector product): the directional derivative along Ω of the whole
# forward pass (Ṙ, q̇) and backward pass (Ė) (Mensch & Blondel 2018). Verified against the autograd version in
# tests/test_losses.py.
import numpy as np
from numba import njit, prange
@njit(parallel=True, cache=True)
def _sdtw_nll(mu, sg, y, gamma, band, alpha):
"""For each row b: loss_b = α·R_end + (1 − α)·TDI with D_ij = −log N(y_j; μ_i, σ_i²), Ω_ij = ((i − j)/n)²,
together with ∂loss_b/∂μ, ∂loss_b/∂σ. Only cells inside the band are visited; cells outside have R = big, so
E = 0, G = 0."""
B, n = mu.shape
big = 1e10
bw = band if band >= 0 else 2 * n
hvp = alpha < 1.0
c0 = 0.5 * np.log(2.0 * np.pi)
loss = np.empty(B)
g_mu = np.zeros((B, n))
g_s = np.zeros((B, n))
for b in prange(B):
R = np.full((n + 2, n + 2), big)
Rd = np.zeros((n + 2, n + 2))
Q = np.zeros((n + 2, n + 2, 3))
Qd = np.zeros((n + 2, n + 2, 3))
R[0, 0] = 0.0
for i in range(1, n + 1):
mi = mu[b, i - 1]
si = sg[b, i - 1]
ls = np.log(si)
for j in range(max(1, i - bw), min(n, i + bw) + 1):
r = (y[b, j - 1] - mi) / si
d = ls + 0.5 * r * r + c0
a0 = R[i - 1, j - 1] + 2.0 * d
a1 = R[i - 1, j] + d
a2 = R[i, j - 1] + d
am = min(a0, min(a1, a2))
e0 = np.exp(-(a0 - am) / gamma)
e1 = np.exp(-(a1 - am) / gamma)
e2 = np.exp(-(a2 - am) / gamma)
s = e0 + e1 + e2
R[i, j] = am - gamma * np.log(s)
q0, q1, q2 = e0 / s, e1 / s, e2 / s
Q[i, j, 0], Q[i, j, 1], Q[i, j, 2] = q0, q1, q2
if hvp:
z = ((i - j) / n) ** 2
b0 = Rd[i - 1, j - 1] + 2.0 * z
b1 = Rd[i - 1, j] + z
b2 = Rd[i, j - 1] + z
rd = q0 * b0 + q1 * b1 + q2 * b2
Rd[i, j] = rd
Qd[i, j, 0] = -q0 * (b0 - rd) / gamma
Qd[i, j, 1] = -q1 * (b1 - rd) / gamma
Qd[i, j, 2] = -q2 * (b2 - rd) / gamma
E = np.zeros((n + 2, n + 2))
Ed = np.zeros((n + 2, n + 2))
E[n, n] = 1.0
tdi = 0.0
for i in range(n, 0, -1):
mi = mu[b, i - 1]
si = sg[b, i - 1]
for j in range(min(n, i + bw), max(1, i - bw) - 1, -1):
if i < n or j < n:
E[i, j] = E[i + 1, j + 1] * Q[i + 1, j + 1, 0] + E[i + 1, j] * Q[i + 1, j, 1] + E[i, j + 1] * Q[i, j + 1, 2]
if hvp:
Ed[i, j] = (Ed[i + 1, j + 1] * Q[i + 1, j + 1, 0] + E[i + 1, j + 1] * Qd[i + 1, j + 1, 0]
+ Ed[i + 1, j] * Q[i + 1, j, 1] + E[i + 1, j] * Qd[i + 1, j, 1]
+ Ed[i, j + 1] * Q[i, j + 1, 2] + E[i, j + 1] * Qd[i, j + 1, 2])
c = 2.0 * Q[i, j, 0] + Q[i, j, 1] + Q[i, j, 2]
gd = alpha * E[i, j] * c # ∂loss/∂D_ij
if hvp:
cd = 2.0 * Qd[i, j, 0] + Qd[i, j, 1] + Qd[i, j, 2]
gd += (1.0 - alpha) * (Ed[i, j] * c + E[i, j] * cd)
tdi += E[i, j] * c * ((i - j) / n) ** 2
r = y[b, j - 1] - mi
g_mu[b, i - 1] -= gd * r / (si * si)
g_s[b, i - 1] += gd * (1.0 / si - r * r / (si * si * si))
loss[b] = alpha * R[n, n] + (1.0 - alpha) * tdi
return loss, g_mu, g_s
class _SoftDTWNLL(torch.autograd.Function):
"""Batch mean of [α·R_end + (1 − α)·TDI]/(2n) with NLL cost; computed on the CPU (float64)."""
@staticmethod
def forward(ctx, mu, sigma, y, gamma, band, alpha):
m_, s_, y_ = (t.detach().double().cpu().numpy() for t in (mu, sigma, y))
B, n = m_.shape
loss, g_mu, g_s = _sdtw_nll(m_, s_, y_, float(gamma), -1 if band is None else int(band), float(alpha))
T = lambda a: torch.as_tensor(a, dtype=mu.dtype, device=mu.device)
ctx.save_for_backward(T(g_mu / (2 * n * B)), T(g_s / (2 * n * B)))
return T(loss.mean() / (2 * n))
@staticmethod
def backward(ctx, go):
g_mu, g_s = ctx.saved_tensors
return go * g_mu, go * g_s, None, None, None, None
def softdtw_loss_fast(mu, sigma, y, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
return _SoftDTWNLL.apply(mu, sigma, y, gamma, band, 1.0)
def dilate_loss_fast(mu, sigma, y, alpha: float = 0.5, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
return _SoftDTWNLL.apply(mu, sigma, y, gamma, band, alpha)

View File

@@ -0,0 +1,83 @@
"""Shared training routine for the P2 methods on D2 (plan §4.4–4.5, §5.3).
A single CNNGRUHetero predicts (μ, σ) over the full main window; the loss is computed on fixed 64-sample
sub-windows (starting at 0, 2, …, L − 64), full batch, with the same optimizer for all methods. The methods
differ only in:
- "bank": label bank Y (N, S, L), log π (N, S) and λ (None → hard-min). S = 1 gives the Gaussian NLL (Oracle,
B3a–d); a bank of ±K shifts with uniform π gives B4a/B4b; posterior warp samples give M1/M2.
- "softdtw" / "dilate": soft-DTW / DILATE with a Gaussian NLL cost on each sub-window (B4c/B4d).
- "mse_win": MSE of μ against per-sub-window labels, Ywin (N, J, win) (H1: fixed per-window shift).
Test predictions are taken at the step counts in `budgets` along a single training trajectory (full batch,
deterministic given the seed), which is equivalent to training separately for each budget.
"""
from __future__ import annotations
import numpy as np
import torch
import torch.nn as nn
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.train import CNNGRUHetero, predict
WIN = 64
def window_starts_fixed(L: int, win: int = WIN, step: int = 2) -> np.ndarray:
return np.arange(0, L - win + 1, step)
def zscore_patch(seis: np.ndarray, sel: np.ndarray) -> np.ndarray:
"""Patch (C, n_ext) → (C, L) on the main window, z-scored per channel (as in P1)."""
p = seis[:, sel].astype(np.float64)
return (p - p.mean(1, keepdims=True)) / (p.std(1, keepdims=True) + 1e-8)
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]]:
"""X (N, C, L), Xte (M, C, L); labels in spec are already standardised. Returns {budget: (μ, σ)} for
Xte (M, L), on the standardised scale."""
# 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)
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)
elif kind == "mse_win":
Yw = T(spec["Ywin"])
loss_fn = lambda mu, s: ((gather_windows(mu, starts, WIN) - Yw) ** 2).mean()
else:
raise ValueError(kind)
model = CNNGRUHetero(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])
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

View File

@@ -1,6 +1,6 @@
"""CNN (dilated) + GRU 2 tầng hai chiều + skip head 1×1. """Dilated CNN + 2-layer bidirectional GRU + 1×1 skip head.
Chuyển nguyên trạng từ `test 2/train_open_patch_v2.py` (lớp CNNGRU); không đổi kiến trúc. Ported verbatim from `test 2/train_open_patch_v2.py` (class CNNGRU); the architecture is unchanged.
""" """
from __future__ import annotations from __future__ import annotations

View File

@@ -1,4 +1,4 @@
"""Huấn luyện CNN–GRU cho B2 (loss gốc) và B3 (Gaussian NLL), chọn epoch theo vòng inner.""" """CNN–GRU training for B2 (original loss) and B3 (Gaussian NLL), with epoch selection in the inner loop."""
from __future__ import annotations from __future__ import annotations
@@ -12,7 +12,7 @@ from ml_porosity.models.cnn_gru import CNNGRU
class CNNGRUHetero(nn.Module): class CNNGRUHetero(nn.Module):
"""Backbone CNN–GRU v2 với head 2 kênh: μ và σ = softplus(·) + σ_min.""" """CNN–GRU v2 backbone with a 2-channel head: μ and σ = softplus(·) + σ_min."""
def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05, sigma_min: float = 1e-3): def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05, sigma_min: float = 1e-3):
super().__init__() super().__init__()
@@ -35,7 +35,7 @@ def gaussian_nll(mu, sigma, y):
def train_cnn(Xtr, Ytr, cfg: dict, kind: str, seed: int, epochs: int, device: str, def train_cnn(Xtr, Ytr, cfg: dict, kind: str, seed: int, epochs: int, device: str,
Xva=None, Yva=None, eval_every: int = 25): Xva=None, Yva=None, eval_every: int = 25):
"""kind: "legacy" (B2) hoặc "nll" (B3). Y ở thang đã chuẩn hoá. Trả về (model, [(epoch, val_mse)]).""" """kind: "legacy" (B2) or "nll" (B3). Y is on the standardised scale. Returns (model, [(epoch, val_mse)])."""
torch.manual_seed(seed) torch.manual_seed(seed)
np.random.seed(seed) np.random.seed(seed)
T = lambda a: torch.tensor(a, dtype=torch.float32, device=device) T = lambda a: torch.tensor(a, dtype=torch.float32, device=device)

View File

@@ -1,5 +1,5 @@
"""Đường dẫn dự án. Không có đường dẫn tuyệt đối: mọi thứ tính từ gốc repo """Project paths. No absolute paths: everything is resolved from the repository root
hoặc từ biến môi trường ML_POROSITY_F3_ROOT / ML_POROSITY_VOLVE_ROOT / ML_POROSITY_NLOG_ROOT / ML_POROSITY_OUTPUTS.""" or from the environment variables ML_POROSITY_F3_ROOT / ML_POROSITY_VOLVE_ROOT / ML_POROSITY_NLOG_ROOT / ML_POROSITY_OUTPUTS."""
from __future__ import annotations from __future__ import annotations
@@ -10,7 +10,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
def f3_root() -> Path: def f3_root() -> Path:
"""Thư mục survey F3 (chứa `.survey`).""" """F3 survey directory (containing `.survey`)."""
env = os.environ.get("ML_POROSITY_F3_ROOT") env = os.environ.get("ML_POROSITY_F3_ROOT")
return Path(env) if env else REPO_ROOT / "data" / "F3_Demo_2023" / "F3_Demo_2023" return Path(env) if env else REPO_ROOT / "data" / "F3_Demo_2023" / "F3_Demo_2023"
@@ -24,13 +24,13 @@ def f3_segy() -> Path:
def volve_root() -> Path: def volve_root() -> Path:
"""Thư mục Volve tải từ data village (Geophysical_Interpretations/, Seismic/, ...).""" """Volve directory downloaded from the Data Village (Geophysical_Interpretations/, Seismic/, ...)."""
env = os.environ.get("ML_POROSITY_VOLVE_ROOT") env = os.environ.get("ML_POROSITY_VOLVE_ROOT")
return Path(env) if env else REPO_ROOT / "data" / "Volve" return Path(env) if env else REPO_ROOT / "data" / "Volve"
def nlog_root() -> Path: def nlog_root() -> Path:
"""LAS và TD công khai của NLOG cho các giếng F3 (tải theo docs/research/f3-nlog-inventory.xlsx).""" """Public NLOG LAS and TD files for the F3 wells (downloaded per docs/research/f3-nlog-inventory.xlsx)."""
env = os.environ.get("ML_POROSITY_NLOG_ROOT") env = os.environ.get("ML_POROSITY_NLOG_ROOT")
return Path(env) if env else REPO_ROOT / "data" / "NLOG" return Path(env) if env else REPO_ROOT / "data" / "NLOG"

View File

@@ -0,0 +1,36 @@
"""Labels per warp sample (plan §4.3): y^(s)(t_i) = (𝒜φ)(τ^(s)(t_i)).
Logs live on the uniform fine τ grid (sonic time). 𝒜 is a zero-phase low-pass filter applied before 4 ms
sampling (as in resample.log_to_time); τ^(s) is the inverse map of t(·; u^(s)), which exists because t is
monotone.
"""
from __future__ import annotations
import numpy as np
from scipy import signal
def antialias(y: np.ndarray, d_fine_ms: float, out_dt_ms: float = 4.0, cutoff_frac: float = 0.8,
order: int = 6) -> np.ndarray:
"""Low-pass filter at cutoff_frac·Nyquist of the out_dt_ms grid (default 100 Hz for 4 ms)."""
fc = cutoff_frac * 500.0 / out_dt_ms
sos = signal.butter(order, fc, fs=1000.0 / d_fine_ms, output="sos")
return signal.sosfiltfilt(sos, y, padtype="even")
def invert_warps(t_of_tau: np.ndarray, tau: np.ndarray, t_out: np.ndarray) -> np.ndarray:
"""τ(t_out) for each warp sample; t_of_tau (S, n) strictly increasing on the tau grid. NaN outside the
domain."""
t_of_tau = np.atleast_2d(t_of_tau)
out = np.empty((len(t_of_tau), len(t_out)))
for s, ts in enumerate(t_of_tau):
out[s] = np.interp(t_out, ts, tau, left=np.nan, right=np.nan)
return out
def labels_for_warps(tau_fine: np.ndarray, y_filtered: np.ndarray, t_of_tau_fine: np.ndarray,
t_out: np.ndarray) -> np.ndarray:
"""(S, L): labels at t_out for each warp. y_filtered is the log after `antialias` on tau_fine."""
tau_at = invert_warps(t_of_tau_fine, tau_fine, t_out)
return np.where(np.isfinite(tau_at), np.interp(np.nan_to_num(tau_at), tau_fine, y_filtered), np.nan)

View File

@@ -0,0 +1,122 @@
"""Registration of the training wells of one D2 cell (plan §4.1–4.3, §5.3).
Uses training-well data only: warp hyperparameters (MAP-II on the training anchors), statistical wavelet from the
centre trace + constant phase maximising the marginal likelihood over the posterior warp samples, posterior warp
samples, physical M2 weights, label banks for each method, λ = 1/τ_c, and warp diagnostics against the true warp
(for reporting only, not used for selection).
"""
from __future__ import annotations
import numpy as np
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet
from ml_porosity.losses.rml import effective_lambda
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.sampler import ess, sample_warps, temper
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, phase_loglik, synth_for_warps
from ml_porosity.registration.ties import tie_b3a, tie_b3b, tie_b3c, warp_errors, warp_mean
from ml_porosity.registration.warp_prior import WarpHyper, fit_hyper
def fit_cell_hyper(R, obs: list[dict], reg: dict, seed: int = 0) -> tuple[WarpHyper, dict]:
"""MAP-II for (m_g, σ_g, ℓ); σ_a, σ_b fixed; log-normal hyperprior (median, log sd) for σ_g, ℓ."""
wells = [{"grid": R.grid, "tau_k": o["tau_k"], "d_k": o["t_k"] - o["tau_k"]} for o in obs]
hp = reg["hyperprior"]
init = WarpHyper(0.0, hp["sigma_g"][0], hp["ell_ms"][0], reg["sigma_b_ms"], reg["sigma_a_ms"], reg["kernel"])
return fit_hyper(wells, init, fixed={"sigma_a_ms": reg["sigma_a_ms"], "sigma_b_ms": reg["sigma_b_ms"]},
hyperprior={k: (np.log(m), s) for k, (m, s) in hp.items()}, n_starts=reg["hyper_starts"],
seed=seed)
def label_norm(R, obs: list[dict]) -> tuple[float, float]:
"""Mean/standard deviation of the (anti-aliased) φ log over τ ∈ main window — independent of the tie,
so all methods use the same normalisation."""
m0, m1 = R.cfg["main_window_ms"]
sel = (R.tau_fine >= m0) & (R.tau_fine <= m1)
v = np.concatenate([antialias(o["phi_log"], R.cfg["fine_dt_ms"], R.dt)[sel] for o in obs])
return float(v.mean()), float(v.std())
PHASES = np.arange(-180, 180, 15)
def register(R, obs: list[dict], reg: dict, seed: int, prior: WarpHyper | None = None) -> dict:
"""prior = None: with anchors; returns banks for Oracle, B3a–d, B4 (±K shift bank), M1, M2.
prior given: anchor-free variant (H4) — M1/M2 only, samples from the prior, zero-phase wavelet (the true phase
of D2, i.e. favourable to the anchor-free variant).
banks[m]: (N, S_m, L) labels on t_main; logpi[m]: (N, S_m)."""
f = R.cfg["fine_dt_ms"]
fac = int(round(R.dt / f))
anchors = prior is None
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
w0 = statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"])
out = {"wells": [o["name"] for o in obs], "diag": [], "norm": label_norm(R, obs)}
if anchors:
h, info = fit_cell_hyper(R, obs, reg, seed)
out["hyper_info"] = {k: info[k] for k in ("log_marginal", "at_bound")}
else:
h = prior
out["hyper"] = h.as_dict()
# warp samples, labels and physical log-likelihood per constant phase for every well; one phase per cell
lab = lambda y_aa, T, t=R.t_main: labels_for_warps(R.tau_fine, y_aa, np.atleast_2d(T), t)
w0_fine = fine_wavelet(w0, fac)
T_all, Y_all, ok_all, LL = [], [], [], []
for i, o in enumerate(obs):
rng = np.random.default_rng([seed, i, 11])
tk, ttk = (o["tau_k"], o["t_k"]) if anchors else (np.zeros(0), np.zeros(0))
smp = sample_warps(R.grid, h, tk, ttk, reg["S"], reg["g_max"], rng)
T = R.grid.t_of_tau(smp["b"], smp["g"], tau=R.tau_fine)
Y = lab(antialias(o["phi_log"], f, R.dt), T)
ok = np.all(np.isfinite(Y), 1) # valid domain: keep only warps covering the whole main window
Y[~ok] = Y[ok][0]
T_all.append(T)
Y_all.append(Y)
ok_all.append(ok)
LL.append(phase_loglik(synth_for_warps(R.tau_fine, o["ai_log"], T, R.t_fine, R.t_ext, w0_fine), seis[i], PHASES))
k = fit_phase(LL, ok_all, PHASES) if anchors else int(np.flatnonzero(PHASES == 0)[0])
out["phase"] = float(PHASES[k])
w_fine = fine_wavelet(rotate_phase(w0, PHASES[k]), fac)
K = reg["shift_K"]
t_wide = np.arange(R.t_main[0] - K * R.dt, R.t_main[-1] + K * R.dt + R.dt / 2, R.dt)
L = len(R.t_main)
names = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4", "M1", "M2"] if anchors else ["M1", "M2"]
banks = {m: [] for m in names}
logpi = {"M1": [], "M2": []}
for i, o in enumerate(obs):
T, Y, ok, ll = T_all[i], Y_all[i], ok_all[i], LL[i][k]
tk, ttk = (o["tau_k"], o["t_k"]) if anchors else (np.zeros(0), np.zeros(0))
lp2, gam, ess2 = temper(np.where(ok, ll, -np.inf), reg["ess_min_frac"])
lp1 = np.where(ok, 0.0, -np.inf) - np.log(ok.sum())
d = {"well": o["name"], "n_anchor": int(len(tk)), "n_valid": int(ok.sum()), "gamma": gam,
"ess": ess2, "ess_gamma1": ess(np.where(ok, ll, -np.inf))}
d |= {f"M1_{k_}": v for k_, v in warp_errors(T[ok], R.tau_fine, o["t_of_tau_true"], R.t_main).items()}
d |= {f"M2_{k_}": v for k_, v in warp_errors(T[ok], R.tau_fine, o["t_of_tau_true"], R.t_main, lp2[ok]).items()}
banks["M1"].append(Y)
banks["M2"].append(Y)
logpi["M1"].append(lp1)
logpi["M2"].append(lp2)
if anchors:
y_aa = antialias(o["phi_log"], f, R.dt)
ties = {"Oracle": o["t_of_tau_true"], "B3a": tie_b3a(tk, ttk, R.tau_fine), "B3b": tie_b3b(tk, ttk, R.tau_fine)}
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], ties["B3b"], R.t_fine, R.t_ext, w_fine)[0]
ties["B3c"] = tie_b3c(ties["B3b"], R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
ties["B3d"] = warp_mean(T[ok], lp2[ok])
for m, t in ties.items():
banks[m].append(lab(y_aa, t))
if m != "Oracle":
d[f"{m}_warp_rmse_ms"] = warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
yw = lab(y_aa, ties["B3b"], t_wide)[0]
banks["B4"].append(np.stack([yw[K + j: K + j + L] for j in range(-K, K + 1)]))
out["diag"].append(d)
out["banks"] = {m: np.stack(v).astype(np.float32) for m, v in banks.items()}
out["logpi"] = {m: np.stack(v).astype(np.float32) for m, v in logpi.items()}
if anchors:
ref = [b[0] for b in out["banks"]["B3b"]]
else: # no point tie: M2-weighted mean label as a proxy
ref = [np.exp(lp) @ Yb for lp, Yb in zip(out["logpi"]["M2"], out["banks"]["M2"])]
out["lam"], out["tau_c"] = effective_lambda(ref, dt_ms=R.dt)
return out

View File

@@ -0,0 +1,104 @@
"""Warp posterior sampling: elliptical slice sampling (Murray, Adams & MacKay 2010) around the linearised
Gaussian posterior, plus tempered importance weights and ESS (plan §4.1–4.2, §4.8).
Exact target: p(u | anchor) ∝ N(u; μ0, Σ0) · Π_k N(d_k; b + F(τ_k; g), σ_a²) · 1{|g| ≤ g_max},
where F uses e^g − 1. Rewritten as N(u; μ_lin, Σ_lin) · exp(L(u)), L = exact log-lik − linearised log-lik
(+ constraints), so elliptical slice sampling uses the linearised posterior (Gauss–Newton at the MAP) as the
"prior" and L as the likelihood.
"""
from __future__ import annotations
import numpy as np
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, interp_matrix, laplace_posterior, prior_moments
def _ess_step(f, loglik_f, chol, mu, loglik, rng):
nu = mu + chol @ rng.standard_normal(len(mu))
log_y = loglik_f + np.log(rng.uniform())
th = rng.uniform(0, 2 * np.pi)
lo, hi = th - 2 * np.pi, th
for _ in range(200):
fp = mu + (f - mu) * np.cos(th) + (nu - mu) * np.sin(th)
lp = loglik(fp)
if lp > log_y:
return fp, lp
if th < 0:
lo = th
else:
hi = th
th = rng.uniform(lo, hi)
return f, loglik_f
def elliptical_slice(mu, cov, loglik, n_samples, rng, n_chains=4, burn=40, thin=4, init=None):
"""Elliptical slice sampling with prior N(mu, cov). Returns (n_samples, d). Chains start from init (if given)
or mu."""
chol = np.linalg.cholesky(cov + 1e-9 * np.eye(len(mu)) * max(np.trace(cov) / len(mu), 1e-12))
per = int(np.ceil(n_samples / n_chains))
out = []
for c in range(n_chains):
f = mu.copy() if init is None else init.copy()
lf = loglik(f)
if not np.isfinite(lf):
f, lf = mu.copy(), loglik(mu)
for it in range(burn + per * thin):
f, lf = _ess_step(f, lf, chol, mu, loglik, rng)
if it >= burn and (it - burn) % thin == thin - 1:
out.append(f.copy())
return np.array(out[:n_samples])
def sample_warps(grid: WarpGrid, h: WarpHyper, tau_k, t_k, n_samples: int = 64, g_max: float = 0.15,
rng=None, **kw) -> dict:
"""Samples (b, g) from the warp posterior conditioned on anchors (τ_k, t_k). No anchors ⇒ prior samples
(truncated at g_max). Returns {"u": (S, n+1), "b", "g", "mu_lin", "cov_lin"}."""
rng = rng or np.random.default_rng(0)
tau_k = np.asarray(tau_k, dtype=float)
d_k = np.asarray(t_k, dtype=float) - tau_k
if tau_k.size:
mu, cov, A, off = laplace_posterior(grid, h, tau_k, d_k)
P = interp_matrix(tau_k, grid.tau) @ grid.Q
else:
mu, cov = prior_moments(grid, h)
s2 = h.sigma_a_ms**2
def loglik(u):
g = u[1:]
if np.max(np.abs(g)) > g_max:
return -np.inf
if not tau_k.size:
return 0.0
exact = u[0] + P @ np.expm1(g)
lin = A @ u + off
return float(-0.5 * (np.sum((d_k - exact) ** 2) - np.sum((d_k - lin) ** 2)) / s2)
init = mu.copy()
init[1:] = np.clip(init[1:], -0.9 * g_max, 0.9 * g_max)
u = elliptical_slice(mu, cov, loglik, n_samples, rng, init=init, **kw)
return {"u": u, "b": u[:, 0], "g": u[:, 1:], "mu_lin": mu, "cov_lin": cov}
def ess(logw: np.ndarray) -> float:
w = np.exp(logw - np.max(logw))
return float(w.sum() ** 2 / np.sum(w**2))
def temper(loglik: np.ndarray, min_frac: float = 0.25, tol: float = 1e-3) -> tuple[np.ndarray, float, float]:
"""Weights π_s ∝ p_s^γ with the largest γ ∈ [0, 1] such that ESS ≥ min_frac·S (bisection).
Returns (normalised log π, γ, ESS)."""
ll = np.asarray(loglik, dtype=float)
S = len(ll)
target = min_frac * S
if ess(ll) >= target:
g = 1.0
else:
lo, hi = 0.0, 1.0
while hi - lo > tol:
mid = 0.5 * (lo + hi)
lo, hi = (mid, hi) if ess(mid * ll) >= target else (lo, mid)
g = lo
lw = g * ll
lw = lw - np.logaddexp.reduce(lw)
return lw, g, ess(lw)

View File

@@ -0,0 +1,288 @@
"""Warp posterior conditioned on anchors and seismic via SMC tempering (post-G-B diagnostic, plan §4.2, §9).
protocol_p2 draws S = 64 samples from the anchor posterior and then weights them by π ∝ p(s | u)^γ; the ESS at
γ = 1 collapses to ≈ 1, so the rule ESS ≥ S/4 forces γ down to 0.02–0.11 and the samples carry almost no seismic
information. Here we sample directly from
π_γ(u) ∝ p(u | anchor) · p(s | u)^γ
by SMC tempering (Del Moral, Doucet & Jasra 2006): start from anchor-posterior samples (sampler.sample_warps),
increase γ in adaptive steps that keep ESS ≥ P/2, apply systematic resampling, then move the particles by
elliptical slice sampling with a Gaussian reference q (Gauss–Newton approximation of π_γ around the particle mean,
inflated) and "likelihood" π_γ/q — this leaves π_γ exactly invariant for any q with full support.
Whitened coordinates z: u = μ_lin + L z with Σ_lin = L Lᵀ (linearised anchor posterior), so
log p(u | anchor) = −½‖z‖² + L_a(u) + const, with L_a as in sampler.sample_warps.
γ (power likelihood): −(n/2) log RSS treats the residual as white; band-limited noise and wavelet error make it
over-count information. Matching the curvature to the sandwich variance of the score gives γ = 1/κ,
κ = Σ_{|k| ≤ K} ρ_r(k) ρ_d(k), where ρ_r is the residual ACF and ρ_d is the ACF of the time derivative of the
synthetic (residual_kappa).
Constant wavelet phase (smc_fit_phase): fit_phase in protocol_p2 takes log mean exp ℓ over S anchor-posterior
samples at γ = 1 — essentially a max over a sample that is off by a few ms per well, so the phase compensates for
warp error. Here we maximise Σ_w log Z_w(φ) with Z_w(φ) = ∫ p(u | anchor) p(s_w | u, φ)^{γ_w} du, where log Z_w
is estimated by the SMC itself for each phase on a grid.
"""
from __future__ import annotations
import copy
import numpy as np
from scipy.linalg import solve_triangular
from ml_porosity.data.wavelet import rotate_phase
from ml_porosity.registration.sampler import ess
from ml_porosity.registration.tie_likelihood import fine_wavelet, forward_fine, profile_loglik
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, interp_matrix, laplace_posterior
def residual_kappa(syn: np.ndarray, seis: np.ndarray, max_lag: int = 16) -> float:
"""κ = Σ_{|k| ≤ K} ρ_r(k) ρ_d(k) ≥ 1: score-variance inflation factor under correlated residuals (r = residual
after profiling α ≥ 0, d = time derivative of the synthetic). A white residual gives κ ≈ 1."""
a = max(float(syn @ seis) / max(float(syn @ syn), 1e-30), 0.0)
def acf(x):
x = x - x.mean()
c = np.correlate(x, x, "full")[len(x) - 1: len(x) + max_lag]
return c / c[0]
rr, rd = acf(seis - a * syn), acf(np.gradient(syn))
return max(1.0, 1.0 + 2.0 * float(np.sum(rr[1:] * rd[1:])))
class TiePosterior:
"""π_γ for one well in z coordinates; synthetics are computed for many particles at once.
t(τ) is piecewise linear between warp-grid nodes (as in WarpGrid.t_of_tau with a fine tau), so the inverse map
τ(t) is also piecewise linear and AI as a function of t is obtained exactly by two interpolations; t_fine is
cropped to the seismic window ± half a wavelet (result identical to tie_likelihood.synth_for_warps)."""
def __init__(self, grid: WarpGrid, h: WarpHyper, tau_k, t_k, g_max: float, tau_fine: np.ndarray,
ai_log: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray, seis: np.ndarray,
t_cover: tuple[float, float] | None = None):
tau_k = np.asarray(tau_k, dtype=float)
if tau_k.size == 0:
raise ValueError("anchors required")
self.d_k = np.asarray(t_k, dtype=float) - tau_k
self.mu, cov, self.A, self.off = laplace_posterior(grid, h, tau_k, self.d_k)
jit = 1e-9 * max(np.trace(cov) / len(self.mu), 1e-12) # as in sampler.elliptical_slice
self.Lc = np.linalg.cholesky(cov + jit * np.eye(len(self.mu)))
self.P = interp_matrix(tau_k, grid.tau) @ grid.Q
self.s2a, self.g_max = h.sigma_a_ms**2, g_max
self.tau_g, self.QT = grid.tau, grid.Q.T
self.tau_fine, self.ai_log, self.t_fine = tau_fine, ai_log, t_fine
self.t_out, self.seis = t_out, np.asarray(seis, dtype=float)
self._set_wavelet(w_fine)
self.cover = t_cover
self.n_eval = 0
def _set_wavelet(self, w_fine: np.ndarray) -> None:
self.w_fine = np.asarray(w_fine, dtype=float)
m = (len(self.w_fine) // 2 + 2) * (self.t_fine[1] - self.t_fine[0])
self.t_crop = self.t_fine[(self.t_fine >= self.t_out[0] - m) & (self.t_fine <= self.t_out[-1] + m)]
def with_wavelet(self, w_fine: np.ndarray) -> "TiePosterior":
"""Copy with a different wavelet (keeps the anchor posterior; Laplace is not recomputed)."""
T = copy.copy(self)
T._set_wavelet(w_fine)
T.n_eval = 0
return T
def u(self, Z: np.ndarray) -> np.ndarray:
return self.mu + np.atleast_2d(Z) @ self.Lc.T
def z(self, U: np.ndarray) -> np.ndarray:
return solve_triangular(self.Lc, (np.atleast_2d(U) - self.mu).T, lower=True).T
def t_grid(self, U: np.ndarray) -> np.ndarray:
U = np.atleast_2d(U)
return self.tau_g + U[:, :1] + np.expm1(U[:, 1:]) @ self.QT
def synth(self, U: np.ndarray) -> np.ndarray:
ai = np.stack([np.interp(np.interp(self.t_crop, t, self.tau_g), self.tau_fine, self.ai_log)
for t in self.t_grid(U)])
self.n_eval += len(ai)
return forward_fine(ai, self.t_crop, self.t_out, self.w_fine)
def loglik(self, U: np.ndarray) -> np.ndarray:
return profile_loglik(self.synth(U), self.seis)
def parts(self, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""(log p(u | anchor) + const, ℓ_s(u)) for each row of Z; −inf for particles that violate |g| ≤ g_max or do
not cover t_cover."""
Z = np.atleast_2d(Z)
U = self.u(Z)
g = U[:, 1:]
exact = U[:, :1] + np.expm1(g) @ self.P.T
lin = U @ self.A.T + self.off
la = -0.5 * (np.sum((self.d_k - exact) ** 2, 1) - np.sum((self.d_k - lin) ** 2, 1)) / self.s2a
ok = np.max(np.abs(g), 1) <= self.g_max
if self.cover is not None:
tg = self.t_grid(U)
ok &= (tg[:, 0] <= self.cover[0]) & (tg[:, -1] >= self.cover[1])
ls = np.full(len(Z), -np.inf)
if ok.any():
ls[ok] = self.loglik(U[ok])
return np.where(ok, -0.5 * np.sum(Z**2, 1) + la, -np.inf), ls
def reference(self, m: np.ndarray, gamma: float, infl: float = 2.0, eps: float = 0.05):
"""Gaussian reference q = N(m, Λ⁻¹), Λ = I + γ G / infl, G = α̂² JᵀJ / σ̂² (Gauss–Newton of −ℓ_s at m, J by
finite differences in z). Returns (m, L) with Λ = L Lᵀ. The Cholesky factor is unique and continuous in G, so
samples of q with the same seed do not depend on the basis eigh would pick in a degenerate eigenspace (warp
nodes outside the seismic window give zero columns of J) — the condition for smc_torch to match this version
up to rounding error."""
syn = self.synth(self.u(np.vstack([m, m + eps * np.eye(len(m))])))
s0, J = syn[0], (syn[1:] - syn[0]).T / eps
a = max(float(s0 @ self.seis) / max(float(s0 @ s0), 1e-30), 0.0)
s2 = float(np.sum((self.seis - a * s0) ** 2)) / len(self.seis)
return m, np.linalg.cholesky(np.eye(len(m)) + (gamma / infl) * a**2 * (J.T @ J) / s2)
def systematic_resample(logw: np.ndarray, rng) -> np.ndarray:
w = np.exp(logw - np.max(logw))
c = np.cumsum(w / w.sum())
c[-1] = 1.0
return np.searchsorted(c, (rng.uniform() + np.arange(len(w))) / len(w))
def next_gamma(ll: np.ndarray, g0: float, g1: float, min_frac: float = 0.5, n_iter: int = 50) -> float:
"""Largest γ ∈ (g0, g1] such that the ESS of the incremental weights (γ − g0)·ℓ stays ≥ min_frac·P (bisection)."""
target = min_frac * len(ll)
if ess((g1 - g0) * ll) >= target:
return g1
lo, hi = 0.0, g1 - g0
for _ in range(n_iter):
mid = 0.5 * (lo + hi)
lo, hi = (mid, hi) if ess(mid * ll) >= target else (lo, mid)
return g0 + max(lo, 1e-12)
def ess_moves(T: TiePosterior, Z, base, ll, gamma: float, ref, n_moves: int, rng, max_iter: int = 60):
"""n_moves elliptical slice steps for all particles simultaneously; the "prior" is q = ref, the "likelihood" is
π_γ / q. Returns (Z, base, ll, mean number of shrinkages per step)."""
m, L = ref
logq = lambda X: -0.5 * np.sum(((X - m) @ L) ** 2, 1)
comb = lambda b, l: np.where(np.isfinite(b), b + gamma * l, -np.inf)
Z, base, ll = Z.copy(), base.copy(), ll.copy()
Lq = comb(base, ll) - logq(Z)
P, d = Z.shape
shrink = 0
for _ in range(n_moves):
nu = m + solve_triangular(L, rng.standard_normal((P, d)).T, lower=True, trans="T").T
log_y = Lq + np.log(rng.uniform(size=P))
th = rng.uniform(0.0, 2 * np.pi, P)
lo, hi = th - 2 * np.pi, th.copy()
act = np.arange(P)
for _ in range(max_iter):
if act.size == 0:
break
c, s = np.cos(th[act])[:, None], np.sin(th[act])[:, None]
zp = m + (Z[act] - m) * c + (nu[act] - m) * s
b, l = T.parts(zp)
lq = comb(b, l) - logq(zp)
acc = lq > log_y[act]
i = act[acc]
Z[i], base[i], ll[i], Lq[i] = zp[acc], b[acc], l[acc], lq[acc]
rej = act[~acc]
neg = th[rej] < 0
lo[rej[neg]] = th[rej[neg]]
hi[rej[~neg]] = th[rej[~neg]]
th[rej] = rng.uniform(lo[rej], hi[rej])
shrink += rej.size
act = rej
return Z, base, ll, shrink / (P * n_moves)
def smc_tie_posterior(T: TiePosterior, Z0: np.ndarray, checkpoints, rng, min_frac: float = 0.5,
n_moves: int = 8, infl: float = 2.0, max_stages: int = 500) -> dict:
"""SMC tempering from Z0 (P, d) — anchor-posterior samples in z coordinates (γ = 0) — through increasing γ
checkpoints.
Returns {"Z": {γ: (P, d)}, "ll": {γ: (P,)}, "logZ": {γ: log Ẑ_γ}, "stages": [...]}: at each checkpoint, the
equally weighted particles after the move step and the estimate of log ∫ p(u | anchor) p(s | u)^γ du (product of
the mean incremental weights); stages records γ, the ESS before resampling, the number of distinct particles
after resampling, the mean number of shrinkages, and the RMS jump in z."""
Z = np.atleast_2d(Z0).copy()
base, ll = T.parts(Z)
if not np.all(np.isfinite(base)):
raise ValueError("initial samples violate the constraints")
g, logZ = 0.0, 0.0
out = {"Z": {}, "ll": {}, "logZ": {}, "stages": []}
for gk in sorted(set(float(x) for x in checkpoints)):
while g < gk:
g_new = next_gamma(ll, g, gk, min_frac)
logw = (g_new - g) * ll
logZ += float(np.logaddexp.reduce(logw)) - np.log(len(logw))
idx = systematic_resample(logw, rng)
Z, base, ll = Z[idx], base[idx], ll[idx]
Zb = Z.copy()
Z, base, ll, sh = ess_moves(T, Z, base, ll, g_new, T.reference(Z.mean(0), g_new, infl), n_moves, rng)
out["stages"].append({"gamma": g_new, "ess": ess(logw), "n_unique": int(np.unique(idx).size),
"shrink": sh, "jump_z": float(np.sqrt(np.mean((Z - Zb) ** 2)))})
g = g_new
if len(out["stages"]) >= max_stages:
raise RuntimeError(f"exceeded {max_stages} tempering stages (γ = {g:.4g})")
out["Z"][gk], out["ll"][gk], out["logZ"][gk] = Z.copy(), ll.copy(), logZ
return out
def phase_basis(w0: np.ndarray, factor: int) -> np.ndarray:
"""(2, n_fine): fine wavelet of w0 and of w0 rotated by 90°. rotate_phase(w, φ) = cos φ·w + sin φ·rotate_phase(w,
90°) and fine_wavelet is linear, so the fine wavelet at phase φ is cos φ·B[0] + sin φ·B[1] (exact, not an
approximation)."""
return np.stack([fine_wavelet(w0, factor), fine_wavelet(rotate_phase(w0, 90.0), factor)])
def phase_wavelet(B: np.ndarray, phase_deg: float) -> np.ndarray:
p = np.deg2rad(phase_deg)
return np.cos(p) * B[0] + np.sin(p) * B[1]
def gamma_acf(T: TiePosterior, Z: np.ndarray, ll: np.ndarray) -> float:
"""γ = 1/κ, with κ evaluated at the particle with the largest ℓ_s."""
return 1.0 / residual_kappa(T.synth(T.u(Z[int(np.argmax(ll))]))[0], T.seis)
def smc_fit_phase(Ts: list[TiePosterior], Z0s: list[np.ndarray], B: np.ndarray, phase0: float, seed: list[int],
step: float = 15.0, half_width: int = 3, max_extra: int = 6, run=smc_tie_posterior,
**smc_kw) -> tuple[float, dict]:
"""Common constant phase for the training wells: maximise Σ_w log Z_w(φ),
Z_w(φ) = ∫ p(u | anchor) p(s_w | u, φ)^{γ_w} du.
log Z_w(φ) is taken from the SMC itself (smc_tie_posterior from anchor-posterior samples Z0s[w] up to γ_w; the
same random stream for every φ to reduce the variance of differences). γ_w = 1/κ_w (gamma_acf) is computed once
at phase φ0 so that all φ are compared at the same γ. Grid φ0 + step·k, |k| ≤ half_width; when the argmax lies on
the boundary, one node is added on that side (at most max_extra times); finally refined by a parabola through
the argmax and its two neighbours. Importance sampling from the particles of one phase to another is unusable:
ℓ changes by ~8 nat/5° after tempering, so ESS ≈ 1. Ts may use any wavelet; run is the SMC function (smc_torch
for GPU). Returns (φ̂ ∈ [−180, 180), info)."""
gam = []
for T0, Z0 in zip(Ts, Z0s):
T = T0.with_wavelet(phase_wavelet(B, phase0))
gam.append(gamma_acf(T, Z0, T.parts(Z0)[1]))
lz = {}
def evaluate(phi: float) -> None:
lz[phi] = np.array([run(T0.with_wavelet(phase_wavelet(B, phi)), Z0, [g],
np.random.default_rng([*seed, i]), **smc_kw)["logZ"][g]
for i, (T0, Z0, g) in enumerate(zip(Ts, Z0s, gam))])
for k in range(-half_width, half_width + 1):
evaluate(float(phase0) + step * k)
for _ in range(max_extra):
phis = sorted(lz)
j = int(np.argmax([lz[p].sum() for p in phis]))
if 0 < j < len(phis) - 1:
break
evaluate(phis[j] + (step if j > 0 else -step))
phis = np.array(sorted(lz))
s = np.array([lz[p].sum() for p in phis])
j = int(np.argmax(s))
phi = phis[j]
edge = not 0 < j < len(phis) - 1
if not edge and s[j - 1] - 2 * s[j] + s[j + 1] < 0:
phi += 0.5 * step * (s[j - 1] - s[j + 1]) / (s[j - 1] - 2 * s[j] + s[j + 1])
info = {"gamma": gam, "phases": phis.tolist(), "logZ": [lz[p].tolist() for p in phis], "edge": edge}
return float((phi + 180.0) % 360.0 - 180.0), info

View File

@@ -0,0 +1,301 @@
"""The SMC warp posterior of smc.py on GPU (torch, float64).
Same algorithm and same random stream: all random numbers are still drawn from the numpy Generator in exactly the
order of smc.py (γ and resampling stay on the CPU); synthetics, likelihood, particle π_γ, the Gaussian reference and
the whole elliptical slice shrinkage loop run batched on the device, with no host synchronisation inside each
shrinkage step (ess_moves). With the same seed, results match the CPU version up to rounding error, unless an
accept/reject decision falls exactly within that error — the chain then diverges but keeps the same distribution.
Synthetic: piecewise-linear warp inversion by batched searchsorted, AI interpolation, reflectivity, then the 'same'
convolution and interpolation to t_out are merged into one fixed (n_r, L) matrix per wavelet (conv_interp_matrix).
"""
from __future__ import annotations
import copy
import numpy as np
import torch
from ml_porosity.registration import smc
from ml_porosity.registration.sampler import ess
from ml_porosity.registration.smc import TiePosterior, next_gamma, systematic_resample
F64 = torch.float64
def interp_weights(x: np.ndarray, xp: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""(j, w) with np.interp(x, xp, f) = (1 − w)·f[j] + w·f[j + 1]; clamped at both ends as in np.interp."""
j = np.clip(np.searchsorted(xp, x, side="right") - 1, 0, len(xp) - 2)
return j, np.clip((x - xp[j]) / (xp[j + 1] - xp[j]), 0.0, 1.0)
def conv_interp_matrix(w_fine: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray) -> np.ndarray:
"""M (n_r, L) with tie_likelihood.forward_fine(ai, t_fine, t_out, w_fine) = r(ai) @ M: scipy's 'same'
convolution (the segment starting at (n_w − 1) // 2 of the full convolution), then interpolation from the
midpoints to t_out."""
n_r, n_w = len(t_fine) - 1, len(w_fine)
j, w = interp_weights(t_out, 0.5 * (t_fine[1:] + t_fine[:-1]))
i = np.arange(n_r)[:, None]
def col(jj):
k = jj[None, :] + (n_w - 1) // 2 - i
return np.where((k >= 0) & (k < n_w), w_fine[np.clip(k, 0, n_w - 1)], 0.0)
return (1.0 - w) * col(j) + w * col(j + 1)
def interp_t(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
"""Batched np.interp: x (P, n); xp (P, m) (each row increasing) or (m,); fp (m,)."""
j = (torch.searchsorted(xp, x, right=True) - 1).clamp_(0, xp.shape[-1] - 2)
x0, x1 = (xp[j], xp[j + 1]) if xp.dim() == 1 else (xp.gather(1, j), xp.gather(1, j + 1))
w = ((x - x0) / (x1 - x0)).clamp_(0.0, 1.0)
return fp[j] + w * (fp[j + 1] - fp[j])
def profile_loglik_t(syn: torch.Tensor, seis: torch.Tensor) -> torch.Tensor:
"""tie_likelihood.profile_loglik on tensors."""
a = torch.clamp(syn @ seis / torch.clamp((syn**2).sum(1), min=1e-30), min=0.0)
return -0.5 * len(seis) * torch.log(((seis - a[:, None] * syn) ** 2).sum(1))
class TiePosteriorTorch:
"""TiePosterior with synthetics, likelihood and π_γ computed in batches on `device`. The numpy methods (u, z,
synth, loglik, parts, reference, with_wavelet, n_eval, seis) keep the TiePosterior interface so that
smc.gamma_acf, smc.smc_fit_phase and scripts/14 can be shared; the *_t versions take/return device tensors."""
def __init__(self, T: TiePosterior, device):
self.cpu, self.device = T, torch.device(device)
if self.device.type == "cuda":
torch.cuda.set_device(self.device) # implicit-device operations also go to the right GPU
f = self.tensor
self.mu, self.Lc, self.Pk, self.A, self.off, self.d_k = map(f, (T.mu, T.Lc, T.P, T.A, T.off, T.d_k))
self.tau_g, self.QT, self.tau_fine, self.ai_log = map(f, (T.tau_g, T.QT, T.tau_fine, T.ai_log))
self.seis_t = f(T.seis)
self._set_wavelet()
self._cnt = torch.zeros((), dtype=torch.int64, device=self.device)
def tensor(self, x) -> torch.Tensor:
return torch.as_tensor(np.asarray(x, dtype=float), dtype=F64, device=self.device)
def _set_wavelet(self) -> None:
self.t_crop = self.tensor(self.cpu.t_crop)
self.M = self.tensor(conv_interp_matrix(self.cpu.w_fine, self.cpu.t_crop, self.cpu.t_out))
def with_wavelet(self, w_fine: np.ndarray) -> "TiePosteriorTorch":
T = copy.copy(self)
T.cpu = self.cpu.with_wavelet(w_fine)
T._set_wavelet()
T._cnt = torch.zeros_like(self._cnt)
return T
@property
def seis(self) -> np.ndarray:
return self.cpu.seis
@property
def w_fine(self) -> np.ndarray:
return self.cpu.w_fine
@property
def n_eval(self) -> int:
"""Number of synthetics computed (as in TiePosterior: parts counts only valid particles)."""
return int(self._cnt)
@n_eval.setter
def n_eval(self, v: int) -> None:
self._cnt.fill_(int(v))
def u_t(self, Z: torch.Tensor) -> torch.Tensor:
return self.mu + Z @ self.Lc.T
def _synth_tg(self, tg: torch.Tensor) -> torch.Tensor:
"""(P, L) from t at the warp-grid nodes (P, n_g)."""
tau = interp_t(self.t_crop.expand(len(tg), -1).contiguous(), tg.contiguous(), self.tau_g)
ai = interp_t(tau, self.tau_fine, self.ai_log)
return ((ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])) @ self.M
def synth_t(self, U: torch.Tensor) -> torch.Tensor:
self._cnt += len(U)
return self._synth_tg(self.tau_g + U[:, :1] + torch.expm1(U[:, 1:]) @ self.QT)
def parts_t(self, Z: torch.Tensor, mask: torch.Tensor | None = None) -> tuple[torch.Tensor, torch.Tensor]:
"""TiePosterior.parts on tensors, without host synchronisation. Synthetics are computed for all rows and
violating particles are then masked (cheaper than filtering on the GPU); `mask` (bool, optional) marks the rows
actually needed — only these are counted in n_eval."""
U = self.u_t(Z)
g = U[:, 1:]
eg = torch.expm1(g)
exact = U[:, :1] + eg @ self.Pk.T
lin = U @ self.A.T + self.off
la = -0.5 * (((self.d_k - exact) ** 2).sum(1) - ((self.d_k - lin) ** 2).sum(1)) / self.cpu.s2a
tg = self.tau_g + U[:, :1] + eg @ self.QT
ok = g.abs().amax(1) <= self.cpu.g_max
if self.cpu.cover is not None:
ok &= (tg[:, 0] <= self.cpu.cover[0]) & (tg[:, -1] >= self.cpu.cover[1])
self._cnt += (ok if mask is None else ok & mask).sum()
ls = profile_loglik_t(self._synth_tg(tg), self.seis_t)
return torch.where(ok, -0.5 * (Z**2).sum(1) + la, -np.inf), torch.where(ok, ls, -np.inf)
def reference_t(self, m: torch.Tensor, gamma: float, infl: float = 2.0, eps: float = 0.05):
"""TiePosterior.reference on the device. Returns tensors (m, L)."""
eye = torch.eye(len(m), dtype=F64, device=self.device)
syn = self.synth_t(self.u_t(torch.cat([m[None], m + eps * eye])))
s0, J = syn[0], (syn[1:] - syn[0]).T / eps
a = max(float(s0 @ self.seis_t) / max(float(s0 @ s0), 1e-30), 0.0)
s2 = float(((self.seis_t - a * s0) ** 2).sum()) / len(self.seis_t)
return m, torch.linalg.cholesky(eye + (gamma / infl) * a**2 * (J.T @ J) / s2)
def u(self, Z: np.ndarray) -> np.ndarray:
return self.cpu.u(Z)
def z(self, U: np.ndarray) -> np.ndarray:
return self.cpu.z(U)
def t_grid(self, U: np.ndarray) -> np.ndarray:
return self.cpu.t_grid(U)
def synth(self, U: np.ndarray) -> np.ndarray:
return self.synth_t(self.tensor(np.atleast_2d(U))).cpu().numpy()
def loglik(self, U: np.ndarray) -> np.ndarray:
return profile_loglik_t(self.synth_t(self.tensor(np.atleast_2d(U))), self.seis_t).cpu().numpy()
def parts(self, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
b, ls = self.parts_t(self.tensor(np.atleast_2d(Z)))
return b.cpu().numpy(), ls.cpu().numpy()
def reference(self, m: np.ndarray, gamma: float, infl: float = 2.0, eps: float = 0.05):
return tuple(x.cpu().numpy() for x in self.reference_t(self.tensor(m), gamma, infl, eps))
_LAST_GRAPH: dict = {}
def cuda_graph(fn, device: torch.device):
"""Capture fn() — no arguments, no host synchronisation, only in-place writes into pre-allocated tensors — as a
CUDA graph; returns the replay function. fn is run once beforehand for warm-up (cuBLAS workspace, ...), so that
run must be free of side effects.
All graphs on a device share one stream and the memory pool of the graph captured before them: the pool of a
discarded graph is returned to the device only on empty_cache, so recapturing every SMC stage with a fresh pool
would hold unbounded memory. The previous graph is kept until the new one has been captured (the shared pool must
still have a user, on the host side too) and is never replayed again — sharing a pool is safe only when at most
one graph is still replayed at any time; ess_moves drops its graph when done. capture_begin is called directly
instead of torch.cuda.graph, which empties the memory cache on every capture."""
side, prev = _LAST_GRAPH.get(device) or (torch.cuda.Stream(device), None)
side.wait_stream(torch.cuda.current_stream(device))
graph = torch.cuda.CUDAGraph()
with torch.cuda.stream(side):
fn()
graph.capture_begin(pool=None if prev is None else prev.pool(), capture_error_mode="thread_local")
try:
fn()
finally:
graph.capture_end()
torch.cuda.current_stream(device).wait_stream(side)
_LAST_GRAPH[device] = side, graph
return graph.replay
def ess_moves(T: TiePosteriorTorch, Z, base, ll, gamma: float, ref, n_moves: int, rng, max_iter: int = 60,
check_every: int = 4):
"""smc.ess_moves with Z, base, ll, ref as device tensors, without host synchronisation in the shrinkage loop.
Each shrinkage step evaluates all P particles and masks those already accepted (on the GPU one call costs almost
the same regardless of P), writing in place into fixed state, so on CUDA the whole step is captured as one graph.
Random numbers are still drawn on the CPU in exactly the order of the numpy version: ξ, u, initial angle, then
the shrinkages — uniform(lo, hi) = lo + (hi − lo)·U with U the next number in the stream, so a pool of U(0, 1) is
drawn in advance, the particles rejected at each step take numbers in index order, and the Generator is then
reset and advanced by exactly the number used. The host reads the device only every `check_every` steps to check
whether any particle remains unaccepted."""
m, L = ref
dev = Z.device
logq = lambda X: -0.5 * (((X - m) @ L) ** 2).sum(1)
comb = lambda b, l: torch.where(torch.isfinite(b), b + gamma * l, -np.inf)
Z, base, ll = Z.clone(), base.clone(), ll.clone()
Lq = comb(base, ll) - logq(Z)
P, d = Z.shape
nu = torch.zeros_like(Z)
log_y, th, lo, hi = (torch.zeros_like(ll) for _ in range(4))
pool = torch.zeros(P * max_iter, dtype=F64, device=dev)
act = torch.zeros(P, dtype=torch.bool, device=dev)
used = torch.zeros((), dtype=torch.int64, device=dev)
def step(): # act all False: no change
zp = m + (Z - m) * torch.cos(th)[:, None] + (nu - m) * torch.sin(th)[:, None]
b, l = T.parts_t(zp, act)
lq = comb(b, l) - logq(zp)
up = lq > log_y
acc, rej = act & up, act & ~up
Z.copy_(torch.where(acc[:, None], zp, Z))
for x, y in ((base, b), (ll, l), (Lq, lq)):
x.copy_(torch.where(acc, y, x))
neg = th < 0
lo.copy_(torch.where(rej & neg, th, lo))
hi.copy_(torch.where(rej & ~neg, th, hi))
u = pool[(used + rej.cumsum(0) - 1).clamp_(0, len(pool) - 1)]
th.copy_(torch.where(rej, lo + (hi - lo) * u, th))
used.add_(rej.sum())
act.copy_(rej)
cuda = dev.type == "cuda"
run = cuda_graph(step, dev) if cuda else step
shrink = 0
for _ in range(n_moves):
head = [rng.standard_normal(P * d), np.log(rng.uniform(size=P)), rng.uniform(0.0, 2 * np.pi, P)]
state = rng.bit_generator.state
buf = torch.from_numpy(np.concatenate(head + [rng.random(P * max_iter)]))
buf = (buf.pin_memory() if cuda else buf).to(dev, non_blocking=True)
xi, log_u, th0, pool0 = torch.split(buf, [P * d, P, P, P * max_iter])
nu.copy_(m + torch.linalg.solve_triangular(L.T, xi.view(P, d).T, upper=True).T)
log_y.copy_(Lq + log_u)
for x, y in ((th, th0), (lo, th0 - 2 * np.pi), (hi, th0), (pool, pool0)):
x.copy_(y)
act.fill_(True)
used.zero_()
for it in range(1, max_iter + 1):
run()
if it % check_every == 0 or it == max_iter:
n_act, n_used = torch.stack([act.sum(), used]).tolist()
if n_act == 0:
break
rng.bit_generator.state = state
rng.random(n_used)
shrink += n_used
return Z, base, ll, shrink / (P * n_moves)
def smc_tie_posterior(T: TiePosteriorTorch, Z0: np.ndarray, checkpoints, rng, min_frac: float = 0.5,
n_moves: int = 8, infl: float = 2.0, max_stages: int = 500) -> dict:
"""smc.smc_tie_posterior on the device; numpy in/out as in the CPU version."""
Z = T.tensor(np.atleast_2d(Z0))
base, ll = T.parts_t(Z)
if not bool(torch.isfinite(base).all()):
raise ValueError("initial samples violate the constraints")
g, logZ = 0.0, 0.0
out = {"Z": {}, "ll": {}, "logZ": {}, "stages": []}
for gk in sorted(set(float(x) for x in checkpoints)):
while g < gk:
ll_np = ll.cpu().numpy()
g_new = next_gamma(ll_np, g, gk, min_frac)
logw = (g_new - g) * ll_np
logZ += float(np.logaddexp.reduce(logw)) - np.log(len(logw))
idx = systematic_resample(logw, rng)
idx_t = torch.from_numpy(idx).to(Z.device)
Z, base, ll = Z[idx_t], base[idx_t], ll[idx_t]
Zb = Z.clone()
Z, base, ll, sh = ess_moves(T, Z, base, ll, g_new, T.reference_t(Z.mean(0), g_new, infl), n_moves, rng)
out["stages"].append({"gamma": g_new, "ess": ess(logw), "n_unique": int(np.unique(idx).size),
"shrink": sh, "jump_z": float(torch.sqrt(torch.mean((Z - Zb) ** 2)))})
g = g_new
if len(out["stages"]) >= max_stages:
raise RuntimeError(f"exceeded {max_stages} tempering stages (γ = {g:.4g})")
out["Z"][gk], out["ll"][gk], out["logZ"][gk] = Z.cpu().numpy(), ll.cpu().numpy(), logZ
return out
def smc_fit_phase(Ts: list[TiePosteriorTorch], Z0s: list[np.ndarray], B: np.ndarray, phase0: float, seed: list[int],
**kw) -> tuple[float, dict]:
"""smc.smc_fit_phase with the SMC run on the device."""
return smc.smc_fit_phase(Ts, Z0s, B, phase0, seed, run=smc_tie_posterior, **kw)

View File

@@ -0,0 +1,66 @@
"""Physical well-tie likelihood (plan §4.2): p(s | g) = N(s; α W r(g), σ_n² I).
Forward model shared by the D2 generator and the M2 weights: AI on a fine time axis → reflectivity at the
sample midpoints → convolution with the fine wavelet → interpolation to the 4 ms sample times. α and σ_n² are
profiled out: log p = −(n/2)·log RSS(α̂). Weights π_s ∝ p_s^γ with γ chosen by sampler.temper (ESS ≥ S/4).
Constant wavelet phase: maximum marginal likelihood over the posterior warp samples (fit_phase).
"""
from __future__ import annotations
import numpy as np
from scipy import signal
from ml_porosity.data.wavelet import rotate_phase
def fine_wavelet(w: np.ndarray, factor: int) -> np.ndarray:
"""Band-limited interpolation of the wavelet (odd length, centred) onto a grid `factor` times finer; keeps the
centre."""
wf = signal.resample_poly(w, factor, 1)
n = len(w) // 2
return wf[: 2 * n * factor + 1]
def forward_fine(ai: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray) -> np.ndarray:
"""Synthetic seismic at t_out from AI on the uniform fine time grid t_fine. ai (..., nf) → (..., L)."""
ai = np.atleast_2d(ai)
r = (ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])
s = signal.fftconvolve(r, w_fine[None, :], mode="same", axes=1)
tm = 0.5 * (t_fine[1:] + t_fine[:-1])
return np.stack([np.interp(t_out, tm, si) for si in s])
def synth_for_warps(tau_fine: np.ndarray, ai_log: np.ndarray, t_of_tau_fine: np.ndarray,
t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray) -> np.ndarray:
"""(S, L): synthetic for each warp. The AI log (τ axis) is mapped to the t axis by each warp sample."""
t_of_tau_fine = np.atleast_2d(t_of_tau_fine)
ai_t = np.stack([np.interp(t_fine, ts, ai_log) for ts in t_of_tau_fine])
return forward_fine(ai_t, t_fine, t_out, w_fine)
def profile_loglik(syn: np.ndarray, seis: np.ndarray) -> np.ndarray:
"""log p_s = −(n/2)·log RSS_s after profiling out α_s ≥ 0 (constrained least squares; synthetic and seismic
follow the same polarity convention, so phases φ and φ + 180° no longer give the same likelihood) and σ_n²."""
syn = np.atleast_2d(syn)
a = np.maximum(syn @ seis / np.maximum(np.sum(syn**2, 1), 1e-30), 0.0)
rss = np.sum((seis[None, :] - a[:, None] * syn) ** 2, 1)
return -0.5 * len(seis) * np.log(rss)
def phase_loglik(syn0: np.ndarray, seis: np.ndarray, phases=np.arange(-180, 180, 15)) -> np.ndarray:
"""(P, S): log p_s for each constant phase. syn0 (S, L) is the synthetic with the zero-phase wavelet; phase
rotation commutes with convolution, so only the synthetic needs to be rotated."""
return np.stack([profile_loglik(rotate_phase(np.atleast_2d(syn0), p), seis) for p in phases])
def fit_phase(ll_list: list[np.ndarray], valid_list: list[np.ndarray], phases=np.arange(-180, 180, 15)) -> int:
"""Phase maximising the marginal likelihood Σ_w log mean_s p(s_w | g_ws, φ) over the (anchor) posterior warp
samples of each training well; ll_list[w] (P, S) from phase_loglik. Returns the phase index in `phases`.
Correlation against a single point tie is unusable: a tie error of a few ms already reduces ncc to ~0.1 and
the estimated phase is almost random."""
from scipy.special import logsumexp
score = sum(logsumexp(ll[:, ok], axis=1) - np.log(ok.sum()) for ll, ok in zip(ll_list, valid_list))
return int(np.argmax(score))

View File

@@ -0,0 +1,93 @@
"""Point ties for B3a–d on D2 (plan §5.3) and warp-error diagnostics.
Every tie returns t(τ) on the fine τ grid (strictly increasing), so that `labels_for_warps` can be shared:
- B3a: single-point tie at the shallowest anchor, t = τ + (t_0 − τ_0) — analogous to the thesis's "integrated DT
hung at the first marker" (no drift correction).
- B3b: marker-calibrated sonic (tdr.calibrate_to_anchors) after removing anchors that break monotonicity.
- B3c: B3b + local shifts from synthetic–seismic correlation (synthetic.local_shifts), as in a manual tie.
- B3d: M2-weighted mean warp, Σ_s π_s t_s(τ) (the plan states MAP; the mean is more stable than the MAP over a
finite importance sample — recorded as a deviation in protocol_p2).
"""
from __future__ import annotations
import numpy as np
from ml_porosity.data.synthetic import local_shifts
from ml_porosity.data.tdr import TDR, calibrate_to_anchors
from ml_porosity.registration.labels import invert_warps
def clean_monotone(tau_k, t_k) -> tuple[np.ndarray, np.ndarray]:
"""Longest strictly increasing subsequence of (τ_k, t_k) sorted by τ (pick noise can make t non-monotone)."""
o = np.argsort(tau_k)
tau, t = np.asarray(tau_k, float)[o], np.asarray(t_k, float)[o]
n = len(t)
if n == 0:
return tau, t
best, prev = np.ones(n, int), np.full(n, -1)
for i in range(n):
for j in range(i):
if t[j] < t[i] and tau[j] < tau[i] and best[j] + 1 > best[i]:
best[i], prev[i] = best[j] + 1, j
k, keep = int(np.argmax(best)), []
while k >= 0:
keep.append(k)
k = prev[k]
keep = keep[::-1]
return tau[keep], t[keep]
def tie_b3a(tau_k, t_k, tau: np.ndarray) -> np.ndarray:
k = int(np.argmin(tau_k))
return tau + (t_k[k] - tau_k[k])
def tie_b3b(tau_k, t_k, tau: np.ndarray) -> np.ndarray:
tk, ttk = clean_monotone(tau_k, t_k)
if len(tk) < 2:
return tie_b3a(tk, ttk, tau) if len(tk) else tau.copy()
return calibrate_to_anchors(TDR(tau, tau, "sonic"), tk, ttk).time_at(tau)
def tie_b3c(t_b3b: np.ndarray, tau: np.ndarray, syn: np.ndarray, seis: np.ndarray, t_out: np.ndarray,
dt_ms: float = 4.0, r_min: float = 0.3, smooth: int = 3, **kw) -> np.ndarray:
"""syn: synthetic under the B3b tie on t_out; seis: centre trace on t_out. Shifts s(t) (positive = synthetic
must be later) from windows with r ≥ r_min, smoothed by a moving average over `smooth` windows, then
t(τ) = t_B3b(τ) + s(t_B3b(τ)); strict monotonicity is enforced (dt/dτ ≥ 0.05)."""
c, s, r = local_shifts(syn, seis, dt_ms, **kw)
ok = r >= r_min
if ok.sum() == 0:
return t_b3b.copy()
tc, sc = t_out[c[ok]], s[ok]
if smooth > 1 and len(sc) >= smooth:
sc = np.convolve(np.pad(sc, smooth // 2, mode="edge"), np.ones(smooth) / smooth, "valid")
t = t_b3b + np.interp(t_b3b, tc, sc)
return np.maximum.accumulate(t - 0.05 * tau) + 0.05 * tau
def warp_mean(t_of_tau: np.ndarray, logw: np.ndarray) -> np.ndarray:
w = np.exp(logw - np.max(logw))
return (w / w.sum()) @ np.atleast_2d(t_of_tau)
def warp_errors(t_of_tau: np.ndarray, tau: np.ndarray, t_true_of_tau: np.ndarray, t_eval: np.ndarray,
logw: np.ndarray | None = None) -> dict:
"""Warp error in τ(t) on t_eval (ms). One warp: RMSE. Several warps: RMSE of the weighted mean,
90% coverage (weighted 5–95% quantiles) and mean interval width."""
tau_true = invert_warps(t_true_of_tau, tau, t_eval)[0]
T = invert_warps(t_of_tau, tau, t_eval)
if len(T) == 1:
return {"warp_rmse_ms": float(np.sqrt(np.nanmean((T[0] - tau_true) ** 2)))}
w = np.ones(len(T)) if logw is None else np.exp(logw - np.max(logw))
w = w / w.sum()
mean = w @ T
o = np.argsort(T, 0)
cw = np.cumsum(w[o], 0)
Ts = np.take_along_axis(T, o, 0)
lo = Ts[np.argmax(cw >= 0.05, 0), np.arange(T.shape[1])]
hi = Ts[np.argmax(cw >= 0.95, 0), np.arange(T.shape[1])]
return {"warp_rmse_ms": float(np.sqrt(np.mean((mean - tau_true) ** 2))),
"warp_cov90": float(np.mean((tau_true >= lo) & (tau_true <= hi))),
"warp_width90_ms": float(np.mean(hi - lo))}

View File

@@ -0,0 +1,243 @@
"""GP log-slowness warp prior conditioned on anchors (plan §4.1).
The reference axis τ is sonic time (integrated DT, ms) and t is seismic time (ms):
t(τ) = τ + b + ∫_{τ0}^{τ} (e^{g(τ')} − 1) dτ', g ~ GP(m_g, k_{σ_g, ℓ}), b ~ N(0, σ_b²)
Anchors (markers with TWT): t_k = t(τ_k) + ε_k, ε_k ~ N(0, σ_a²). Writing dt/dτ = e^g is equivalent to the
depth form in the plan (dt/dz = 2·DT·e^g) since dτ/dz = 2·DT. g is defined on a uniform τ grid; the integral is
the trapezoid rule on that grid (the same quadrature for the linearised version e^g − 1 ≈ g and the exact one),
so the difference between the two comes only from the nonlinearity of e^g.
Latent vector u = [b, g_1..g_n]. The linearised Gaussian posterior serves as the proposal for elliptical slice
sampling (sampler.py). Hyperparameters (m_g, σ_g, ℓ, σ_b, σ_a) are fitted by type-II maximum likelihood on the
anchors of the training wells (empirical Bayes).
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
import numpy as np
from scipy import optimize
from scipy.linalg import cho_factor, cho_solve
@dataclass
class WarpHyper:
m_g: float = 0.0
sigma_g: float = 0.03
ell_ms: float = 200.0
sigma_b_ms: float = 30.0
sigma_a_ms: float = 4.0
kernel: str = "matern32"
def scaled(self, c: float) -> WarpHyper:
"""Drift scaled by a factor c (used for the ×c drift grid of D2): g → c·g, b → c·b."""
return WarpHyper(c * self.m_g, c * self.sigma_g, self.ell_ms, c * self.sigma_b_ms, self.sigma_a_ms, self.kernel)
def as_dict(self) -> dict:
return asdict(self)
def kernel_matrix(x: np.ndarray, y: np.ndarray, sigma: float, ell: float, kind: str = "matern32") -> np.ndarray:
r = np.abs(np.asarray(x)[:, None] - np.asarray(y)[None, :]) / ell
if kind == "matern32":
a = np.sqrt(3.0) * r
return sigma**2 * (1.0 + a) * np.exp(-a)
if kind == "se":
return sigma**2 * np.exp(-0.5 * r**2)
raise ValueError(kind)
def cumtrapz_matrix(n: int, dx: float) -> np.ndarray:
"""Q with (Q f)_i = ∫_{x_0}^{x_i} f by the trapezoid rule on a uniform grid."""
Q = np.zeros((n, n))
for i in range(1, n):
Q[i, :i + 1] = dx
Q[i, 0] = Q[i, i] = dx / 2
return Q
def interp_matrix(x: np.ndarray, grid: np.ndarray) -> np.ndarray:
"""P with P f = linear interpolation of f (on grid) at x. x must lie within grid."""
x = np.asarray(x, dtype=float)
P = np.zeros((len(x), len(grid)))
j = np.clip(np.searchsorted(grid, x) - 1, 0, len(grid) - 2)
w = (x - grid[j]) / (grid[j + 1] - grid[j])
P[np.arange(len(x)), j] = 1 - w
P[np.arange(len(x)), j + 1] = w
return P
class WarpGrid:
"""τ grid of one well and the associated linear operators."""
def __init__(self, tau0: float, tau1: float, dtau: float = 4.0):
n = int(np.ceil((tau1 - tau0) / dtau)) + 1
self.tau = tau0 + dtau * np.arange(n)
self.dtau = dtau
self.Q = cumtrapz_matrix(n, dtau)
@property
def n(self) -> int:
return len(self.tau)
def t_of_tau(self, b, g, tau=None) -> np.ndarray:
"""t(τ) for samples (b, g); b scalar or (S,), g (n,) or (S, n). Returns (S, ·) on the grid or
at tau (linear interpolation; tau must lie within the grid)."""
g = np.atleast_2d(g)
t = self.tau[None, :] + np.reshape(b, (-1, 1)) + np.expm1(g) @ self.Q.T
if tau is not None:
t = t @ interp_matrix(tau, self.tau).T
return t
def anchor_operator(self, tau_k: np.ndarray) -> np.ndarray:
"""A with t(τ_k) − τ_k ≈ A u (linearised), u = [b, g]."""
C = interp_matrix(tau_k, self.tau) @ self.Q
return np.hstack([np.ones((len(tau_k), 1)), C])
def prior_moments(grid: WarpGrid, h: WarpHyper) -> tuple[np.ndarray, np.ndarray]:
mu = np.concatenate([[0.0], np.full(grid.n, h.m_g)])
S = np.zeros((grid.n + 1, grid.n + 1))
S[0, 0] = h.sigma_b_ms**2
S[1:, 1:] = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
S[1:, 1:] += 1e-10 * np.eye(grid.n)
return mu, S
def linearize(grid: WarpGrid, tau_k: np.ndarray, g0: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""t(τ_k) − τ_k ≈ A u + off, linearising e^g − 1 at g0. g0 = 0 gives A = anchor_operator, off = 0."""
C = interp_matrix(tau_k, grid.tau) @ grid.Q
e = np.exp(g0)
return np.hstack([np.ones((len(tau_k), 1)), C * e[None, :]]), C @ (e - 1.0 - e * g0)
def linear_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, g0=None) -> tuple[np.ndarray, np.ndarray]:
"""Gaussian posterior of u = [b, g] given d_k = t_k − τ_k ≈ A u + off + ε (linearised at g0,
default 0). Without anchors: returns the prior."""
mu, S = prior_moments(grid, h)
tau_k = np.asarray(tau_k, dtype=float)
if tau_k.size == 0:
return mu, S
A, off = linearize(grid, tau_k, np.zeros(grid.n) if g0 is None else g0)
SA = S @ A.T
G = A @ SA + h.sigma_a_ms**2 * np.eye(len(tau_k))
cf = cho_factor(G)
mu_p = mu + SA @ cho_solve(cf, np.asarray(d_k) - off - A @ mu)
S_p = S - SA @ cho_solve(cf, SA.T)
return mu_p, 0.5 * (S_p + S_p.T)
def laplace_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, n_iter: int = 8, tol: float = 1e-7):
"""Gauss–Newton: iterated linearisation at the posterior mean; converges to the MAP of the exact posterior
(ignoring the g_max constraint). Returns (mu, S, A, off) with A, off the linearisation at mu."""
g0 = np.full(grid.n, h.m_g)
mu, S = linear_posterior(grid, h, tau_k, d_k, g0)
for _ in range(n_iter):
if np.max(np.abs(mu[1:] - g0)) < tol:
break
g0 = mu[1:].copy()
mu, S = linear_posterior(grid, h, tau_k, d_k, g0)
A, off = linearize(grid, np.asarray(tau_k, dtype=float), g0)
return mu, S, A, off
# ---------------------------------------------------------------- type-II maximum likelihood
def _marginal_cov(C: np.ndarray, Kgg: np.ndarray, h: WarpHyper) -> np.ndarray:
n = C.shape[0]
return h.sigma_b_ms**2 * np.ones((n, n)) + C @ Kgg @ C.T + h.sigma_a_ms**2 * np.eye(n)
def log_marginal(wells: list[dict], h: WarpHyper) -> float:
"""Σ_w log N(d_w; C_w m_g 1, σ_b² 11ᵀ + C_w K C_wᵀ + σ_a² I). wells[i] = {"grid", "tau_k", "d_k"}."""
total = 0.0
for w in wells:
grid: WarpGrid = w["grid"]
C = interp_matrix(w["tau_k"], grid.tau) @ grid.Q
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
V = _marginal_cov(C, K, h)
r = np.asarray(w["d_k"]) - h.m_g * C.sum(1)
try:
cf = cho_factor(V)
except np.linalg.LinAlgError:
return -np.inf
total += -0.5 * r @ cho_solve(cf, r) - np.log(np.diag(cf[0])).sum() - 0.5 * len(r) * np.log(2 * np.pi)
return float(total)
_FREE = ("m_g", "sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms")
_LOG = {"sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms"}
def fit_hyper(
wells: list[dict],
init: WarpHyper | None = None,
fixed: dict | None = None,
bounds: dict | None = None,
hyperprior: dict | None = None,
n_starts: int = 8,
seed: int = 0,
) -> tuple[WarpHyper, dict]:
"""Type-II ML (or MAP-II if a hyperprior is given) for the hyperparameters that are not fixed.
hyperprior[name] = (mean, sd) of the parameter on the log scale (σ, ℓ) or the original scale (m_g).
Returns (best hyperparameters, info containing the log-marginal and the starting points)."""
init = init or WarpHyper()
fixed = fixed or {}
hyperprior = hyperprior or {}
bnd = {"m_g": (-0.2, 0.2), "sigma_g": (1e-4, 0.3), "ell_ms": (10.0, 3000.0),
"sigma_b_ms": (0.5, 200.0), "sigma_a_ms": (0.2, 50.0)} | (bounds or {})
free = [k for k in _FREE if k not in fixed]
to_x = lambda k, v: np.log(v) if k in _LOG else v
from_x = lambda k, x: float(np.exp(x)) if k in _LOG else float(x)
lo = np.array([to_x(k, bnd[k][0]) for k in free])
hi = np.array([to_x(k, bnd[k][1]) for k in free])
def make(x):
vals = asdict(init) | fixed | {k: from_x(k, xi) for k, xi in zip(free, x)}
return WarpHyper(**vals)
def obj(x):
h = make(x)
lp = log_marginal(wells, h)
for k, xi in zip(free, x):
if k in hyperprior:
m, s = hyperprior[k]
lp += -0.5 * ((xi - m) / s) ** 2
return -lp if np.isfinite(lp) else 1e12
rng = np.random.default_rng(seed)
x0s = [np.clip([to_x(k, getattr(init, k)) for k in free], lo, hi)]
x0s += [lo + (hi - lo) * rng.uniform(0.15, 0.85, len(free)) for _ in range(n_starts - 1)]
best, starts = None, []
for x0 in x0s:
res = optimize.minimize(obj, x0, method="L-BFGS-B", bounds=list(zip(lo, hi)))
starts.append(float(-res.fun))
if best is None or res.fun < best.fun:
best = res
h = make(best.x)
return h, {"log_marginal": log_marginal(wells, h), "objective": float(-best.fun), "starts": starts,
"free": free, "at_bound": [k for k, xi, a, b in zip(free, best.x, lo, hi) if min(xi - a, b - xi) < 1e-3]}
def loao_zscores(wells: list[dict], h: WarpHyper) -> list[np.ndarray]:
"""Leave-one-anchor-out: z-score of d_k under the (linearised) posterior prediction from the remaining
anchors of the same well (plan §5.4). Returns a list of z arrays, one per well."""
out = []
for w in wells:
grid: WarpGrid = w["grid"]
tk, dk = np.asarray(w["tau_k"]), np.asarray(w["d_k"])
A = grid.anchor_operator(tk)
z = np.empty(len(tk))
for k in range(len(tk)):
keep = np.arange(len(tk)) != k
mu, S = linear_posterior(grid, h, tk[keep], dk[keep])
m = A[k] @ mu
v = A[k] @ S @ A[k] + h.sigma_a_ms**2
z[k] = (dk[k] - m) / np.sqrt(v)
out.append(z)
return out

358
ml_porosity/runlog.py Normal file
View File

@@ -0,0 +1,358 @@
"""Log and runtime recording for every run.
python -m ml_porosity.runlog [-n NAME] [--note "..."] [--] <command> [args...]
python -m ml_porosity.runlog ls [-k 30] # most recent runs + runs in progress
python -m ml_porosity.runlog reindex # rebuild logs/index.csv from the meta.json files
Each run creates `logs/runs/<YYYYmmdd-HHMMSS>_<name>/` (root overridable via ML_POROSITY_LOGS):
log.txt merged stdout + stderr, including child workers (ProcessPool); each line carries the elapsed time [h:mm:ss]
meta.json command, cwd, git commit + dirty state + source hash, thread/GPU variables, device, start/end,
wall/CPU time, peak RSS, peak VRAM of the process tree, exit code; written at start with status=running
and appends one row to `logs/index.csv`. A `.py` file at the head of the command is run with the current python.
For nested calls (RUNLOG_DIR already set, e.g. the individual steps of scripts/run_p2.sh), the child step is placed
inside the parent run's directory, and the `parent` column of the index points to the parent run.
"""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import fcntl
import hashlib
import json
import os
import platform
import re
import resource
import shlex
import signal
import socket
import subprocess
import sys
import threading
import time
from pathlib import Path
from .paths import REPO_ROOT
FIELDS = ["run_id", "parent", "name", "status", "exit_code", "start", "end", "wall_s", "wall",
"device", "git", "dirty", "code_sha", "source", "cmd"]
ENV_KEYS = ["CUDA_VISIBLE_DEVICES", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS",
"PYTHONHASHSEED", "DEVICE", "WORKERS", "ML_POROSITY_OUTPUTS"]
CODE_DIRS = ["ml_porosity", "scripts", "configs", "tests"]
GPU_POLL_S = 15.0
def logs_dir() -> Path:
env = os.environ.get("ML_POROSITY_LOGS")
return Path(env) if env else REPO_ROOT / "logs"
def now() -> dt.datetime:
return dt.datetime.now().astimezone()
def fmt_wall(s: float | None) -> str:
if s is None:
return ""
h, r = divmod(int(round(s)), 3600)
return f"{h}:{r // 60:02d}:{r % 60:02d}"
def _out(cmd: list[str]) -> str:
try:
return subprocess.run(cmd, capture_output=True, text=True, timeout=20, cwd=REPO_ROOT).stdout.strip()
except (OSError, subprocess.SubprocessError):
return ""
def git_state() -> dict:
"""Commit + working-tree state. Since uncommitted code may also be run, a content hash of the files in
CODE_DIRS (tracked + untracked, excluding ignored files) is recorded to identify the exact code version run."""
st = _out(["git", "status", "--porcelain"]).splitlines()
files = sorted(_out(["git", "ls-files", "-co", "--exclude-standard", *CODE_DIRS]).splitlines())
h = hashlib.sha256()
for f in files:
p = REPO_ROOT / f
if p.is_file():
h.update(f.encode() + b"\0" + p.read_bytes() + b"\0")
return {"commit": _out(["git", "rev-parse", "--short=12", "HEAD"]), "branch": _out(["git", "branch", "--show-current"]),
"dirty": any(not s.startswith("??") for s in st), "n_modified": sum(not s.startswith("??") for s in st),
"n_untracked": sum(s.startswith("??") for s in st), "code_sha256": h.hexdigest()[:16] if files else ""}
def gpu_state() -> list[dict]:
rows = _out(["nvidia-smi", "--query-gpu=index,memory.used,memory.total,utilization.gpu",
"--format=csv,noheader,nounits"])
out = []
for r in rows.splitlines():
try:
i, used, tot, util = (int(x) for x in r.split(","))
except ValueError:
continue
out.append({"index": i, "mem_used_mib": used, "mem_total_mib": tot, "util_pct": util})
return out
def _group_pids(pgid: int) -> set[int]:
pids = set()
for d in Path("/proc").iterdir():
if d.name.isdigit():
try:
if os.getpgid(int(d.name)) == pgid:
pids.add(int(d.name))
except OSError:
pass
return pids
class GpuSampler(threading.Thread):
"""Sample the VRAM of the process tree (same process group as the child process) every GPU_POLL_S seconds."""
def __init__(self, pgid: int):
super().__init__(daemon=True)
self.pgid, self.peak, self.stop = pgid, 0, threading.Event()
def run(self) -> None:
wait = 2.0 # early first sample so that short jobs still get a reading
while not self.stop.wait(wait):
wait = GPU_POLL_S
rows = _out(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"])
if not rows:
continue
pids = _group_pids(self.pgid)
tot = 0
for r in rows.splitlines():
try:
pid, mem = (int(x) for x in r.split(","))
except ValueError:
continue
tot += mem if pid in pids else 0
self.peak = max(self.peak, tot)
def default_name(cmd: list[str]) -> str:
for a in cmd:
m = re.search(r"(\d\d_\w+)\.py$", a) or re.search(r"(run_p\d+)\.sh$", a)
if m:
return m.group(1)
if "pytest" in cmd:
return "pytest"
return re.sub(r"\W+", "_", Path(cmd[0]).stem) or "run"
def device_of(cmd: list[str]) -> str:
for i, a in enumerate(cmd):
if a == "--device" and i + 1 < len(cmd):
return cmd[i + 1]
if a.startswith("--device="):
return a.split("=", 1)[1]
return os.environ.get("DEVICE", "")
def write_json(path: Path, obj: dict) -> None:
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str))
tmp.replace(path)
def append_index(row: dict, root: Path | None = None) -> None:
root = root or logs_dir()
root.mkdir(parents=True, exist_ok=True)
with open(root / "index.csv", "a+", newline="") as f:
fcntl.flock(f, fcntl.LOCK_EX) # several concurrent runs may write to the index
f.seek(0)
new = not f.read(1)
w = csv.DictWriter(f, FIELDS, extrasaction="ignore")
if new:
w.writeheader()
w.writerow(row)
fcntl.flock(f, fcntl.LOCK_UN)
def index_row(meta: dict) -> dict:
g = meta.get("git", {})
return {"run_id": meta["run_id"], "parent": meta.get("parent") or "", "name": meta["name"], "status": meta["status"],
"exit_code": "" if meta.get("exit_code") is None else meta["exit_code"], "start": meta.get("start") or "",
"end": meta.get("end") or "", "wall_s": "" if meta.get("wall_s") is None else round(meta["wall_s"], 1),
"wall": fmt_wall(meta.get("wall_s")), "device": meta.get("device", ""), "git": g.get("commit", ""),
"dirty": g.get("dirty", ""), "code_sha": g.get("code_sha256", ""), "source": meta.get("source", "runlog"),
"cmd": " ⏎ ".join(meta["cmd"].splitlines())}
def new_run_dir(name: str, start: dt.datetime) -> tuple[Path, str, str | None]:
parent = os.environ.get("RUNLOG_DIR")
if parent and Path(parent).is_dir():
k = sum(1 for p in Path(parent).iterdir() if p.is_dir()) + 1
while any(Path(parent).glob(f"{k:02d}_*")):
k += 1
d = Path(parent) / f"{k:02d}_{name}"
return d, f"{Path(parent).name}/{d.name}", os.environ.get("RUNLOG_ID")
base = logs_dir() / "runs" / f"{start:%Y%m%d-%H%M%S}_{name}"
d, k = base, 1
while d.exists(): # two runs started in the same second
k += 1
d = base.with_name(f"{base.name}-{k}")
return d, d.name, None
class Tee:
"""Write the child process bytes to the terminal (verbatim) and to log.txt (prefixing each line with [h:mm:ss])."""
def __init__(self, path: Path, t0: float, stamp: bool):
self.f, self.t0, self.stamp, self.bol, self.echo = open(path, "ab"), t0, stamp, True, True
def write(self, b: bytes) -> None:
if self.echo:
try:
sys.stdout.buffer.write(b)
sys.stdout.buffer.flush()
except (BrokenPipeError, ValueError): # terminal/pipe closed: keep writing to log.txt
self.echo = False
if self.stamp:
parts = b.split(b"\n")
out = []
for i, p in enumerate(parts):
if self.bol and (p or i < len(parts) - 1):
out.append(f"[{fmt_wall(time.time() - self.t0)}] ".encode())
self.bol = False
out.append(p)
if i < len(parts) - 1:
out.append(b"\n")
self.bol = True
b = b"".join(out)
self.f.write(b)
self.f.flush()
def note(self, s: str) -> None:
self.f.write(f"# {s}\n".encode())
self.f.flush()
def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
if cmd and cmd[0].endswith(".py"):
cmd = [sys.executable, *cmd]
name = re.sub(r"[^\w.-]+", "_", name or default_name(cmd))
start = now()
rdir, run_id, parent = new_run_dir(name, start)
rdir.mkdir(parents=True)
t0 = time.time()
meta = {"run_id": run_id, "parent": parent, "name": name, "note": note, "status": "running", "exit_code": None,
"cmd": shlex.join(cmd), "argv": cmd, "cwd": os.getcwd(), "start": start.isoformat(timespec="seconds"),
"end": None, "wall_s": None, "device": device_of(cmd), "host": socket.gethostname(),
"user": os.environ.get("USER", ""), "launcher_pid": os.getpid(), "python": platform.python_version(),
"env": {k: os.environ[k] for k in ENV_KEYS if k in os.environ}, "git": git_state(),
"gpu_start": gpu_state(), "source": "runlog"}
write_json(rdir / "meta.json", meta)
tee = Tee(rdir / "log.txt", t0, stamp)
tee.note(f"{run_id} {meta['start']} {meta['cmd']}")
env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1"}
try:
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, process_group=0)
except OSError as e:
tee.note(f"failed to launch: {e}")
child = None
got = []
def forward(sig, _frame): # Ctrl-C / kill: forward to the whole child process group and record it
got.append(signal.Signals(sig).name)
if child is not None:
try:
os.killpg(child.pid, sig)
except OSError:
pass
for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
signal.signal(s, forward)
sampler = None
if child is not None:
sampler = GpuSampler(child.pid)
sampler.start()
fd = child.stdout.fileno()
while True:
try:
b = os.read(fd, 65536)
except InterruptedError:
continue
if not b:
break
tee.write(b)
code = child.wait()
sampler.stop.set()
else:
code = 127
ru = resource.getrusage(resource.RUSAGE_CHILDREN)
wall = time.time() - t0
status = "ok" if code == 0 else ("interrupted" if got or code < 0 else "failed")
meta |= {"status": status, "exit_code": code, "signals": got, "end": now().isoformat(timespec="seconds"),
"wall_s": round(wall, 2), "wall": fmt_wall(wall), "cpu_user_s": round(ru.ru_utime, 1),
"cpu_sys_s": round(ru.ru_stime, 1), "max_rss_mib": round(ru.ru_maxrss / 1024),
"gpu_peak_mib": sampler.peak if sampler else None, "gpu_end": gpu_state()}
write_json(rdir / "meta.json", meta)
tee.note(f"{status} exit {code} wall {fmt_wall(wall)} ({wall:.1f} s)")
append_index(index_row(meta))
print(f"[runlog] {status} exit {code} wall {fmt_wall(wall)} -> {rdir}", file=sys.stderr, flush=True)
return code if code >= 0 else 128 - code
def all_metas(root: Path) -> list[dict]:
metas = [json.loads(m.read_text()) for m in [*(root / "runs").glob("*/meta.json"), *(root / "runs").glob("*/*/meta.json")]]
return sorted(metas, key=lambda m: (m.get("start") or m.get("end") or "", m["run_id"]))
def reindex() -> None:
root = logs_dir()
metas = [m for m in all_metas(root) if m.get("status") != "running"]
(root / "index.csv").unlink(missing_ok=True)
for m in metas:
append_index(index_row(m), root)
print(f"{len(metas)} rows -> {root / 'index.csv'}")
def ls(k: int) -> None:
root = logs_dir()
rows = list(csv.DictReader(open(root / "index.csv"))) if (root / "index.csv").exists() else []
done = {r["run_id"] for r in rows}
for meta in all_metas(root):
if meta["run_id"] in done or meta.get("status") != "running":
continue
alive = Path(f"/proc/{meta.get('launcher_pid')}").exists()
meta["status"] = "running" if alive else "lost" # launcher killed with -9 / machine rebooted
start = dt.datetime.fromisoformat(meta["start"])
meta["wall_s"] = (now() - start).total_seconds() if alive else None
rows.append(index_row(meta))
rows = rows[-k:]
cols = ["run_id", "status", "exit_code", "start", "wall", "device", "cmd"]
w = {c: min(60, max([len(c)] + [len(str(r[c])) for r in rows])) for c in cols}
print(" ".join(c.ljust(w[c]) for c in cols))
for r in rows:
print(" ".join(str(r[c])[:w[c]].ljust(w[c]) for c in cols))
def main(argv: list[str] | None = None) -> int:
argv = sys.argv[1:] if argv is None else argv
if argv[:1] == ["ls"]:
ap = argparse.ArgumentParser(prog="python -m ml_porosity.runlog ls")
ap.add_argument("-k", type=int, default=30)
ls(ap.parse_args(argv[1:]).k)
return 0
if argv == ["reindex"]:
reindex()
return 0
ap = argparse.ArgumentParser(prog="python -m ml_porosity.runlog", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("-n", "--name", help="run name (default: script name, e.g. 11_run_d2)")
ap.add_argument("--note", default="", help="free-text note stored in meta.json")
ap.add_argument("--no-stamp", action="store_true", help="do not prefix log.txt lines with [h:mm:ss]")
ap.add_argument("cmd", nargs=argparse.REMAINDER)
a = ap.parse_args(argv)
cmd = a.cmd[1:] if a.cmd[:1] == ["--"] else a.cmd
if not cmd:
ap.error("missing command to run")
return run(cmd, a.name, a.note, not a.no_stamp)
if __name__ == "__main__":
sys.exit(main())

View File

@@ -26,4 +26,4 @@ include = ["ml_porosity*"]
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["tests"] testpaths = ["tests"]
markers = ["data: cần dữ liệu F3 trên đĩa (tự bỏ qua nếu thiếu)"] markers = ["data: requires F3 data on disk (skipped automatically if missing)"]

View File

@@ -100,7 +100,7 @@ footer{margin-top:32px;color:var(--mute);font-size:12px}
<header> <header>
<div> <div>
<h1>Theo dõi tiến độ ML-Porosity</h1> <h1>Theo dõi tiến độ ML-Porosity</h1>
<div class="sub">Học porosity từ seismic khi well tie không chắc chắn · kế hoạch 24 tuần từ 26/10/2026 · nguồn: <code>docs/plan.md</code></div> <div class="sub">Dự đoán porosity từ seismic khi việc căn chỉnh giếng với seismic (well tie) không chắc chắn · lịch nén: 26/10 đến hết thứ 7, 31/10/2026 · nguồn: <code>docs/plan.md</code></div>
<div class="sub" id="today"></div> <div class="sub" id="today"></div>
</div> </div>
<div class="btns"> <div class="btns">
@@ -127,10 +127,61 @@ footer{margin-top:32px;color:var(--mute);font-size:12px}
<div class="grid2" id="finds"></div> <div class="grid2" id="finds"></div>
<h2>Kết quả P1: baseline LOWO trên F3</h2> <h2>Kết quả P1: baseline LOWO trên F3</h2>
<div class="tw"><table id="p1res"><thead><tr><th>Phương pháp</th><th>RMSE (p.u.)</th><th>PCC</th><th>PCC băng seismic</th><th>Skill vs B0a</th><th>RMSE, tham chiếu .wlt</th></tr></thead><tbody></tbody></table></div> <div class="tw"><table id="p1res"><thead><tr><th>Phương pháp</th><th>RMSE (p.u.)</th><th>PCC</th><th>PCC băng seismic</th><th>Skill so với B0a</th><th>RMSE, tham chiếu .wlt</th></tr></thead><tbody></tbody></table></div>
<div class="card" style="margin-top:12px;font-size:13.5px"> <div class="card" style="margin-top:12px;font-size:13.5px">
<b>Đánh giá cổng G-A (29/11):</b> (1) Baseline tái lập được với 5 seed và có phương sai: <b>đạt</b>. (2) Misregistration còn lại: đã ước lượng nhưng chỉ đến mức ngưỡng nhiễu 8–14 ms; không chứng minh được &lt; 1/8 chu kỳ (≈ 2.5 ms). (3) B3a so với B3b: RMSE +4.2%, PCC −0.055, tức khác nhau theo ngưỡng protocol nhưng sát ngưỡng và nhỏ hơn độ lệch giữa các seed (0.12). Điều kiện pivot sang D2 + D3 (cần cả (2) lẫn B3a ≈ B3b) <b>không thoả</b>, nên theo luật đã khoá thì tiếp tục P2. <b>Cổng G-A (đánh giá 26/10/2026):</b> (1) Baseline tái lập được với 5 seed, có phương sai: <b>đạt</b>. (2) Sai lệch căn chỉnh còn lại: đo được, nhưng chỉ tới ngưỡng nhiễu 8–14 ms, nên không chứng minh được nó nhỏ hơn 1/8 chu kỳ (≈ 2.5 ms). (3) B3a và B3b chênh RMSE +4.2%, PCC −0.055: khác nhau theo ngưỡng protocol, nhưng sát ngưỡng và nhỏ hơn độ lệch giữa các seed (0.12). Muốn chuyển sang D2 + D3 thì cần cả (2) lẫn B3a ≈ B3b; điều kiện này <b>không thoả</b>, nên theo luật đã khoá ta tiếp tục P2.
<br><b>Cảnh báo:</b> không phương pháp nào hơn trend nén chặt, và PCC trong băng seismic ≤ 0.24. Trên F3 gần như không có tín hiệu băng seismic để học, nên H2 sẽ khó thể hiện trên field này (rủi ro R1); sức mạnh của bài phải đến từ D2. Ngày 26/10/2026 bỏ bước chờ GVHD: không pivot, sang P2. <br><b>Cảnh báo:</b> chưa phương pháp nào hơn đường xu hướng nén chặt, và PCC trong băng seismic chỉ ≤ 0.24. F3 gần như không có tín hiệu băng seismic để học, nên khó thể hiện H2 trên field này (rủi ro R1). Sức nặng của bài phải đến từ D2.
</div>
<h2>Kết quả P2: synthetic D2 (lưới chính, protocol_p2)</h2>
<div class="sub" style="margin:-6px 0 10px">Mỗi ô (c, N) gồm 8 realization × 5 seed, chấm trên 8 giếng test. Tỉ số = RMSE băng seismic của M2 chia cho đối thủ tốt nhất trong B3a–B3d, B4a–B4d; CI 95% bootstrap theo realization. Ô đạt khi tỉ số ≤ 0.90 hoặc ΔPCC băng ≥ +0.05, ở ≥ 4/5 seed và quá nửa số realization. Hình: outputs/figures/p2_phase.png, p2_band_lines.png; bảng đầy đủ: outputs/p2/summary/main/summary.md.</div>
<div class="tw"><table id="p2gb"><thead><tr><th>Drift c</th><th>N giếng train</th><th>Đối thủ tốt nhất</th><th>Tỉ số RMSE băng</th><th>CI 95%</th><th>ΔPCC băng</th><th>Seed cải thiện</th><th>Realization cải thiện</th><th>Ô</th></tr></thead><tbody></tbody></table></div>
<div class="tw" style="margin-top:12px"><table id="p2m"><thead><tr><th>Phương pháp</th><th>RMSE băng, c = 0</th><th>c = 0.5</th><th>c = 1</th><th>c = 2</th><th>PCC băng, c = 1</th></tr></thead><tbody></tbody></table></div>
<div class="sub" style="margin-top:6px">Bảng trên: p.u., trung bình theo N ∈ {2, 4, 8, 16}, mỗi N 8 realization × 5 seed. Oracle học với warp thật nên là cận dưới, không phải đối thủ.</div>
<div class="card" style="margin-top:12px;font-size:13.5px" id="p2card">
<b>Cổng G-B (26/10/2026): không đạt.</b> (1) Ở drift thực tế c = 1: <b>0/4 ô đạt</b> (cần ≥ 3/4). Tỉ số M2/B3c là 0.985–1.045 (cần ≤ 0.90), ΔPCC băng từ −0.018 đến +0.003; không ô nào có seed cải thiện đủ ngưỡng. (2) Khi drift = 0, M2 kém B3d <b>3.9%</b> (trung bình theo N; từng N 1.5–5.6%; ngưỡng 2%). CI của tỉ số nằm hẳn trên 1 ở c = 0 (N ≥ 4) và c = 2 (N = 2, 8); không ô nào nằm hẳn dưới 1.
<br><b>So với baseline:</b> M2 thấp hơn B3b (tie theo marker) 12–28% ở c = 1. Nhưng B3c (B3b + dịch cục bộ) và B3d (nhãn warp trung bình của M2), hai đối thủ đã khoá trước khi chạy, cũng đạt mức đó mà không cần marginalize. Tức lợi ích đến từ căn chỉnh tốt hơn, không phải từ RML.
<br><b>H1</b> đứng vững: tỉ số làm mờ đo được/lý thuyết r = 1.01 ở σ = 4–16 ms, 1.09 ở 32 ms (chỉ kiểm được 7–23 Hz). <b>H3</b> bị bác: CE của M2-ens 0.278 so với B5 0.230 (ΔCE +0.048, CI [0.035, 0.061]); khoảng hẹp hơn (0.85×), NLL kém hơn (3.39 so với 3.00), CRPS ngang (0.969 so với 0.974). Coverage 90% của cả hai chỉ 0.46–0.80 vì σ co lại (đã ghi trước khi chạy). <b>H4</b> đứng vững: ở c = 1, N = 4, bỏ anchor làm sai số warp của M2 tăng 9.9× (3.2 → 31 ms) và RMSE băng tăng 1.9× (0.73 → 1.40 p.u.), dù bản không anchor được biết pha thật.
<br><b>Vì sao trượt.</b> (a) Ngưỡng RMSE còn với tới (Oracle thấp hơn B3c 13–21% ở c = 1), ngưỡng PCC +0.05 thì gần như không (Oracle chỉ hơn +0.035 đến +0.042 khi N ≥ 4). (b) Trung bình trên bank có ích khi drift lớn: M2 thấp hơn B3d 3–11% ở c = 1 và 5–14% ở c = 2 (N ≥ 4), nhưng cao hơn 1.5–5.6% ở c = 0. (c) Nút thắt là posterior: bank 64 mẫu chỉ dựa vào anchor, rồi đánh lại trọng số theo độ khớp seismic. Độ khớp quá nhọn (ESS ở γ = 1 chỉ ≈ 1.0–1.2/64), nên luật ESS ≥ S/4 ép γ xuống 0.02–0.11 và M2 bỏ gần hết thông tin seismic (rủi ro R6). Kết quả: sai số warp của M2 (3.2–3.4 ms ở c = 1, 4.1–4.5 ms ở c = 2) không nhỏ hơn B3c (3.0–3.3 và 3.5–3.7 ms). (d) Ở c = 0 bank rộng hơn cần (width90 3.7–4.9 ms, coverage 0.95), nên nhãn trung bình bị mờ hơn nhãn của B3d; vai trò của λ chưa kiểm.
<br><b>Tiếp theo (luật đã khoá):</b> chẩn đoán chỉ trên realization dev, đến hết 27/10/2026 (lịch nén); khoá protocol mới rồi chạy lại trên realization mới; nếu vẫn trượt thì chuyển hướng theo §9. Chi tiết ở việc p2-diag và p2-p2r của pha P2.
</div>
<h2>Chẩn đoán sau G-B: realization dev 900/901</h2>
<div class="sub" style="margin:-6px 0 10px">Chỉ dùng realization dev 900/901, c ∈ {0, 1, 2}, N ∈ {4, 16}; không đụng realization 0–7 của lưới chính hay nhãn test, nên đây chưa phải kết quả đã khoá. Posterior warp (scripts/14, cuda:1): SMC tempering từ 256 mẫu, 8 bước elliptical slice mỗi tầng, giữ ESS ≥ P/2, dừng ở ba mốc γ: γ của M2 cũ, γ_acf = 1/κ (κ từ tự tương quan phần dư) và γ = 1. Pha wavelet được ước lượng lại trên lưới 7 pha, cộng qua các giếng train (pha thật của D2 là 0). Sai số warp = RMSE (ms) của warp trung bình. Coverage và độ rộng 90% gộp theo mẫu thời gian vốn tương quan mạnh, nên không dùng làm claim calibration. Số liệu trung bình theo 2 realization và các giếng train; đầy đủ ở outputs/p2/diag/posterior_gpu/warp.csv.</div>
<div class="tw"><table id="dgpost"><thead><tr><th>Drift c</th><th>N</th><th>|Sai số pha| cũ → mới</th><th>M2 cũ</th><th>B3c</th><th>B3c-R (pha mới)</th><th>SMC γ_acf, pha cũ</th><th>SMC γ_acf, pha mới</th><th>SMC γ = 1, pha mới</th><th>Trần: γ_acf, wavelet thật</th><th>Coverage / độ rộng 90% (ms), γ_acf</th><th>Như trên, γ = 1</th></tr></thead><tbody></tbody></table></div>
<div class="sub" style="margin:12px 0 10px">Huấn luyện (scripts/15, cuda:1): backbone, optimizer, cửa sổ và chuẩn hoá nhãn giữ như protocol_p2. Mỗi ô 2 realization × 2 seed, chấm trên 8 giếng test. B3d-S học một nhãn duy nhất là warp trung bình của mọi hạt SMC; M2-S học trên bank S mẫu lấy ngẫu nhiên từ các hạt, trọng số đều, λ của ô. Số bước huấn luyện chọn theo đúng quy tắc protocol_p2 (RMSE tổng nhỏ nhất ở c = 1, không dùng metric băng). Bảng ghi RMSE băng (p.u.), trung bình theo realization × seed.</div>
<div class="tw"><table id="dgtrain"><thead><tr><th>Phương pháp</th><th>c = 0, N = 4</th><th>c = 0, N = 16</th><th>c = 1, N = 4</th><th>c = 1, N = 16</th><th>c = 2, N = 4</th><th>c = 2, N = 16</th><th>PCC băng, c = 1 (N = 4 / 16)</th></tr></thead><tbody></tbody></table></div>
<div class="sub" style="margin:12px 0 10px">Tính lại gate kiểu G-B trên dev với hai tập đối thủ: "p2" là tập đã khoá trong protocol_p2 (B3a–d, B4a–d); "full" thêm B3c-R và B3d-S dùng cùng posterior với ứng viên. Ô c = 1 đạt khi cả 2 seed và 2 realization cùng cải thiện; điều kiện drift = 0 đạt khi tỉ số ≤ 1.02 ở từng N và trung bình.</div>
<div class="tw"><table id="dggate"><thead><tr><th>Ứng viên</th><th>Tập đối thủ</th><th>Đối thủ tốt nhất, c = 1</th><th>Tỉ số RMSE băng, c = 1 (N = 4 / 16)</th><th>Ô c = 1 đạt</th><th>Tỉ số, drift = 0 (N = 4 / 16)</th><th>Gate</th></tr></thead><tbody></tbody></table></div>
<div class="card" style="margin-top:12px;font-size:13.5px" id="dgcard">
<b>Kết luận (26/10/2026; dev, 2 realization × 2 seed, chưa khoá):</b> P2 trượt vì posterior warp, không phải vì loss RML. Sửa posterior thì nhãn đạt mức Oracle, nhưng lúc đó RML không hơn nhãn warp trung bình lấy từ cùng posterior.
<br><b>(1) Posterior.</b> Sai số warp của M2 cũ: 1.33/0.90 ms (c = 0), 3.40/3.21 ms (c = 1), 5.19/4.87 ms (c = 2), với N = 4/16. SMC với pha mới và γ_acf hạ xuống 0.24/0.20, 0.58/0.56 và 1.98/1.54 ms, ngang trần dùng wavelet thật. B3c, kể cả khi sửa pha (B3c-R), vẫn ở 3.5–4.1 ms. Tách từng bước ở c = 1: chỉ thay bằng SMC mà giữ γ cũ thì giảm ít (3.22/2.84 ms); nâng γ lên γ_acf giảm mạnh (1.32/0.55 ms); sửa pha đưa N = 4 xuống 0.58 ms. Vậy nguyên nhân chính là γ quá nhỏ: M2 cũ chỉ đánh lại trọng số nên luật ESS ép γ xuống (trung vị 0.057), thấp hơn γ_acf (trung vị 0.41) khoảng 7 lần. SMC di chuyển được mẫu nên giữ được γ lớn. Pha cũ lệch 0–22°, ước lượng lại còn 1.4–6.1°. Coverage 90% với γ_acf là 0.90–0.98; với γ = 1 chỉ 0.73–0.86 (quá tự tin).
<br><b>(2) Huấn luyện.</b> Với nhãn từ posterior SMC, RMSE băng ở c = 1 thấp hơn B3c 22–23% (M2-Sa 0.608/0.431 so với 0.779/0.563 p.u.) và ngang Oracle (0.608/0.430). PCC băng 0.888/0.942, so với 0.798/0.897 của B3c và 0.886/0.944 của Oracle. Với tập đối thủ "p2", M2-Sa và M2-S1 đạt gate (2/2 ô c = 1; tỉ số 0.76–0.80); M2 cũ chỉ 1/2 ô và trượt điều kiện drift = 0.
<br><b>(3) Không phải nhờ RML.</b> Khi thêm đối thủ cùng posterior (B3d-S), mọi M2-S đều 0/2 ô: M2-Sa/B3d-Sa = 0.92–1.03, M2-S1/B3d-S1 = 0.97–1.03 trên 6 ô. Khớp Mệnh đề 1: posterior warp đã hẹp (độ rộng 90% chỉ 0.9–2.9 ms ở c ≤ 1, σ ≈ 0.3–0.9 ms), nên hệ số làm mờ exp(−2π²σ²f²) còn ≥ 0.94 ở 60 Hz và trung bình trên bank gần như trùng nhãn warp trung bình. Ở c = 2 posterior rộng hơn (4.7–5.3 ms) và M2-Sa có vẻ tốt hơn (0.920 ở N = 16), nhưng 2 × 2 lần chạy chưa đủ để kết luận.
<br><b>(4) λ.</b> Với posterior SMC, bốn giá trị λ ∈ {1/τ_c, 1, 3, ∞} chênh nhau tối đa 7% trong từng ô. Với bank cũ, λ lớn hơn 1/τ_c làm kém đi ở 16/18 cặp (ô, λ), nặng nhất +36% (c = 0, N = 4, λ = ∞). Chỉ là bằng chứng trên dev.
<br><b>(5) Ổn định Monte Carlo.</b> So bản CPU với lưới GPU: ở c ≤ 1 sai số warp lệch tối đa 0.53 ms. Ở c = 2, 10/240 trường hợp lệch > 1 ms (tối đa 5.7 ms) do posterior nhiều mode, nên P = 256 hạt chưa đủ. Pha ước lượng lại cũng dao động tới ≈ 10° giữa hai lần chạy.
<br><b>Hệ quả.</b> H2 (RML hơn nhãn điểm) không được ủng hộ khi đối thủ dùng cùng posterior. Phần cải thiện đo được đến từ posterior tie (SMC, ước lượng lại pha, γ theo tự tương quan); tie posterior tự nó không mới (Gunning &amp; Glinsky 2006), nên điều cần kiểm là dùng posterior làm nhãn (xem mục P2r). <b>Còn lại đến hết 27/10/2026:</b> lưới stress trên dev (SNR thấp, ít anchor, rock physics sai) để tìm vùng posterior đủ rộng cho RML; học σ_a, σ_b. Cuối ngày chọn một trong hai: khoá protocol_p2r (posterior SMC, thêm đối thủ B3d-S, realization mới 8–15, nhiều hạt hơn) và chạy lại D2 qua đêm trên cuda:1, hoặc Pivot 1.
</div>
<h2>Dev cho P2r (chạy lại P2) và khoá protocol_p2r (27/10/2026)</h2>
<div class="sub" style="margin:-6px 0 10px">Chỉ dùng realization dev 900/901, 5 seed, SMC P = 1024. Protocol: configs/protocol_p2r.yaml (khoá bằng configs/protocol_p2r.sha256 và tag git protocol-p2r). Lưới chính sẽ chạy trên realization mới 8–15. Tổng hợp: outputs/p2/diag/p2rdev/summary.md.</div>
<div class="card" style="font-size:13.5px" id="p2rcard">
<b>H2 tách đôi.</b> <b>H2a</b>: nhãn ở warp trung bình của posterior SMC (B3d-Sa) hơn tie điểm tốt nhất {B3b, B3c, B3c-R}. Dev ở c = 1 (N = 4/16): R10 0.85/0.76 (đạt; drift = 0: 0.85/0.77), R0 0.87/0.89, Rm5 0.94/0.95 (N = 16 cải thiện ở 1/2 realization). Khi tính cả B3d (warp trung bình của M2 cũ), R0/Rm5 không ô nào đạt, nên phần này chuyển thành phân tích phụ. <b>H2b</b>: RML trên bank (M2-Sa) hơn B3d-Sa khi σ_post ≥ 1.5 ms, lợi ích tăng theo σ_post, và khi hẹp thì không kém quá 2%. Dev N = 16: ρ = −0.63 (p = 0.002), 19/19 ô rộng có tỉ số &lt; 1 (trung bình 0.89); ô hẹp trung bình 0.98.
<br><b>Ổn định SMC.</b> Chọn P = 1024, K = 1. c = 1 đạt 4/4 ô ở SNR 10 và 3/4 ở SNR −5; c = 2 gắn cờ "posterior không ổn định".
<br><b>σ_a sai.</b> Với σ_a = 3.5 hoặc 14 ms (dữ liệu sinh với 7 ms), coverage warp chỉ còn 0.45–0.75 và B3d-Sa không còn hơn tie điểm (0/4 ô). Claim H2a vì vậy cần σ_a đúng; lưới chính có thêm nhánh σ_a để đo phạm vi này.
<br><b>H3.</b> Oracle-ens có CE tệ nhất (0.39 so với 0.11 của B5 ở c = 1, N = 16): CE so với B5 thưởng nhiễu nhãn. P2r chỉ báo cáo H3 dạng mô tả và không claim calibration.
<br><b>F3.</b> σ_post 2.5–3.4 ms nếu σ_a = 7 ms (gần Rm5), 0.56–0.64 ms nếu σ_a ≈ 0.4 ms. Vị trí của F3 không chắc chắn, chỉ mô tả.
<br><b>Diễn đạt.</b> Tie posterior đã có (Gunning &amp; Glinsky 2006; Buland &amp; Omre 2003) và SMC chỉ là công cụ. Câu hỏi đang kiểm là dùng posterior làm nhãn huấn luyện.
</div>
<h2>Chốt P2 (27/10/2026)</h2>
<div class="card" style="font-size:13.5px" id="p2close">
<b>P2 đã đóng về thí nghiệm.</b> Kết luận mới về posterior SMC hay RML chỉ lấy từ lưới chính P2r (realization 8–15, chưa chạy). P2r là bản chạy lại P2, không phải pha P3 (F3 thật); bản khoá đầu tên protocol_p3 đã được đổi tên trước khi sinh dữ liệu mới.
<br><b>Kết quả đã khoá, giữ nguyên:</b> G-B không đạt (0/4 ô ở c = 1; drift = 0 kém 3.9%); H1 không bị bác, H3 bị bác, H4 không bị bác. Không chạy thêm trên realization 0–7.
<br><b>Chẩn đoán (dev 900/901):</b> nút thắt là posterior warp, không phải λ. Quyết định cuối 27/10: khoá protocol_p2r thay vì Pivot 1.
<br><b>Lệch so với luật đã khoá:</b> luật trượt của protocol_p2 ghi "chẩn đoán rồi pivot"; phương án chạy lại được thêm sau khi G-B trượt. P2r vì vậy là pre-registration mới, thiết kế sau khi thấy P2 trượt (chỉ dựa trên dev); kết luận G-B của P2 giữ nguyên và phải nêu trong phần Methods.
<br><b>Chưa kiểm:</b> σ_b (chưa học, chưa stress); σ_a chỉ stress, bản học trên F3 không đáng tin; stress rock physics sai bị cắt theo thứ tự cắt phạm vi (plan §6). Chẩn đoán chỉ có 2 realization nên chỉ dùng để thiết kế.
<br><b>Với pha P3 (F3, G-C):</b> chiều cải thiện trên synthetic lấy từ P2r. Điều kiện coverage 80/90% trong ±5% nhiều khả năng trượt; ngưỡng không nới.
</div> </div>
<h2>Kiểm chứng P0: số liệu trong plan tái tạo từ code</h2> <h2>Kiểm chứng P0: số liệu trong plan tái tạo từ code</h2>
@@ -144,177 +195,270 @@ footer{margin-top:32px;color:var(--mute);font-size:12px}
<footer> <footer>
Trạng thái công việc lưu trong trình duyệt (localStorage) của bạn; sửa dữ liệu gốc trong khối <code>DATA</code> ở cuối file này. Trạng thái công việc lưu trong trình duyệt (localStorage) của bạn; sửa dữ liệu gốc trong khối <code>DATA</code> ở cuối file này.
Các bảng [XM], quyết định, phát hiện và dữ liệu là bản chụp từ ngày ghi trong nhật ký, không tự cập nhật theo <code>plan.md</code>. Các bảng [XM], quyết định, phát hiện và dữ liệu là bản chụp tại ngày ghi trong nhật ký, không tự cập nhật theo <code>plan.md</code>.
</footer> </footer>
</div> </div>
<script> <script>
/* ===================== DATA (sửa ở đây) ===================== */ /* ===================== DATA (sửa ở đây) ===================== */
const START = "2026-10-26", END = "2027-05-02"; const START = "2026-10-26", END = "2026-10-31"; // END tính cả ngày; mục tiêu: xong bài trước thứ 7 31/10/2026
const STATES = {todo:"Chưa làm", doing:"Đang làm", done:"Xong", blocked:"Bị chặn"}; const STATES = {todo:"Chưa làm", doing:"Đang làm", done:"Xong", blocked:"Bị chặn"};
const PHASES = [ const PHASES = [
{id:"P0", name:"P0 Hạ tầng", start:"2026-10-26", end:"2026-11-08", weeks:"Tuần 1–2", {id:"P0", name:"P0 Hạ tầng", start:"2026-10-26", end:"2026-10-26", weeks:"T2 26/10",
out:"Pipeline chạy end-to-end; manifest dữ liệu", gate:null, out:"pipeline chạy thông từ đầu đến cuối; manifest dữ liệu", gate:null,
tasks:[ tasks:[
{id:"p0-git", t:"git init, .gitignore loại dữ liệu và outputs/", s:"done", n:"26/10: .gitignore chỉ track .survey, WellInfo/, dữ liệu giếng và fault dạng text của F3; bỏ qua phần còn lại của bản 9.43 GB, *.zip, *.egg-info. Chưa commit."}, {id:"p0-git", t:"Khởi tạo git, .gitignore loại dữ liệu và outputs/", s:"done", n:"Git chỉ theo dõi các file nhỏ dạng text của F3 (.survey, WellInfo/, dữ liệu giếng, fault). Bỏ qua phần dữ liệu lớn (9.43 GB), file *.zip và *.egg-info. Đã commit cùng P0 + P1."},
{id:"p0-hash", t:"Ghi hash dữ liệu theo manifest", s:"done", n:"data_manifest/f3_demo_2023.json: SHA-256 của 279 file (9.43 GB). 101/101 hash trong cleanup-manifest.json cũ khớp. Kiểm lại bằng scripts/00_data_manifest.py --check."}, {id:"p0-hash", t:"Ghi mã băm của dữ liệu theo manifest", s:"done", n:"Mỗi file có một mã SHA-256 như dấu vân tay; file bị đổi thì mã đổi theo. Đã ghi cho 279 file F3 (9.43 GB) ở data_manifest/f3_demo_2023.json; 101/101 mã của manifest cũ khớp. Kiểm lại bằng scripts/00_data_manifest.py --check."},
{id:"p0-f3", t:"Tải F3 Demo 2023 đầy đủ (segy, horizon)", s:"done", n:"26/10: 9.43 GB, 104 file đã lọc khớp byte-by-byte."}, {id:"p0-f3", t:"Tải bản F3 Demo 2023 đầy đủ (seismic, horizon)", s:"done", n:"26/10: 9.43 GB; 104 file của bản lọc cũ trùng từng byte."},
{id:"p0-out", t:"Lấy outputs/ của luận văn từ iCloud", s:"doing", n:"26/10: đã có 4 file, hash ở data_manifest/thesis_outputs.json. 3 file dùng được; porosity_volume_600_1100ms.npz rỗng (0 byte), cần tải lại. Không chặn P1."}, {id:"p0-out", t:"Lấy outputs/ của luận văn từ iCloud", s:"doing", n:"26/10: đã có 4 file (mã băm ở data_manifest/thesis_outputs.json), 3 file dùng được. File porosity_volume_600_1100ms.npz rỗng (0 byte), cần tải lại. Không chặn P1."},
{id:"p0-geo", t:"geometry.py và test bằng Set Point", s:"done", n:"ml_porosity/data/geometry.py đọc biến đổi bin↔XY từ .survey, khớp cả 3 Set Point (sai số < 0.01 m) và header CDP của SEG-Y. Tái tạo đúng bảng IL/XL và độ lệch 6.94 / 5.05 / 11.42 km ở mục 1.2a."}, {id:"p0-geo", t:"Chuyển số hiệu ô lưới ↔ toạ độ thật (geometry.py), kiểm bằng Set Point", s:"done", n:"ml_porosity/data/geometry.py đọc công thức chuyển bin ↔ XY từ file .survey. Khớp cả 3 điểm kiểm Set Point (sai số < 0.01 m) và header CDP của SEG-Y. Tái tạo đúng bảng IL/XL và phát hiện luận văn đặt giếng lệch 6.94 / 5.05 / 11.42 km (mục 1.2a)."},
{id:"p0-td", t:"tdr.py (marker-calibrated sonic) và hình drift 4 giếng (nháp F2)", s:"done", n:"4 TDR: legacy, calibrated (co giãn theo từng khoảng anchor, luôn đơn điệu), anchors, wlt. Hình outputs/figures/td_drift.png và bảng outputs/td_qc.csv."}, {id:"p0-td", t:"Dựng quan hệ thời gian–độ sâu (tdr.py) và hình drift của 4 giếng", s:"done", n:"4 phiên bản TDR: legacy (của luận văn), calibrated (co giãn trong từng khoảng giữa hai anchor để đi qua mọi marker, luôn đơn điệu), anchors, wlt (của OpendTect). Hình outputs/figures/td_drift.png, bảng outputs/td_qc.csv."},
{id:"p0-refactor", t:"Tái cấu trúc code theo mục 7, bỏ đường dẫn Windows", s:"done", n:"Gói ml_porosity/ (data, models, losses, eval; registration/ để trống cho P2), scripts 00–03, configs/. Đường dẫn tính từ gốc repo hoặc biến môi trường. Log sang thời gian có lọc chống alias (sửa lỗi #8). test 2/ giữ nguyên."}, {id:"p0-refactor", t:"Tái cấu trúc code theo plan mục 7, bỏ đường dẫn Windows", s:"done", n:"Gói ml_porosity/ (data, models, losses, eval), scripts 00–03, configs/. Đường dẫn tính từ gốc repo hoặc biến môi trường. Log chuyển sang thời gian có lọc chống alias (sửa lỗi #8 của audit). Thư mục test 2/ (code luận văn) giữ nguyên."},
{id:"p0-env", t:"Khóa môi trường (phiên bản thư viện)", s:"done", n:"pyproject.toml và requirements-lock.txt (Python 3.13.15, numpy 2.5.3, torch 2.14.0, segyio 1.9.14, lasio 0.32). Venv .venv dùng lại gói hệ thống."}, {id:"p0-env", t:"Khoá phiên bản thư viện", s:"done", n:"pyproject.toml và requirements-lock.txt (Python 3.13.15, numpy 2.5.3, torch 2.14.0, segyio 1.9.14, lasio 0.32). Venv .venv dùng lại gói hệ thống."},
{id:"p0-tests", t:"Unit test geometry và TD", s:"done", n:"41 test pass trong 4 s: geometry, TDR (đơn điệu, đi qua anchor, chống alias), SEG-Y, model; các test dữ liệu kiểm số liệu mục 1.2a–c."}, {id:"p0-tests", t:"Unit test cho geometry và TDR", s:"done", n:"41 test chạy trong 4 s: geometry, TDR (đơn điệu, đi qua anchor, chống alias), đọc SEG-Y, model. Một số test kiểm trực tiếp số liệu audit mục 1.2a–c."},
{id:"p0-e2e", t:"Pipeline chạy end-to-end", s:"done", n:"scripts/run_p0.sh (kiểm hash, dựng giếng, QC TD, train thử B2, test) chạy trong 17 s trên Linux có GPU, kết quả lặp lại được. Chưa thử trên macOS. Số liệu train thử chỉ để kiểm hạ tầng, không phải baseline."} {id:"p0-e2e", t:"Chạy thông toàn bộ pipeline", s:"done", n:"scripts/run_p0.sh (kiểm mã băm → dựng dữ liệu giếng → QC TDR → train thử B2 → chạy test) mất 17 s trên Linux có GPU, chạy lại cho cùng kết quả. Chưa thử trên macOS. Số liệu train thử chỉ để kiểm hạ tầng, không phải baseline."}
]}, ]},
{id:"P1", name:"P1 Audit và baseline đúng", start:"2026-11-02", end:"2026-11-29", weeks:"Tuần 2–5", {id:"P1", name:"P1 Audit và baseline đúng", start:"2026-10-26", end:"2026-10-26", weeks:"T2 26/10",
out:"Ghi chú audit dữ liệu; bảng baseline", out:"ghi chú audit dữ liệu; bảng baseline",
gate:{label:"G-A", date:"2026-11-29", text:"Baseline tái lập được (5 seed, có phương sai); đã ước lượng misregistration còn lại. Nếu sau tie tốt nhất còn < 1/8 chu kỳ ở mọi giếng và B3a ≈ B3b thì dồn sang D2 + D3."}, gate:{label:"G-A", date:"2026-10-26", text:"Baseline chạy lại được (5 seed, có độ dao động) và đã ước lượng sai lệch căn chỉnh còn lại. Nếu sau tie tốt nhất sai lệch còn < 1/8 chu kỳ ở mọi giếng và B3a ≈ B3b, thì F3 không đủ để thể hiện vấn đề, nên dồn sang D2 + D3.", res:"đánh giá ngày 26/10/2026: điều kiện chuyển hướng không thoả, tiếp tục P2 (xem Kết quả P1)."},
tasks:[ tasks:[
{id:"p1-td", t:"So sánh các nguồn TD (DT_model, checkshot, .wlt)", s:"done", n:"DT_model lệch +40, +40, +25, −15 ms theo giếng, không phải hằng số; .wlt khớp checkshot hơn."}, {id:"p1-td", t:"So sánh các nguồn thời gian–độ sâu (DT_model, checkshot, .wlt)", s:"done", n:"DT_model lệch checkshot +40, +40, +25, −15 ms tuỳ giếng, không phải một hằng số. .wlt khớp checkshot hơn."},
{id:"p1-spec", t:"Đo tần số trội và phổ seismic", s:"done", n:"Đỉnh ~60 Hz, trung bình ~49 Hz, băng 4–83 Hz; f_c đề xuất 6 Hz."}, {id:"p1-spec", t:"Đo tần số trội và phổ seismic", s:"done", n:"Đỉnh ~60 Hz, trung bình ~49 Hz, băng 4–83 Hz, nên một chu kỳ khoảng 17–20 ms. Chọn ranh giới băng thấp / băng seismic f_c = 6 Hz."},
{id:"p1-protocol", t:"Viết và khoá configs/protocol.yaml trước khi train", s:"done", n:"26/10: v2 khoá bằng SHA-256 (configs/protocol.sha256) lúc 04:28:09Z, trước lần chạy LOWO đầu tiên (04:30:50Z); v1 → v2 chỉ đổi solver của B1, ghi trong changelog. 05_lowo.py từ chối chạy nếu hash lệch. Commit cùng P0 + P1 và gắn tag protocol-v2 ngày 26/10; commit có sau lần chạy, nên bằng chứng khoá trước là hash và các mốc thời gian."}, {id:"p1-protocol", t:"Viết và khoá configs/protocol.yaml trước khi huấn luyện", s:"done", n:"Protocol ghi trước mọi lựa chọn (phương pháp, metric, ngưỡng). Bản v2 được khoá bằng SHA-256 (configs/protocol.sha256) lúc 04:28:09Z, trước lần chạy LOWO đầu tiên (04:30:50Z). Từ v1 lên v2 chỉ đổi solver của B1, có ghi trong changelog. 05_lowo.py từ chối chạy nếu mã băm lệch. Commit và tag protocol-v2 có sau lần chạy, nên bằng chứng khoá trước là mã băm và các mốc thời gian."},
{id:"p1-wav", t:"Ước lượng wavelet từ F3", s:"done", n:"Wavelet thống kê pha không và wavelet LS từ giếng (ml_porosity/data/wavelet.py). Pha hằng tốt nhất khác nhau rất nhiều giữa các giếng (−120° đến +130°), nên một wavelet chung không tie tốt cả 4 giếng."}, {id:"p1-wav", t:"Ước lượng wavelet từ F3", s:"done", n:"Wavelet thống kê pha không và wavelet bình phương tối thiểu từ giếng (ml_porosity/data/wavelet.py). Pha tốt nhất khác nhau rất nhiều giữa các giếng (−120° đến +130°), nên một wavelet chung không tie tốt được cả 4 giếng."},
{id:"p1-synth", t:"Synthetic seismogram 4 giếng (QC tie)", s:"done", n:"scripts/04_wavelet_tie.py, hình outputs/figures/ties.png. Tie tốt nhất mỗi giếng (pha + bulk shift): r = 0.33 (F02-1), 0.34 (F03-2), 0.58 (F03-4), 0.46 (F06-1) với calibrated; .wlt tie tốt hơn ở cả 4 giếng (0.40–0.70)."}, {id:"p1-synth", t:"Seismic nhân tạo (synthetic) cho 4 giếng để kiểm tra tie", s:"done", n:"scripts/04_wavelet_tie.py, hình outputs/figures/ties.png. Tương quan synthetic–seismic tốt nhất mỗi giếng (cho phép chỉnh pha và dịch chung), với TDR calibrated: 0.33 (F02-1), 0.34 (F03-2), 0.58 (F03-4), 0.46 (F06-1). .wlt tie tốt hơn ở cả 4 giếng (0.40–0.70). Nói chung tie trên F3 yếu."},
{id:"p1-misreg", t:"Ước lượng misregistration còn lại sau tie tốt nhất", s:"done", n:"Lệch cục bộ còn lại 6–14 ms RMS (calibrated), nhưng ngưỡng nhiễu của chính phép đo ở cùng mức tương quan là 8–14 ms. Với chất lượng tie này, F3 không phân giải được misregistration ở mức T/8 ≈ 2.5 ms. Trong cửa sổ, .wlt lệch marker tới 9–37 ms và tích phân DT tới 14–66 ms tuỳ giếng."}, {id:"p1-misreg", t:"Ước lượng sai lệch căn chỉnh còn lại sau tie tốt nhất", s:"done", n:"Lệch cục bộ còn lại 6–14 ms RMS (calibrated), nhưng chính phép đo có ngưỡng nhiễu 8–14 ms. Vì vậy không phân biệt được với 0, cũng không chứng minh được nó dưới 1/8 chu kỳ (≈ 2.5 ms). Trong cửa sổ, .wlt lệch marker tới 9–37 ms, tích phân DT lệch tới 14–66 ms tuỳ giếng."},
{id:"p1-label", t:"QC nhãn và quyết định D-1", s:"done", n:"PHIE là hàm chính xác của RHOB (1600) và sonic ở 3/4 giếng. scripts/08_d1_label_check.py so φ_D từ RHOB đo của NLOG với PHIE_DT: R² 0.27–0.59 ở 4 giếng. Chốt D-1 ngày 26/10: PHIE_DT chính, PHIE phụ, φ_D chỉ để đánh giá độ nhạy; giữ 4 giếng."}, {id:"p1-label", t:"Kiểm tra nhãn và quyết định D-1", s:"done", n:"Ở 3/4 giếng, PHIE là công thức chính xác của RHOB (hằng số 1600) và sonic, không phải số đo độc lập. scripts/08_d1_label_check.py so porosity tính từ RHOB đo thật của NLOG với PHIE_DT: R² chỉ 0.27–0.59 ở 4 giếng. Chốt D-1 ngày 26/10: PHIE_DT là nhãn chính, PHIE phụ, φ_D chỉ để kiểm độ nhạy; giữ 4 giếng."},
{id:"p1-lowo", t:"LOWO cho B0, B1, B2, B3a–b (5 seed)", s:"done", n:"26/10: scripts/05_lowo.py (inner LOWO chọn epoch, α, e; không dùng thông tin giếng test), 06_summarize_p1.py. 240 dòng kết quả, 2 nhãn × 2 tham chiếu. Không phương pháp nào hơn trend B0a về RMSE; xem bảng Kết quả P1."}, {id:"p1-lowo", t:"LOWO cho B0, B1, B2, B3a–b (5 seed)", s:"done", n:"26/10: scripts/05_lowo.py (vòng LOWO bên trong chọn epoch, α, e mà không dùng thông tin giếng test) và 06_summarize_p1.py. 240 dòng kết quả, 2 nhãn × 2 tham chiếu. Không phương pháp nào hơn đường xu hướng B0a về RMSE; xem Kết quả P1."},
{id:"p1-volve", t:"Kiểm kê Volve", s:"done", n:"26/10 xong phần cục bộ (docs/research/volve-inventory.md): toạ độ và survey lệch đủ cho 8 giếng (ED50 UTM31N). Đã tải Geophysical_Interpretations (mục 6, scripts/07_volve_interp_qc.py): 32 horizon trên lưới ST10010 12.5 m, well picks cho cả 10 giếng D3 có 6–13 marker TWT nên hết thiếu TD. Cube post-stack ST10010 đã về và đã kiểm tra (toạ độ khớp lưới horizon trong 0.15 m; sửa t0 từ 12 về 4 ms). Còn dựng lại manifest khi tải xong."}, {id:"p1-volve", t:"Kiểm kê Volve", s:"done", n:"Phần cục bộ xong 26/10 (docs/research/volve-inventory.md): toạ độ và quỹ đạo giếng cho 8 giếng (ED50 UTM31N). Đã tải Geophysical_Interpretations (scripts/07_volve_interp_qc.py): 32 horizon trên lưới ST10010 12.5 m, và marker TWT cho cả 10 giếng D3 (6–13 marker mỗi giếng), nên hết thiếu dữ liệu thời gian–độ sâu. Cube post-stack ST10010 đã về và đã kiểm (toạ độ khớp lưới horizon trong 0.15 m; sửa t0 từ 12 về 4 ms). Manifest data_manifest/volve.json đã dựng lại sau khi tải xong."},
{id:"p1-nlog", t:"Kiểm kê NLOG trong footprint F3", s:"done", n:"38 borehole, 7 có TD số; F03-03 và F03-06 thêm được."} {id:"p1-nlog", t:"Kiểm kê NLOG trong vùng F3", s:"done", n:"38 lỗ khoan, 7 có số liệu thời gian–độ sâu dạng số; dùng thêm được F03-03 và F03-06."}
]}, ]},
{id:"P2", name:"P2 Lý thuyết, synthetic, RML v1", start:"2026-11-30", end:"2027-01-03", weeks:"Tuần 5–9", {id:"P2", name:"P2 Lý thuyết, synthetic, RML v1", start:"2026-10-26", end:"2026-10-27", weeks:"T2–T3 26–27/10",
out:"Kết quả synthetic; phase diagram v1", out:"kết quả synthetic; bản đồ pha v1",
gate:{label:"G-B", date:"2027-01-03", text:"M2 hơn B3/B4 tốt nhất (RMSE băng −10% hoặc PCC băng +0.05) ở ≥ 4/5 seed; không kém hơn 2% khi drift = 0. Nếu trượt: chẩn đoán tối đa 2 tuần rồi pivot."}, gate:{label:"G-B", date:"2026-10-26", text:"Trên synthetic D2, M2 hơn B3/B4 tốt nhất (RMSE băng −10% hoặc PCC băng +0.05) ở ≥ 4/5 seed, và không kém quá 2% khi không có drift. Nếu trượt: chẩn đoán có thời hạn rồi chạy lại hoặc chuyển hướng.", res:"đánh giá ngày 26/10/2026, <b>không đạt</b> (c = 1: 0/4 ô; drift = 0: tỉ số 1.039 so với ngưỡng 1.02). Chẩn đoán đến hết 27/10/2026 trên realization dev (lịch nén), rồi chạy lại trên realization mới hoặc chuyển hướng theo §9 (xem Kết quả P2 và Chẩn đoán sau G-B)."},
tasks:[ tasks:[
{id:"p2-proof", t:"Chứng minh Mệnh đề 1 và 2", s:"todo"}, {id:"p2-proof", t:"Chứng minh Mệnh đề 1 và 2", s:"done", n:"26/10: docs/theory.md. Mệnh đề 1 (làm mờ): học MSE với nhãn lệch ngẫu nhiên tương đương học nhãn đã lọc bởi exp(−2π²σ²f²). Vì vậy std ratio và PCC trong băng bị chặn trên, còn L_Var chỉ chỉnh được biên độ. Mệnh đề 2 (nhận dạng): không có anchor thì mạng và warp có thể cùng dịch mà loss không đổi. Với K anchor, độ bất định của phép dịch chung ≈ σ_a/√K (≈ 1.75 ms với 16 anchor, σ_a = 7 ms). Thêm heuristic λ = 1/τ_c và Bổ đề 1–5: B3, B4a–d là trường hợp riêng của RML. Chưa làm: chẩn đoán strain energy, tính nhất quán của estimator."},
{id:"p2-synth", t:"Bộ sinh synthetic D2", s:"todo"}, {id:"p2-synth", t:"Bộ sinh synthetic D2", s:"done", n:"26/10: ml_porosity/data/synth_d2.py, configs/d2_synth.yaml. 8 realization, mỗi realization 24 giếng giả (16 để train, 8 để test), cửa sổ 400–1300 ms, SNR 10 dB. Anchor đặt ở biên các lớp con (14–21 anchor mỗi giếng), nhiễu pick σ_a = 7 ms. Drift rút từ prior GP fit trên marker F3, nhân c ∈ {0, 0.5, 1, 2}. Kiểm tra (scripts/10): ở c = 1 drift có trung vị 39 ms (F3: 13–46 ms), độ dài tương quan của nhãn τ_c = 2.7 mẫu (F3: 1.6–2.5); dao động của nhãn thấp hơn F3 một chút (0.022 so với 0.025–0.051). Chưa có: lưới SNR, mật độ anchor, rock physics sai mô hình."},
{id:"p2-rml", t:"RML M1, M2", s:"todo"}, {id:"p2-rml", t:"RML M1, M2", s:"done", n:"26/10: ml_porosity/registration/. Prior GP Matérn-3/2 trên g (học m_g, σ_g, ℓ bằng MAP-II); lấy mẫu bằng Laplace + elliptical slice, S = 64; likelihood tie có pha hằng; tempering chọn γ lớn nhất sao cho ESS ≥ S/4. Loss ở losses/rml.py, huấn luyện ở models/bank_train.py, λ = 1/τ_c ≈ 0.37. Khác plan: σ_a, σ_b cố định (7 / 50 ms), |g| ≤ 1.0 thay vì 0.15. M3 (RML-EM) hoãn."},
{id:"p2-b45", t:"Baseline B4, B5", s:"todo"} {id:"p2-b45", t:"Baseline B4, B5", s:"done", n:"26/10: B4a hard-min ±8 mẫu (σ học được), B4b soft-min, B4c soft-DTW (losses/softdtw.py), B4d DILATE; B5 = ensemble 5 seed của B3b. Thêm hai đối thủ mạnh hơn: B3c (B3b + dịch cục bộ theo tương quan synthetic–seismic) và B3d (một nhãn từ warp trung bình của M2)."},
{id:"p2-grid", t:"Lưới D2 chính, bản đồ pha v1, cổng G-B", s:"done", n:"26/10: scripts/11_run_d2.py --main trên cuda:1, 89 phút. 128 ô (8 realization × c ∈ {0, 0.5, 1, 2} × N ∈ {2, 4, 8, 16}), mỗi ô 11 phương pháp × 5 seed, chấm trên 8 giếng test (56 960 dòng, gồm cả biến thể không anchor cho H4). Số bước huấn luyện chọn trên realization dev 900/901 và khoá trong protocol_p2 (sha256 07336200…) trước khi chạy. scripts/13 vẽ bản đồ pha v1 (outputs/figures/p2_phase.png), p2_band_lines.png, p2_h1.png, p2_h3.png. G-B không đạt; xem Kết quả P2."},
{id:"p2-diag", t:"Chẩn đoán sau G-B (đến hết 27/10/2026), rồi chuyển hướng nếu vẫn trượt", s:"done", n:"Xong 27/10, xem mục Chốt P2 (σ_b và rock physics sai chưa kiểm). Đã xong (1)–(3) trên dev 900/901, xem mục Chẩn đoán sau G-B. (1) Sampler nhắm thẳng posterior có seismic: SMC tempering + elliptical slice, ước lượng lại pha (registration/smc.py, smc_torch.py; scripts/14). (2) Chọn γ theo tự tương quan phần dư thay cho luật ESS ≥ S/4. (3) Quét λ ∈ {0.37, 1, 3, ∞} (scripts/15). Kết quả: sai số căn chỉnh về mức trần; nhãn SMC đạt gate với đối thủ của protocol_p2 nhưng không hơn nhãn warp trung bình cùng posterior (B3d-S); λ ít quan trọng khi posterior tốt. Còn lại: (4) học σ_a, σ_b như plan §4.1; (5) lưới stress (SNR thấp, ít anchor, rock physics sai) để tìm vùng posterior rộng. Sau đó khoá protocol_p2r (đối thủ B3d-S, realization mới, nhiều hạt hơn) hoặc Pivot 1. Luật: protocol cho tối đa 2 tuần, lịch nén rút còn đến hết 27/10/2026; chỉ dùng realization dev (thêm dev mới nếu cần), không đụng realization 0–7 của lưới chính. Nếu vẫn trượt thì chuyển hướng theo §9, nhiều khả năng Pivot 1 (bài phân tích) cùng claim của R1: khi nào vấn đề này quan trọng, và cách làm không gây hại."},
{id:"p2-p2r", t:"Khoá protocol_p2r và chạy lại D2 trên realization mới, hoặc quyết định Pivot 1", s:"done", n:"Xong 27/10 (11:29 giờ máy chủ). Đã khoá protocol_p2r (tag protocol-p2r) và chạy lưới chính trên realization 8–15 (cuda:0 + cuda:1; scripts/run_p2r_main.sh, scripts/18_summarize_p2r.py → outputs/p2r/summary/). Không Pivot 1. Kết quả theo luật đã khoá: H2a ĐẠT (R10 c = 1: band RMSE B3d-Sa / point tie tốt nhất 0.857 / 0.782 ở N = 4 / 16; R0 và Rm5 cũng đạt). So với cả B3d: chỉ R10 đạt (R0 1/2 ô, Rm5 0/2). Nhánh σ_a trượt (σ_a = 3.5 ms: 0.98 / 1.14; 14 ms: 0.99 / 0.93), nên bài phải nói H2a cần σ_a đúng. H2b ĐẠT (N = 16: 8/8 ô posterior rộng, ρ = −0.85, p = 1e-4, ô hẹp 0.996). Lưu ý: B3d-Sa đã hơn point tie ngay ở c = 0 (≈ 0.81), nên phần lợi gắn với drift là B3d-Sa giữ nguyên khi drift tăng còn B3d xấu đi; ở phần lớn ô rộng c = 1 lợi của H2b vượt cận 1/B(σ_post). H3 chỉ mô tả: mọi ensemble, kể cả Oracle, under-cover."}
]}, ]},
{id:"P3", name:"P3 F3 field", start:"2027-01-04", end:"2027-01-31", weeks:"Tuần 9–13", {id:"P3", name:"P3 F3 thật", start:"2026-10-28", end:"2026-10-28", weeks:"T4 28/10",
out:"Bảng và hình F3", out:"bảng và hình cho F3",
gate:{label:"G-C", date:"2027-01-31", text:"Chiều cải thiện nhất quán với synthetic ở ≥ 3/4 giếng; coverage 80/90% trong ±5% mức danh nghĩa."}, gate:{label:"G-C", date:"2026-10-28", text:"Trên F3 thật, chiều cải thiện giống synthetic ở ≥ 3/4 giếng; coverage 80/90% lệch mức danh nghĩa không quá ±5%."},
tasks:[ tasks:[
{id:"p3-lowo", t:"Nested LOWO đầy đủ, ensemble, calibration", s:"todo"}, {id:"p3-lowo", t:"Nested LOWO đầy đủ, ensemble, calibration", s:"todo"},
{id:"p3-abl", t:"Ablation, leave-one-anchor-out", s:"todo"}, {id:"p3-abl", t:"Ablation (bỏ từng thành phần), leave-one-anchor-out", s:"todo"},
{id:"p3-vol", t:"Volume kèm bất định, M3", s:"todo"} {id:"p3-vol", t:"Dự đoán cả khối kèm bất định", s:"todo", n:"Nếu trễ: chỉ một inline và một crossline qua giếng. M3 (RML-EM) hoãn, không đưa vào bài."}
]}, ]},
{id:"P4", name:"P4 Field thứ hai", start:"2027-01-25", end:"2027-03-07", weeks:"Tuần 12–17", {id:"P4", name:"P4 Field thứ hai (Volve)", start:"2026-10-28", end:"2026-10-29", weeks:"T4–T5 28–29/10",
out:"Bảng field 2", out:"bảng kết quả field 2",
gate:{label:"G-D", date:"2027-03-07", text:"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ả."}, gate:{label:"G-D", date:"2026-10-29", text:"Báo cáo kết quả field 2 dù tốt hay xấu; thu hẹp phạm vi claim theo kết quả."},
tasks:[ tasks:[
{id:"p4-roi", t:"ROI Volve, tie, pipeline", s:"todo", n:"Cube ST10010 FULL_T đã có (ROI IL 10020–10303, XL 2089–2440, TWT 2000–3200 ms). Time-depth: marker TWT từ well picks cho cả 10 giếng, checkshot ở F-11 T2 và F-15 A; 6 giếng đủ log."}, {id:"p4-roi", t:"Vùng quan tâm (ROI) của Volve, tie, pipeline", s:"todo", n:"Đã có cube ST10010 FULL_T (ROI IL 10020–10303, XL 2089–2440, TWT 2000–3200 ms). Thời gian–độ sâu: marker TWT từ well picks cho cả 10 giếng, checkshot ở F-11 T2 và F-15 A; 6 giếng đủ log."},
{id:"p4-run", t:"Chạy tập con B1, B3, B4, B5, M2", s:"todo"} {id:"p4-run", t:"Chạy tập con B1, B3, B4, B5, M2", s:"todo", n:"T5 29/10. Nếu trễ: chỉ B3 tốt nhất, B3d-S và M2."}
]}, ]},
{id:"P5", name:"P5 Viết bài", start:"2027-02-08", end:"2027-04-11", weeks:"Tuần 15–21", {id:"P5", name:"P5 Viết bài", start:"2026-10-29", end:"2026-10-30", weeks:"T5–T6 29–30/10",
out:"Draft v1 (tuần 19), v2 (tuần 21); gói tái lập", gate:null, out:"draft v1 (cuối 29/10), v2 (cuối 30/10); gói tái lập", gate:null,
tasks:[ tasks:[
{id:"p5-d1", t:"Draft v1", s:"todo"}, {id:"p5-d1", t:"Draft v1", s:"todo", n:"Cuối T5 29/10. Khung bài và các mục audit F3, lý thuyết, D2 viết dần từ 27/10 vì số liệu đã có."},
{id:"p5-d2", t:"Draft v2, phụ lục chứng minh", s:"todo"}, {id:"p5-d2", t:"Draft v2, phụ lục chứng minh", s:"todo", n:"Cuối T6 30/10."},
{id:"p5-repro", t:"Gói tái lập (code, config, dữ liệu dẫn xuất)", s:"todo"} {id:"p5-repro", t:"Gói tái lập (code, config, dữ liệu dẫn xuất)", s:"todo"}
]}, ]},
{id:"P6", name:"P6 Review và nộp", start:"2027-04-12", end:"2027-05-02", weeks:"Tuần 21–24", {id:"P6", name:"P6 Review và nộp", start:"2026-10-31", end:"2026-10-31", weeks:"T7 31/10",
out:"Bản nộp", gate:null, out:"bản nộp", gate:null,
tasks:[ tasks:[
{id:"p6-rev", t:"GVHD và một người làm địa vật lý review", s:"todo"}, {id:"p6-rev", t:"GVHD và một người làm địa vật lý đọc góp ý", s:"todo"},
{id:"p6-nov", t:"Kiểm tra novelty lần cuối, kiểm tra quartile venue", s:"todo"}, {id:"p6-nov", t:"Kiểm tra tính mới lần cuối, tra quartile của venue", s:"todo"},
{id:"p6-sub", t:"Preprint và nộp", s:"todo"} {id:"p6-sub", t:"Đăng preprint và nộp", s:"todo"}
]} ]}
]; ];
const XM = [ const XM = [
{name:"DT_model lệch checkshot (do datum?)", where:"dòng 89, mục 1.2c", s:"done", r:"Không phải hằng số, không do MD/TVD (giếng thẳng đứng) và không giải thích được bằng KB 30 ms. Nghi vấn nằm ở file DT_model."}, {name:"DT_model lệch checkshot: có phải do datum?", where:"dòng 89, mục 1.2c", s:"done", r:"Không. Độ lệch không phải hằng số, không do MD/TVD (giếng thẳng đứng) và không giải thích được bằng KB 30 ms. Nghi vấn nằm ở chính file DT_model."},
{name:"PHIE của F02-1", where:"mục 1.2d", s:"done", r:"Bám RHOB đo (R² 0.84, corr −0.92) nhưng không tất định; còn thành phần khác chưa xác định."}, {name:"PHIE của F02-1 tính từ đâu?", where:"mục 1.2d", s:"done", r:"Bám RHOB đo (R² 0.84, corr −0.92) nhưng không theo công thức tất định; còn một thành phần khác chưa xác định."},
{name:"Tần số trội của seismic F3", where:"dòng 114, mục 1.3", s:"done", r:"Đỉnh ~60 Hz, trung bình ~49 Hz; bất định registration bằng 1–4 chu kỳ."}, {name:"Tần số trội của seismic F3", where:"dòng 114, mục 1.3", s:"done", r:"Đỉnh ~60 Hz, trung bình ~49 Hz. Bất định căn chỉnh tương đương 1–4 chu kỳ."},
{name:"Thay giả định 30 Hz bằng phổ thật", where:"mục 2.3", s:"done", r:"Băng 4–83 Hz; σ_δ = 8 ms chỉ giữ lại ~6% phương sai."}, {name:"Thay giả định 30 Hz bằng phổ thật", where:"mục 2.3", s:"done", r:"Băng 4–83 Hz; với phổ thật, độ lệch σ_δ = 8 ms chỉ giữ lại ~6% phương sai."},
{name:"f_c cho tách băng tần", where:"mục 5.4", s:"done", r:"Năng lượng < 8 Hz chỉ 1–2%; đề xuất f_c = 6 Hz, độ nhạy 5 và 8 Hz."}, {name:"Ranh giới f_c để tách băng", where:"mục 5.4", s:"done", r:"Năng lượng dưới 8 Hz chỉ 1–2%. Chọn f_c = 6 Hz, kiểm độ nhạy ở 5 và 8 Hz."},
{name:"Mốc thời gian của SEG-Y (delay 4 ms)", where:"mục 1.2, phát hiện khi làm P0", s:"todo", r:"F3_entire.segy có DelayRecordingTime = 4 ms (mẫu đầu ở 4 ms) trong khi .survey ghi Z bắt đầu từ 0. Cần xác nhận marker TD và horizon dùng cùng mốc, nếu không sẽ có lệch đều 1 mẫu. 26/10: horizon − marker tại giếng có trung vị +1.6 ms (FS8, Truncation lệch ≤ 2 ms); bulk shift của tie tốt nhất ở F03-4, F06-1 là +1 đến +7 ms. Chưa đủ để kết luận ở mức 4 ms."}, {name:"Mốc thời gian của SEG-Y (delay 4 ms)", where:"mục 1.2, phát hiện khi làm P0", s:"todo", r:"F3_entire.segy ghi DelayRecordingTime = 4 ms (mẫu đầu ở 4 ms), trong khi .survey ghi trục Z bắt đầu từ 0. Cần xác nhận marker và horizon dùng cùng mốc, nếu không sẽ lệch đều 1 mẫu. Kiểm 26/10: horizon − marker tại giếng có trung vị +1.6 ms (FS8, Truncation lệch ≤ 2 ms); dịch chung của tie tốt nhất ở F03-4, F06-1 là +1 đến +7 ms. Chưa đủ để kết luận ở mức 4 ms."},
{name:"Kiểm kê NLOG", where:"D1, mục 5.1", s:"done", r:"F03-03 và F03-06 dùng được; F03-05-S1 không (TD bắt đầu 1295 ms)."}, {name:"Kiểm kê NLOG", where:"D1, mục 5.1", s:"done", r:"F03-03 và F03-06 dùng được; F03-05-S1 không (dữ liệu thời gian–độ sâu bắt đầu ở 1295 ms)."},
{name:"Kiểm kê Volve", where:"D3, mục 5.1", s:"done", r:"Xong phần cục bộ: toạ độ, survey, ROI. Horizon và well picks đã tải 26/10 (marker TWT cho cả 10 giếng). Cube ST10010 đã tải và kiểm tra."}, {name:"Kiểm kê Volve", where:"D3, mục 5.1", s:"done", r:"Xong phần cục bộ: toạ độ, quỹ đạo, ROI. Horizon và well picks tải ngày 26/10 (marker TWT cho cả 10 giếng). Cube ST10010 đã tải và kiểm tra."},
{name:"Quét SEG/EAGE 2024–2026", where:"mục 2.4 (4)", s:"todo", r:"Từ khóa: well tie uncertainty, misalignment, label noise, porosity, impedance."}, {name:"Quét SEG/EAGE 2024–2026", where:"mục 2.4 (4)", s:"todo", r:"Từ khoá: well tie uncertainty, misalignment, label noise, porosity, impedance."},
{name:"Đặt Google Scholar alert", where:"mục 2.4 (5)", s:"todo", r:"Làm cùng bước quét; nhắc lại trước khi nộp."}, {name:"Đặt Google Scholar alert", where:"mục 2.4 (5)", s:"todo", r:"Làm cùng bước quét; nhắc lại trước khi nộp."},
{name:"5 bài chỉ có abstract (P03, P04, P05, P07, P09)", where:"mục 2.2", s:"todo", r:"Cần toàn văn để kiểm tra lại các ô trong bảng định vị."}, {name:"5 bài mới đọc được abstract (P03, P04, P05, P07, P09)", where:"mục 2.2", s:"todo", r:"Cần toàn văn để kiểm lại các ô trong bảng định vị literature."},
{name:"Quartile SJR của venue", where:"dòng 28, mục 8", s:"todo", r:"Tra SCImago khi nộp bài."}, {name:"Quartile SJR của venue", where:"dòng 28, mục 8", s:"todo", r:"Tra SCImago khi nộp bài."},
{name:"Xếp hạng CORE của hội nghị", where:"mục 8", s:"todo", r:"Tra portal.core.edu.au (ICANN, ICONIP)."}, {name:"Xếp hạng CORE của hội nghị", where:"mục 8", s:"todo", r:"Tra portal.core.edu.au (ICANN, ICONIP)."},
{name:"Gunning & Glinsky (2006), Wavelet extractor", where:"mục 2.4 (2), mục 11", s:"done", r:"Đã đọc toàn văn 26/10/2026 (refs/j.cageo.2005.10.001.pdf). Tóm tắt ở mục 2.1 L1; bib gunning2006waveletextractor."}, {name:"Gunning & Glinsky (2006), Wavelet extractor", where:"mục 2.4 (2), mục 11", s:"done", r:"Đã đọc toàn văn ngày 26/10/2026 (refs/j.cageo.2005.10.001.pdf). Tóm tắt ở plan mục 2.1 L1; bib gunning2006waveletextractor."},
{name:"Bài RING 2025, bài EAGE 2023", where:"mục 2.4 (1, 3)", s:"drop", r:"Quyết định bỏ ngày 26/10/2026 (không tìm thấy hoặc không xác định được bài)."} {name:"Bài RING 2025, bài EAGE 2023", where:"mục 2.4 (1, 3)", s:"drop", r:"Bỏ ngày 26/10/2026 vì không tìm thấy hoặc không xác định được bài."}
]; ];
const DECISIONS = [ const DECISIONS = [
{id:"D-1", q:"Định nghĩa nhãn", p:"PHIE_DT hài hòa làm nhãn chính (báo cáo là porosity dẫn xuất từ sonic); PHIE gốc làm phụ để so với luận văn; φ_D = (2650 − RHOB đo)/1600 chỉ để đánh giá độ nhạy ở F02-1 và F03-4. Giữ 4 giếng.", n:"scripts/08: φ_D so với PHIE_DT trong 600–1100 ms có R² 0.27–0.59 và RMS 3.9–5.0 p.u. Như vậy nhãn density khác nhãn sonic, nhưng RHOB đo chỉ có ở 2/4 giếng demo, còn PHIE_DT có ở cả 4 và chuỗi rock physics là chính xác. Hoãn F03-03 và F03-06: chưa có marker làm anchor, TZ có thể là TD đã xử lý, F03-06 có DRHO cao. Kiểm tra độc lập với sonic giao cho D3 (PHIF của Volve). Protocol v2 không phải đổi."}, {id:"D-1", q:"Dùng nhãn porosity nào?", p:"Nhãn chính là PHIE_DT (porosity suy từ sonic, ghi rõ như vậy trong bài). PHIE gốc làm nhãn phụ để so với luận văn. φ_D = (2650 − RHOB đo)/1600 chỉ để kiểm độ nhạy ở F02-1 và F03-4. Giữ cả 4 giếng.", n:"So φ_D với PHIE_DT trong 600–1100 ms (scripts/08): R² 0.27–0.59, RMS 3.9–5.0 p.u., tức nhãn density khác nhãn sonic. Nhưng RHOB đo chỉ có ở 2/4 giếng demo, còn PHIE_DT có ở cả 4 và chuỗi rock physics chính xác. Hoãn F03-03 và F03-06: chưa có marker làm anchor, TZ có thể là dữ liệu thời gian–độ sâu đã qua xử lý, F03-06 có DRHO cao. Việc kiểm tra với nhãn độc lập với sonic giao cho D3 (PHIF của Volve). Protocol v2 không phải đổi."},
{id:"D-2", q:"Cửa sổ thời gian", p:"600–1100 ms chính, thêm một cửa sổ mở rộng (chốt theo đề xuất)", n:"Phổ ổn định trong 200–1100 ms; sau 1100 ms phổ đổi (đỉnh ~7 Hz), cần xem trước khi mở rộng cửa sổ xuống sâu."}, {id:"D-2", q:"Cửa sổ thời gian", p:"600–1100 ms là cửa sổ chính, thêm một cửa sổ mở rộng (theo đề xuất).", n:"Phổ ổn định trong 200–1100 ms. Sau 1100 ms phổ đổi (đỉnh ~7 Hz), cần xem kỹ trước khi mở rộng xuống sâu."},
{id:"D-3", q:"Field thứ hai", p:"Volve (chốt)", n:"PHIF phụ thuộc density nên đúng yêu cầu D3. Cube ST10010 đã có và khớp horizon; horizon và well picks đã có, marker TWT cho cả 10 giếng nên không phải mượn TD (TWT của pick là minh giải của operator, không phải đo độc lập); giếng lệch 30–86° nên phải ánh xạ quỹ đạo 3D vào trace; các giếng chung slot (F-1/1A/1B, F-11 A/T2) nên phải giữ lại theo nhóm khi CV."}, {id:"D-3", q:"Field thứ hai", p:"Volve.", n:"PHIF của Volve phụ thuộc density nên đáp ứng yêu cầu nhãn độc lập với sonic. Cube ST10010 có sẵn và khớp horizon. Marker TWT có cho cả 10 giếng nên không phải mượn dữ liệu thời gian–độ sâu (TWT của pick là minh giải của operator, không phải đo độc lập). Giếng nghiêng 30–86° nên phải chiếu quỹ đạo 3D lên trace. Các giếng chung slot (F-1/1A/1B, F-11 A/T2) phải được giữ cùng nhóm khi cross-validation."},
{id:"D-4", q:"Venue đích và ngưỡng các gate", p:"Geophysical Prospecting hoặc J. Applied Geophysics (giữ đề xuất)", n:"Quartile chưa tra."} {id:"D-4", q:"Venue đích và ngưỡng các cổng", p:"Geophysical Prospecting hoặc J. Applied Geophysics (giữ đề xuất).", n:"Chưa tra quartile."}
]; ];
const FINDS = [ const FINDS = [
{h:"Nhãn PHIE là hàm chính xác của density và sonic", p:"Ở F03-2, F03-4, F06-1: <b>PHIE = (2650 − RHOB)/1600</b> (R² = 1.0000) và tuyến tính theo DT trong cửa sổ. Density của F03-4 và F06-1 là dự đoán của dGB, của F03-2 không đo trong cửa sổ."}, {h:"Nhãn porosity của F3 thực chất là sonic đổi đơn vị", p:"Ở F03-2, F03-4, F06-1: <b>PHIE = (2650 − RHOB)/1600</b> chính xác (R² = 1.0000) và tuyến tính theo DT trong cửa sổ. Density của F03-4 và F06-1 là giá trị dGB dự đoán; F03-2 không có số đo density trong cửa sổ."},
{h:"F02-1 khác ba giếng còn lại", p:"PHIE bám RHOB đo thật (R² 0.84) nhưng không theo công thức tất định; phần còn lại không phải neutron (NPHI trên NLOG bắt đầu từ 1650 m). Split trộn F02-1 với giếng khác có label shift."}, {h:"F02-1 khác ba giếng còn lại", p:"PHIE bám RHOB đo thật (R² 0.84) nhưng không theo công thức tất định. Phần còn lại không giải thích được bằng neutron (NPHI trên NLOG chỉ bắt đầu từ 1650 m)."},
{h:"Nguồn TD không thống nhất", p:"DT_model trừ checkshot: <b>+40, +40, +25, −15 ms</b> (F02-1, F03-2, F03-4, F06-1). Mô hình .wlt khớp checkshot tốt hơn."}, {h:"Nhãn density và nhãn sonic khác nhau đáng kể", p:"φ_D = (2650 − RHOB đo)/1600 từ LAS của NLOG so với PHIE_DT trong 600–1100 ms: R² chỉ <b>0.27–0.59</b> ở F02-1, F03-4, F03-03, F03-06 (RMS 3.9–5.0 p.u.). RHOB demo ở F03-4 lệch RHOB đo (r 0.65, bias −63 kg/m³), xác nhận đây là density dự đoán. Ở F02-1, RHOB demo trùng RHOB đo (r 1.000). DT demo khác DT của NLOG (r 0.90–0.94)."},
{h:"Seismic F3 là dải tần cao", p:"Đỉnh <b>~60 Hz</b>, băng −20 dB khoảng <b>4–83 Hz</b>. Sai số TD 9–66 ms bằng 1–4 chu kỳ wavelet."}, {h:"Các nguồn thời gian–độ sâu không thống nhất", p:"DT_model trừ checkshot: <b>+40, +40, +25, −15 ms</b> (F02-1, F03-2, F03-4, F06-1). Mô hình .wlt khớp checkshot hơn."},
{h:"Làm mờ theo MSE mạnh hơn dự tính", p:"Với phổ thật, σ_δ = 8 ms chỉ giữ lại khoảng <b>6%</b> phương sai trong băng seismic (bảng 30 Hz cũ cho hệ số biên độ 0.32 ở 30 Hz)."}, {h:"Seismic F3 có tần số cao so với sai số căn chỉnh", p:"Đỉnh <b>~60 Hz</b>, băng −20 dB khoảng <b>4–83 Hz</b>, nên một chu kỳ khoảng 17–20 ms. Sai số thời gian–độ sâu 9–66 ms tương đương 1–4 chu kỳ wavelet."},
{h:"outputs/ của luận văn xác nhận vị trí giếng sai", p:"Patch seismic trong f3_wells_dataset.npz trùng <b>chính xác</b> với trace tại IL/XL của luận văn (362/821, 418/608, 283/842), không trùng vị trí thật. Nhãn dựng bằng tích phân DT không hiệu chỉnh; var(PHIE) F06-1 = 0.00139 như plan."}, {h:"Làm mờ do MSE mạnh hơn dự tính", p:"Với phổ thật, độ lệch ngẫu nhiên σ_δ = 8 ms chỉ giữ lại khoảng <b>6%</b> phương sai trong băng seismic (bảng giả định 30 Hz cũ cho hệ số biên độ 0.32 ở 30 Hz)."},
{h:"Checkpoint và dự đoán đã lưu là bản v1, không phải số trong luận văn", p:"open_loop_patch_best.pt có GRU 1 tầng, không có head_skip, nên không nạp được vào CNN–GRU v2. Chạy lại checkpoint cho đúng y_pred đã lưu (sai số 2·10⁻⁷). Dự đoán gần như hằng số (0.350–0.351, std ratio 0.001), <b>PCC 0.18</b>, R² −0.27; nhãn test bị dịch lag −2 mẫu ước lượng từ chính nhãn test. Không khớp PCC 0.34 / MSE 0.015 của luận văn: run cho ra các số đó không có trong outputs/."}, {h:"outputs/ của luận văn xác nhận giếng bị đặt sai chỗ", p:"Patch seismic trong f3_wells_dataset.npz trùng <b>chính xác</b> với trace tại IL/XL của luận văn (362/821, 418/608, 283/842), không phải vị trí giếng thật. Nhãn dựng bằng tích phân DT không hiệu chỉnh drift; var(PHIE) của F06-1 = 0.00139, đúng như plan."},
{h:"Không baseline nào hơn trend nén chặt", p:"LOWO, nhãn PHIE_DT: trend tuyến tính theo TWT (B0a) có RMSE <b>2.48 p.u.</b>; tốt nhất còn lại là Ridge trên attribute (2.58) và B3b (2.82 ± 0.21). PCC tổng 0.8 chủ yếu đến từ băng thấp; PCC trong băng seismic chỉ −0.13 đến 0.24."}, {h:"Checkpoint đã lưu không phải mô hình cho ra số trong luận văn", p:"open_loop_patch_best.pt là bản v1 (GRU 1 tầng, không có head_skip), không nạp được vào CNN–GRU v2. Chạy lại checkpoint cho đúng y_pred đã lưu (sai số 2·10⁻⁷): dự đoán gần như hằng số (0.350–0.351, std ratio 0.001), <b>PCC 0.18</b>, R² −0.27. Nhãn test còn bị dịch lag −2 mẫu ước lượng từ chính nhãn test. Không tái tạo được PCC 0.34 / MSE 0.015 của luận văn, vì run cho ra các số đó không có trong outputs/."},
{h:"Tie F3 yếu, misregistration không đo được ở mức T/8", p:"Tie tốt nhất từng giếng r = 0.33–0.70; pha hằng tốt nhất khác nhau tới 250° giữa các giếng. Lệch cục bộ còn lại 6–14 ms nhưng ngưỡng nhiễu của phép đo là 8–14 ms, nên không phân biệt được với 0, cũng không chứng minh được < 2.5 ms."}, {h:"Không baseline nào hơn đường xu hướng nén chặt", p:"LOWO, nhãn PHIE_DT: đường xu hướng theo TWT (B0a) có RMSE <b>2.48 p.u.</b>; tiếp theo là Ridge trên attribute (2.58) và B3b (2.82 ± 0.21). PCC tổng khoảng 0.8 chủ yếu đến từ băng thấp; trong băng seismic chỉ từ −0.13 đến 0.24."},
{h:"B1 (inversion cổ điển) yếu hơn dự kiến", p:"RMSE 3.60 p.u., PCC 0.44. In-sample (wavelet của chính giếng) băng seismic khôi phục r = 0.25–0.65; ngoài mẫu mất vì wavelet ước lượng từ giếng khác không khớp pha. Vòng inner luôn chọn damping lớn nhất. Rủi ro R2 (B1 thắng DL) chưa xảy ra."}, {h:"Tie trên F3 yếu; sai lệch còn lại không đo được ở mức 1/8 chu kỳ", p:"Tương quan tie tốt nhất từng giếng r = 0.33–0.70; pha tốt nhất khác nhau tới 250° giữa các giếng. Lệch cục bộ còn lại 6–14 ms, nhưng ngưỡng nhiễu của phép đo là 8–14 ms. Vì vậy không phân biệt được với 0, cũng không chứng minh được dưới 2.5 ms."},
{h:"σ của B3 quá tự tin", p:"Head heteroscedastic học trên 3 chuỗi cho σ trung bình 0.44 p.u. trong khi RMSE ≈ 2.9 p.u.: coverage 90% chỉ đạt <b>0.17</b>. Cần ensemble/B5 trước khi so calibration (H3)."}, {h:"Inversion cổ điển (B1) yếu hơn dự kiến", p:"RMSE 3.60 p.u., PCC 0.44. Khi dùng wavelet của chính giếng (in-sample), băng seismic khôi phục được r = 0.25–0.65. Ngoài mẫu thì mất, vì wavelet ước lượng từ giếng khác không khớp pha. Vòng chọn tham số bên trong luôn chọn damping lớn nhất. Rủi ro R2 (inversion cổ điển thắng deep learning) chưa xảy ra."},
{h:"Volve: well picks gỡ được blocker time–depth", p:"Cả 10 giếng D3 có <b>6–13 marker TWT</b> từ Ty đến Hugin/Skagerrak (2295–2807 ms), cùng loại anchor với marker F3. Pick không gắn cờ khớp horizon ST10010 trong ±10 ms ở BCU và Hugin; F-11 T2 lệch VSP −6 đến +4 ms. Pick nông (Utsira, Hordaland) lệch tới ~110 ms nên bỏ. Ở F-15 A pick trùng checkshot (0.0 ms) vì checkshot ghi MD từ MSL và pick được suy từ chính checkshot đó."}, {h:"Khoảng bất định của B3 quá tự tin", p:"Head bất định học trên 3 chuỗi cho σ trung bình 0.44 p.u., trong khi sai số thật RMSE ≈ 2.9 p.u. Khoảng 90% chỉ chứa giá trị thật <b>17%</b> số lần (coverage 0.17). Cần ensemble (B5) trước khi so calibration (H3)."},
{h:"Cube Volve: segyio đọc sai t0 thêm 8 ms", p:"Byte 215 của SEG-Y ghi 3, không phải scalar thời gian hợp lệ, nhưng segyio vẫn nhân delay 4 ms với nó nên báo mẫu đầu ở <b>12 ms</b>; EBCDIC ghi 4 ms. Lệch 8 ms cùng cỡ misregistration đang nghiên cứu. Đã sửa trong SeismicCube và kiểm bằng dữ liệu: biên độ trung bình dọc Ty, Shetland, BCU, Hugin top và base đạt cực trị ở lag 0 đến +2 ms. Toạ độ header khớp lưới horizon trong 0.15 m."}, {h:"Drift của F3 mô tả được bằng Gaussian process", p:"scripts/09, 62 marker ở 4 giếng: GP Matérn-3/2 trên g cho m_g = 0.014, σ_g = 0.10, ℓ = 71 ms, σ_b = 19 ms. Kiểm bằng cách bỏ từng anchor rồi dự đoán lại: z² trung bình 0.87, coverage 90% = 0.87, tức prior không quá tự tin. Riêng F02-1 kém (z² 1.8, coverage 0.65). Prior này, nhân với c, là drift của D2; ở c = 1, D2 có drift trung vị <b>39 ms</b> (F3: 13–46 ms)."},
{h:"Gunning & Glinsky (2006) đã có posterior time–depth", p:"Thời gian checkshot/marker là tham số có prior Gauss, ước lượng cùng wavelet, shift đăng ký và sai số định vị giếng; bất định theo Laplace. Bất định tie vì vậy không mới; khác biệt của đề tài vẫn là đưa posterior đó vào bước học. Anchor cứng của ta là giới hạn σ_t → 0; wavelet chung nhiều giếng là hướng xử lý cho B1."}, {h:"H1: mô hình MSE bị làm mờ đúng như Mệnh đề 1", p:"Huấn luyện MSE với nhãn lệch δ ~ N(0, σ²) trên D2 (c = 0, N = 16). Hàm truyền đo được chia cho lý thuyết exp(−2π²σ²f²) bằng <b>1.01</b> ở σ = 4, 8, 16 ms (CI 95% chứa 1) và 1.09 [1.05, 1.14] ở σ = 32 ms, nên H1 không bị bác. PCC băng giảm từ 0.91 xuống 0.39 khi σ tăng từ 4 lên 32 ms. Giới hạn: chỉ kiểm được dải 7–23 Hz (72% phổ chéo trong băng); ở σ = 32 ms chỉ còn 4 tần số."},
{h:"Nhãn density và nhãn sonic khác nhau đáng kể", p:"φ_D = (2650 − RHOB đo)/1600 từ LAS NLOG so với PHIE_DT trong 600–1100 ms: R² chỉ <b>0.27–0.59</b> ở F02-1, F03-4, F03-03, F03-06 (RMS 3.9–5.0 p.u.). RHOB demo ở F03-4 lệch RHOB đo (r 0.65, bias −63 kg/m³), xác nhận là density dự đoán; ở F02-1 trùng RHOB đo (r 1.000). DT demo khác DT NLOG (r 0.90–0.94)."}, {h:"Khoảng bất định co lại khi ít giếng (ghi nhận trước lưới chính)", p:"Ở dev, mọi loss có σ học được cho coverage 90% chỉ <b>0.10–0.66</b> và NLL 2.5–99 ở số bước đã chọn: với N ≤ 16 giếng, mạng nhớ nhãn train nên σ nhỏ quá mức. Không sửa trong P2 (đã ghi vào protocol_p2 trước khi chạy lưới). Metric calibration báo cáo nguyên trạng, và H3 chỉ là so sánh tương đối, cùng mạng và cùng cách lấy bất định."},
{h:"Volve phá vỡ cấu trúc PHIE = f(DT)", p:"PHIF phụ thuộc density: corr(PHIF, RHOB) từ −0.92 đến −0.99; thêm DT không cải thiện (≤ 0.009 R²). Giấy phép CC BY-NC-SA 4.0."} {h:"G-B không đạt: M2 không hơn cách căn chỉnh điểm tốt nhất", p:"Ở drift thực tế (c = 1), RMSE băng của M2 so với B3c là <b>0.985–1.045</b> (cần ≤ 0.90), ΔPCC băng từ −0.018 đến +0.003; không seed nào cải thiện đủ ngưỡng ở bất kỳ ô nào. Khi drift = 0, M2 kém B3d 1.5–5.6% (ngưỡng 2%). B3c là đối thủ tốt nhất ở mọi ô có drift; B3d ở mọi ô drift = 0."},
{h:"Phần lớn lợi ích đến từ căn chỉnh tốt, không phải từ marginalize", p:"RMSE băng ở c = 1 (trung bình theo N): B3a 1.47 → B3b 0.90 → B3c 0.70, B3d 0.74, M2 0.71 → Oracle 0.59 p.u. M2 thấp hơn B3b <b>12–28%</b> nhưng ngang B3c. So với nhãn warp trung bình của chính nó (B3d), M2 thấp hơn 3–14% khi c ≥ 1 và N ≥ 4, nhưng cao hơn 1.5–5.6% khi c = 0."},
{h:"Posterior căn chỉnh là nút thắt (rủi ro R6)", p:"Bank gồm 64 mẫu chỉ có điều kiện anchor, rồi đánh lại trọng số theo độ khớp seismic. Độ khớp này quá nhọn: ở γ = 1, ESS chỉ <b>≈ 1.0–1.2 trên 64</b>. Luật ESS ≥ S/4 vì vậy ép γ = 0.02–0.11, và M2 bỏ gần hết thông tin seismic. Sai số warp của M2 (3.2–4.5 ms khi c ≥ 1) không nhỏ hơn B3c (3.0–3.7 ms). Chẩn đoán sau G-B xác nhận và sửa được điểm này."},
{h:"Anchor là bắt buộc (H4)", p:"c = 1, N = 4: bỏ anchor làm sai số warp của M2 tăng <b>9.9×</b> (3.2 → 31 ms) và RMSE băng tăng 1.9× (PCC băng 0.85 → 0.24), dù biến thể không anchor được cho biết pha thật. Khớp Mệnh đề 2: không có anchor thì phép dịch chung không xác định."},
{h:"Loss chịu lệch không thay được căn chỉnh tốt", p:"B4a (hard-min ±8 mẫu) và B4b (soft-min) có RMSE băng 1.10–1.43 p.u., kém B3b (0.77–1.05) ở mọi ô. Soft-DTW (B4c) và DILATE (B4d) chỉ ngang B3b (chênh −7% đến +4%). Tie một điểm (B3a) xấu đi nhanh theo drift: 0.98 → 1.60 p.u. (trung bình theo N) khi c tăng từ 0 lên 2."},
{h:"Ngưỡng PCC +0.05 của G-B gần như không với tới", p:"Ở c = 1, ngay cả Oracle (biết warp thật) cũng chỉ hơn đối thủ tốt nhất <b>+0.035 đến +0.042</b> PCC băng khi N ≥ 4 (+0.064 ở N = 2). Ngưỡng RMSE thì còn chỗ: Oracle thấp hơn B3c 13–21%."},
{h:"H3 bị bác: M2-ens không calibrate tốt hơn B5", p:"Gộp các N ở c = 1: CE <b>0.278</b> (M2-ens) so với 0.230 (B5), ΔCE +0.048 [0.035, 0.061]. Khoảng hẹp hơn (0.85×), NLL kém hơn, CRPS ngang. Coverage 90% thực tế chỉ 0.46–0.80 với cả hai vì σ co lại (đã ghi nhận trước). CE tính trên mẫu thời gian nên chỉ dùng để so sánh tương đối."},
{h:"Volve phá vỡ cấu trúc \"porosity = hàm của sonic\"", p:"PHIF phụ thuộc density: corr(PHIF, RHOB) từ −0.92 đến −0.99; thêm DT không cải thiện (≤ 0.009 R²). Giấy phép CC BY-NC-SA 4.0."},
{h:"Well picks gỡ được vướng mắc về thời gian–độ sâu", p:"Cả 10 giếng D3 có <b>6–13 marker TWT</b> từ Ty đến Hugin/Skagerrak (2295–2807 ms), cùng loại anchor với marker F3. Pick không gắn cờ khớp horizon ST10010 trong ±10 ms ở BCU và Hugin; F-11 T2 lệch VSP −6 đến +4 ms. Pick nông (Utsira, Hordaland) lệch tới ~110 ms nên bỏ. Ở F-15 A, pick trùng checkshot (0.0 ms) vì checkshot ghi MD từ MSL và pick được suy từ chính checkshot đó."},
{h:"Cube Volve: segyio đọc sai mốc thời gian thêm 8 ms", p:"Byte 215 của SEG-Y ghi 3, không phải hệ số thời gian hợp lệ, nhưng segyio vẫn nhân delay 4 ms với nó, nên báo mẫu đầu ở <b>12 ms</b>; EBCDIC ghi 4 ms. Lệch 8 ms cùng cỡ với sai lệch đang nghiên cứu. Đã sửa trong SeismicCube và kiểm bằng dữ liệu: biên độ trung bình dọc Ty, Shetland, BCU, Hugin top và base đạt cực trị ở lag 0 đến +2 ms. Toạ độ header khớp lưới horizon trong 0.15 m."},
{h:"Gunning & Glinsky (2006) đã có posterior thời gian–độ sâu", p:"Thời gian checkshot/marker là tham số có prior Gauss, được ước lượng cùng wavelet, phép dịch căn chỉnh và sai số định vị giếng; bất định tính theo Laplace. Vậy bất định của tie không mới; điểm mới của đề tài là đưa posterior đó vào bước học. Anchor cứng của ta là giới hạn σ_t → 0; wavelet chung cho nhiều giếng là hướng xử lý cho B1."}
]; ];
const DATA = [ const DATA = [
{n:"F3 Demo 2023 (đầy đủ)", s:"done", note:"9.43 GB, 279 file tại data/F3_Demo_2023/; hash ở data_manifest/f3_demo_2023.json; .gitignore đã cập nhật. Bản lọc cũ ở ../_F3_Demo_2023_filtered_backup."}, {n:"F3 Demo 2023 (đầy đủ)", s:"done", note:"9.43 GB, 279 file tại data/F3_Demo_2023/; mã băm ở data_manifest/f3_demo_2023.json; .gitignore đã cập nhật. Bản lọc cũ ở ../_F3_Demo_2023_filtered_backup."},
{n:"Bộ dữ liệu giếng dẫn xuất", s:"done", note:"outputs/f3_wells.npz: patch 3×3 tại vị trí thật, 126 mẫu (600–1100 ms), 5 log × 4 TDR; tái tạo bằng scripts/01_build_wells.py trong khoảng 2 s."}, {n:"Bộ dữ liệu giếng dẫn xuất", s:"done", note:"outputs/f3_wells.npz: patch 3×3 trace tại vị trí giếng thật, 126 mẫu (600–1100 ms), 5 log × 4 TDR. Tái tạo bằng scripts/01_build_wells.py trong khoảng 2 s."},
{n:"F3 giếng: LAS, TD, markers, track", s:"done", note:"4 giếng F02-1, F03-2, F03-4, F06-1."}, {n:"F3 giếng: LAS, thời gian–độ sâu, marker, quỹ đạo", s:"done", note:"4 giếng F02-1, F03-2, F03-4, F06-1."},
{n:"NLOG footprint F3", s:"done", note:"docs/research/f3-nlog-inventory.xlsx. 11 file LAS và TZ của F02-1, F03-4, F03-03, F03-06 đã tải ngày 26/10 về data/NLOG/raw (hash ở data_manifest/nlog.json; không commit, tải lại theo URL trong xlsx)."}, {n:"NLOG trong vùng F3", s:"done", note:"docs/research/f3-nlog-inventory.xlsx. 11 file LAS và TZ của F02-1, F03-4, F03-03, F03-06 tải ngày 26/10 về data/NLOG/raw (mã băm ở data_manifest/nlog.json; không commit, tải lại theo URL trong xlsx)."},
{n:"Volve: giếng và log", s:"done", note:"data/Volve (bản sao y hệt ../volve_data/raw: cùng danh sách, kích thước và hash đã kiểm). 9 giếng có PHIF. Manifest data_manifest/volve.json: 28 738 file, 164.6 GB."}, {n:"Volve: giếng và log", s:"done", note:"data/Volve (bản sao y hệt ../volve_data/raw: cùng danh sách, kích thước và mã băm). 9 giếng có PHIF. Manifest data_manifest/volve.json: 28 738 file, 164.6 GB."},
{n:"Volve: cube seismic post-stack", s:"done", note:"data/Volve/Seismic/ST10010 (120 GB): Stacks có 18 SEG-Y, 16 GB (KIRCH và RAW, các stack góc, time và depth); Velocities có 6 SEG-Y; Prestack CIP gathers 104 GB, P4 không cần. Dùng KIRCH FULL_T (configs/d3_volve.yaml): IL 9961–10361, XL 1961–2680, 4–3400 ms, thiếu 26 trace ở rìa. 24 SEG-Y post-stack và velocity qua kiểm tra cấu trúc; kích thước prestack khớp danh sách của server."}, {n:"Volve: cube seismic post-stack", s:"done", note:"data/Volve/Seismic/ST10010 (120 GB). Stacks có 18 SEG-Y, 16 GB (KIRCH và RAW, các stack góc, time và depth); Velocities có 6 SEG-Y; Prestack CIP gathers 104 GB, P4 không cần. Dùng KIRCH FULL_T (configs/d3_volve.yaml): IL 9961–10361, XL 1961–2680, 4–3400 ms, thiếu 26 trace ở rìa. 24 SEG-Y post-stack và velocity qua kiểm tra cấu trúc; kích thước prestack khớp danh sách của server."},
{n:"Volve: horizon và well picks", s:"done", note:"data/Volve/Geophysical_Interpretations (hash ở data_manifest/volve.json): 32 horizon (lưới ST10010 12.5 m, affine khớp 0.0 m), 409 pick ở 35 giếng. Đọc bằng ml_porosity/data/volve_io.py."}, {n:"Volve: horizon và well picks", s:"done", note:"data/Volve/Geophysical_Interpretations (mã băm ở data_manifest/volve.json): 32 horizon (lưới ST10010 12.5 m, affine khớp 0.0 m), 409 pick ở 35 giếng. Đọc bằng ml_porosity/data/volve_io.py."},
{n:"Volve: toạ độ giếng và survey lệch", s:"done", note:"Compass ACTUAL, EDM.XML, WITSML trajectory; ED50 UTM31N, RKB 54.9 m."}, {n:"Volve: toạ độ giếng và quỹ đạo", s:"done", note:"Compass ACTUAL, EDM.XML, WITSML trajectory; ED50 UTM31N, RKB 54.9 m."},
{n:"Volve: time-depth", s:"done", note:"Checkshot: F-11 T2 (VSP, MD 2229–4530 m), F-15 A (MD từ MSL, 1067–3940 m). Marker TWT từ well picks: 6–13 điểm mỗi giếng cho cả 10 giếng, khoảng 2295–2807 ms."}, {n:"Volve: thời gian–độ sâu", s:"done", note:"Checkshot: F-11 T2 (VSP, MD 2229–4530 m), F-15 A (MD từ MSL, 1067–3940 m). Marker TWT từ well picks: 6–13 điểm mỗi giếng cho cả 10 giếng, khoảng 2295–2807 ms."},
{n:"outputs/ của luận văn", s:"todo", note:"Đã tải 26/10, hash ở data_manifest/thesis_outputs.json. Có dataset, checkpoint v1, dự đoán F06-1; file volume rỗng (0 byte), cần tải lại. Thiếu checkpoint và dự đoán _v2 ứng với số liệu trong luận văn."} {n:"outputs/ của luận văn", s:"todo", note:"Đã tải 26/10, mã băm ở data_manifest/thesis_outputs.json. Có dataset, checkpoint v1, dự đoán F06-1; file volume rỗng (0 byte), cần tải lại. Thiếu checkpoint và dự đoán _v2 ứng với số liệu trong luận văn."}
]; ];
// Macro 4 giếng, nhãn PHIE_DT, tham chiếu calibrated; mean ± sd theo 5 seed (protocol v2, sha256 c1c77195…) // Macro 4 giếng, nhãn PHIE_DT, tham chiếu calibrated; mean ± sd theo 5 seed (protocol v2, sha256 c1c77195…)
const P1RESULTS = [ const P1RESULTS = [
{m:"B0a trend TWT", rmse:"2.48", pcc:"0.81", band:"−0.13", skill:"0", wlt:"2.54"}, {m:"B0a đường xu hướng", rmse:"2.48", pcc:"0.81", band:"−0.13", skill:"0", wlt:"2.54"},
{m:"B0b Ridge (attribute)", rmse:"2.58", pcc:"0.83", band:"0.24", skill:"−0.09", wlt:"2.60"}, {m:"B0b Ridge (attribute)", rmse:"2.58", pcc:"0.83", band:"0.24", skill:"−0.09", wlt:"2.60"},
{m:"B0b RF", rmse:"2.67 ± 0.01", pcc:"0.79", band:"−0.03", skill:"−0.22", wlt:"2.66"}, {m:"B0b random forest", rmse:"2.67 ± 0.01", pcc:"0.79", band:"−0.03", skill:"−0.22", wlt:"2.66"},
{m:"B0b GBM", rmse:"2.68", pcc:"0.78", band:"0.01", skill:"−0.20", wlt:"2.67"}, {m:"B0b GBM", rmse:"2.68", pcc:"0.78", band:"0.01", skill:"−0.20", wlt:"2.67"},
{m:"B1 inversion PyLops", rmse:"3.60", pcc:"0.44", band:"−0.02", skill:"−1.29", wlt:"3.35"}, {m:"B1 inversion cổ điển (PyLops)", rmse:"3.60", pcc:"0.44", band:"−0.02", skill:"−1.29", wlt:"3.35"},
{m:"B2 CNN–GRU v2, loss gốc", rmse:"3.07 ± 0.16", pcc:"0.52 ± 0.06", band:"0.15", skill:"−0.65", wlt:"3.15"}, {m:"B2 mô hình luận văn, loss gốc", rmse:"3.07 ± 0.16", pcc:"0.52 ± 0.06", band:"0.15", skill:"−0.65", wlt:"3.15"},
{m:"B3a NLL, tie tích phân DT", rmse:"2.93 ± 0.24", pcc:"0.62 ± 0.13", band:"−0.02", skill:"−0.47", wlt:"3.06"}, {m:"B3a tie một điểm (tích phân DT)", rmse:"2.93 ± 0.24", pcc:"0.62 ± 0.13", band:"−0.02", skill:"−0.47", wlt:"3.06"},
{m:"B3b NLL, tie calibrated", rmse:"2.82 ± 0.21", pcc:"0.68 ± 0.12", band:"0.15", skill:"−0.36", wlt:"2.90"} {m:"B3b tie theo marker (calibrated)", rmse:"2.82 ± 0.21", pcc:"0.68 ± 0.12", band:"0.15", skill:"−0.36", wlt:"2.90"}
];
// P2, lưới D2 chính (protocol_p2, sha256 07336200…); sinh từ outputs/p2/summary/main/{cells,methods}.csv, n_boot 2000
const P2CELLS = [
{c:"0", n:2, best:"B3d", ratio:"1.015", ci:"0.966–1.069", dpcc:"−0.004", seeds:"0/5", rids:"0/8", pass:false},
{c:"0", n:4, best:"B3d", ratio:"1.045", ci:"1.012–1.073", dpcc:"−0.010", seeds:"0/5", rids:"0/8", pass:false},
{c:"0", n:8, best:"B3d", ratio:"1.051", ci:"1.028–1.076", dpcc:"−0.006", seeds:"0/5", rids:"0/8", pass:false},
{c:"0", n:16, best:"B3d", ratio:"1.056", ci:"1.041–1.075", dpcc:"−0.006", seeds:"0/5", rids:"0/8", pass:false},
{c:"0.5", n:2, best:"B3c", ratio:"1.023", ci:"0.955–1.100", dpcc:"−0.003", seeds:"0/5", rids:"1/8", pass:false},
{c:"0.5", n:4, best:"B3c", ratio:"1.018", ci:"0.977–1.074", dpcc:"−0.003", seeds:"0/5", rids:"0/8", pass:false},
{c:"0.5", n:8, best:"B3c", ratio:"1.010", ci:"0.980–1.047", dpcc:"+0.000", seeds:"0/5", rids:"0/8", pass:false},
{c:"0.5", n:16, best:"B3c", ratio:"0.991", ci:"0.969–1.019", dpcc:"+0.004", seeds:"0/5", rids:"0/8", pass:false},
{c:"1", n:2, best:"B3c", ratio:"1.045", ci:"0.961–1.144", dpcc:"−0.018", seeds:"0/5", rids:"2/8", pass:false},
{c:"1", n:4, best:"B3c", ratio:"1.025", ci:"0.992–1.063", dpcc:"−0.006", seeds:"0/5", rids:"0/8", pass:false},
{c:"1", n:8, best:"B3c", ratio:"1.020", ci:"0.987–1.054", dpcc:"−0.005", seeds:"0/5", rids:"0/8", pass:false},
{c:"1", n:16, best:"B3c", ratio:"0.985", ci:"0.941–1.028", dpcc:"+0.003", seeds:"0/5", rids:"1/8", pass:false},
{c:"2", n:2, best:"B3c", ratio:"1.078", ci:"1.024–1.128", dpcc:"−0.041", seeds:"0/5", rids:"0/8", pass:false},
{c:"2", n:4, best:"B3c", ratio:"1.035", ci:"0.989–1.082", dpcc:"−0.010", seeds:"0/5", rids:"0/8", pass:false},
{c:"2", n:8, best:"B3c", ratio:"1.066", ci:"1.048–1.097", dpcc:"−0.017", seeds:"0/5", rids:"0/8", pass:false},
{c:"2", n:16, best:"B3c", ratio:"1.006", ci:"0.973–1.039", dpcc:"−0.004", seeds:"0/5", rids:"0/8", pass:false}
];
const P2METHODS = [
{m:"Oracle (biết warp thật)", b:["0.587", "0.589", "0.586", "0.596"], pcc1:"0.901"},
{m:"B3a tie một điểm", b:["0.983", "1.244", "1.470", "1.604"], pcc1:"0.215"},
{m:"B3b tie theo marker", b:["0.903", "0.907", "0.905", "0.912"], pcc1:"0.746"},
{m:"B3c B3b + dịch cục bộ", b:["0.671", "0.690", "0.698", "0.730"], pcc1:"0.856"},
{m:"B3d nhãn warp trung bình của M2", b:["0.600", "0.701", "0.744", "0.813"], pcc1:"0.835"},
{m:"B4a hard-min ±8 mẫu", b:["1.292", "1.293", "1.285", "1.312"], pcc1:"0.433"},
{m:"B4b soft-min", b:["1.271", "1.266", "1.262", "1.258"], pcc1:"0.458"},
{m:"B4c soft-DTW", b:["0.904", "0.903", "0.905", "0.899"], pcc1:"0.741"},
{m:"B4d DILATE", b:["0.898", "0.899", "0.902", "0.899"], pcc1:"0.744"},
{m:"M1 RML, trọng số đều", b:["0.676", "0.736", "0.756", "0.799"], pcc1:"0.826"},
{m:"M2 RML, trọng số vật lý", b:["0.623", "0.698", "0.714", "0.766"], pcc1:"0.849"}
];
// Chẩn đoán sau G-B trên dev 900/901 (không phải lưới chính); sinh từ outputs/p2/diag/{posterior_gpu/warp.csv, train/}
const DGPOST = [
{c:"0", n:4, ph:"15° → 1.7°", m2:"1.33", b3c:"3.76", b3cr:"3.48", acf_old:"0.82", acf:"0.24", one:"0.27", ceil:"0.23", cov:"0.97 / 1.1", cov1:"0.80 / 0.8"},
{c:"0", n:16, ph:"8° → 1.4°", m2:"0.90", b3c:"3.83", b3cr:"3.72", acf_old:"0.49", acf:"0.20", one:"0.23", ceil:"0.20", cov:"0.97 / 0.9", cov1:"0.84 / 0.7"},
{c:"1", n:4, ph:"22° → 2.5°", m2:"3.40", b3c:"4.16", b3cr:"3.80", acf_old:"1.32", acf:"0.58", one:"0.51", ceil:"0.61", cov:"0.94 / 2.3", cov1:"0.81 / 1.4"},
{c:"1", n:16, ph:"0° → 3.5°", m2:"3.21", b3c:"3.77", b3cr:"3.77", acf_old:"0.55", acf:"0.56", one:"0.53", ceil:"0.55", cov:"0.98 / 2.9", cov1:"0.86 / 1.6"},
{c:"2", n:4, ph:"22° → 6.1°", m2:"5.19", b3c:"4.36", b3cr:"4.10", acf_old:"2.69", acf:"1.98", one:"1.43", ceil:"1.98", cov:"0.90 / 5.3", cov1:"0.73 / 2.0"},
{c:"2", n:16, ph:"15° → 5.2°", m2:"4.87", b3c:"3.82", b3cr:"3.66", acf_old:"1.86", acf:"1.54", one:"0.87", ceil:"1.53", cov:"0.94 / 4.7", cov1:"0.80 / 1.9"}
];
const DGTRAIN = [
{m:"Oracle (biết warp thật)", b:["0.610", "0.426", "0.608", "0.430", "0.604", "0.429"], pcc1:"0.886 / 0.944"},
{m:"B3c B3b + dịch cục bộ", b:["0.719", "0.553", "0.779", "0.563", "0.784", "0.569"], pcc1:"0.798 / 0.897"},
{m:"B3d nhãn warp trung bình của M2 cũ", b:["0.673", "0.447", "0.810", "0.592", "0.823", "0.705"], pcc1:"0.776 / 0.886"},
{m:"M2 RML, bank cũ", b:["0.645", "0.465", "0.814", "0.455", "0.866", "0.573"], pcc1:"0.791 / 0.935"},
{m:"M2@∞ bank cũ, λ = ∞", b:["0.880", "0.613", "0.932", "0.551", "0.929", "0.585"], pcc1:"0.717 / 0.905"},
{m:"B3c-R B3c, pha ước lượng lại", b:["0.694", "0.560", "0.721", "0.582", "0.734", "0.582"], pcc1:"0.823 / 0.890"},
{m:"B3d-Sa nhãn warp trung bình từ SMC (γ_acf)", b:["0.588", "0.427", "0.608", "0.421", "0.660", "0.486"], pcc1:"0.889 / 0.946"},
{m:"M2-Sa RML trên bank SMC (γ_acf)", b:["0.607", "0.410", "0.608", "0.431", "0.642", "0.447"], pcc1:"0.888 / 0.942"},
{m:"B3d-S1 nhãn warp trung bình từ SMC (γ = 1)", b:["0.599", "0.428", "0.606", "0.429", "0.644", "0.455"], pcc1:"0.888 / 0.942"},
{m:"M2-S1 RML trên bank SMC (γ = 1)", b:["0.605", "0.414", "0.624", "0.427", "0.631", "0.444"], pcc1:"0.891 / 0.943"},
{m:"M2-Sa@∞ bank SMC (γ_acf), λ = ∞", b:["0.643", "0.424", "0.613", "0.451", "0.639", "0.473"], pcc1:"0.888 / 0.938"}
];
const DGGATE = [
{m:"M2", set:"p2", best:"B3c", r1:"1.045 / 0.808", cells:"1/2", r0:"0.958 / 1.040", pass:false},
{m:"M2@1", set:"p2", best:"B3c", r1:"1.190 / 0.907", cells:"0/2", r0:"1.112 / 0.986", pass:false},
{m:"M2@3", set:"p2", best:"B3c", r1:"1.204 / 0.942", cells:"0/2", r0:"1.300 / 1.145", pass:false},
{m:"M2@∞", set:"p2", best:"B3c", r1:"1.196 / 0.979", cells:"0/2", r0:"1.308 / 1.373", pass:false},
{m:"M2-Se", set:"p2", best:"B3c", r1:"0.882 / 0.806", cells:"1/2", r0:"0.957 / 1.044", pass:false},
{m:"M2-Se", set:"full", best:"B3d-Se", r1:"1.004 / 1.045", cells:"0/2", r0:"0.989 / 1.044", pass:false},
{m:"M2-Sa", set:"p2", best:"B3c", r1:"0.781 / 0.766", cells:"2/2", r0:"0.902 / 0.917", pass:true},
{m:"M2-Sa", set:"full", best:"B3d-Sa", r1:"1.000 / 1.024", cells:"0/2", r0:"1.031 / 0.958", pass:false},
{m:"M2-S1", set:"p2", best:"B3c", r1:"0.801 / 0.758", cells:"2/2", r0:"0.899 / 0.927", pass:true},
{m:"M2-S1", set:"full", best:"B3d-S1", r1:"1.028 / 0.995", cells:"0/2", r0:"1.010 / 0.967", pass:false},
{m:"M2-Sa@1", set:"p2", best:"B3c", r1:"0.810 / 0.793", cells:"2/2", r0:"0.924 / 0.957", pass:true},
{m:"M2-Sa@1", set:"full", best:"B3d-Sa", r1:"1.037 / 1.061", cells:"0/2", r0:"1.057 / 1.001", pass:false},
{m:"M2-Sa@3", set:"p2", best:"B3c", r1:"0.799 / 0.760", cells:"2/2", r0:"0.938 / 0.928", pass:true},
{m:"M2-Sa@3", set:"full", best:"B3d-Sa", r1:"1.023 / 1.017", cells:"0/2", r0:"1.073 / 0.970", pass:false},
{m:"M2-Sa@∞", set:"p2", best:"B3c", r1:"0.787 / 0.801", cells:"2/2", r0:"0.955 / 0.949", pass:true},
{m:"M2-Sa@∞", set:"full", best:"B3d-Sa", r1:"1.008 / 1.071", cells:"0/2", r0:"1.092 / 0.992", pass:false}
]; ];
const CHECKS = [ const CHECKS = [
{item:"IL/XL thật của 4 giếng", plan:"362/336, 722/848, 442/1007, 244/387", code:"Khớp chính xác"}, {item:"IL/XL thật của 4 giếng", plan:"362/336, 722/848, 442/1007, 244/387", code:"Khớp chính xác"},
{item:"Độ lệch vị trí của luận văn", plan:"6.94, 5.05, 11.42 km", code:"Khớp chính xác"}, {item:"Luận văn đặt giếng lệch bao xa", plan:"6.94, 5.05, 11.42 km", code:"Khớp chính xác"},
{item:"Số anchor trong 600–1100 ms", plan:"11, 9, 9, 10", code:"Khớp chính xác"}, {item:"Số anchor trong 600–1100 ms", plan:"11, 9, 9, 10", code:"Khớp chính xác"},
{item:"Tích phân DT (luận văn) − marker", plan:"+2→−44, −3→−14, −42→−52, −21→−66 ms", code:"Khớp sau khi làm tròn tới 1 ms"}, {item:"Tích phân DT (luận văn) − marker", plan:"+2→−44, −3→−14, −42→−52, −21→−66 ms", code:"Khớp sau khi làm tròn tới 1 ms"},
{item:".wlt − marker, max |Δ|", plan:"28.5, 10.2, 9.2, 36.4 ms", code:"28.6, 9.6, 8.8, 36.5 ms (lệch ≤ 0.6 ms, có thể do cách nội suy)"}, {item:".wlt − marker, |Δ| lớn nhất", plan:"28.5, 10.2, 9.2, 36.4 ms", code:"28.6, 9.6, 8.8, 36.5 ms (lệch ≤ 0.6 ms, có thể do cách nội suy)"},
{item:"DT_model − checkshot, trung bình", plan:"+40.5, +40.2, +25.2, −14.6 ms", code:"Khớp chính xác"}, {item:"DT_model − checkshot, trung bình", plan:"+40.5, +40.2, +25.2, −14.6 ms", code:"Khớp chính xác"},
{item:"L_shape = 2·L_PCC − 2/L", plan:"mục 1.1 #7", code:"Đúng (test_models.py)"}, {item:"L_shape = 2·L_PCC − 2/L (hai loss của luận văn trùng nhau)", plan:"mục 1.1 #7", code:"Đúng (test_models.py)"},
{item:"Hash dữ liệu so với manifest cũ", plan:"101 file có SHA-256", code:"101/101 khớp"} {item:"Mã băm dữ liệu so với manifest cũ", plan:"101 file có SHA-256", code:"101/101 khớp"}
]; ];
const LOG = [ const LOG = [
["2026-10-26","Lập plan.md; kiểm tra novelty; kiểm tra trực tiếp dữ liệu F3."], ["2026-10-26","Lập plan.md; kiểm tra tính mới; kiểm tra trực tiếp dữ liệu F3."],
["2026-10-26","Xác minh dòng 89 và 96 (TD, PHIE F02-1), sửa công thức 1650 thành 1600."], ["2026-10-26","Xác minh dòng 89 và 96 của plan (thời gian–độ sâu, PHIE của F02-1); sửa công thức 1650 thành 1600."],
["2026-10-26","Kiểm kê NLOG (f3-nlog-inventory.xlsx) và Volve cục bộ; cập nhật D1, D3."], ["2026-10-26","Kiểm kê NLOG (f3-nlog-inventory.xlsx) và Volve cục bộ; cập nhật D1, D3."],
["2026-10-26","Tải F3 Demo 2023 đầy đủ, thay thư mục; đo phổ seismic; cập nhật mục 1.3, 2.3, 5.4."], ["2026-10-26","Tải F3 Demo 2023 đầy đủ, thay thư mục; đo phổ seismic; cập nhật plan mục 1.3, 2.3, 5.4."],
["2026-10-26","P0: gói ml_porosity/ (geometry, LAS, TDR, SEG-Y, resample, model và loss v2), scripts 00–03, manifest SHA-256, khóa môi trường, 41 unit test. Code tái tạo các số liệu mục 1.2a–c. Phát hiện delay 4 ms của SEG-Y. Còn thiếu outputs/ của luận văn."], ["2026-10-26","P0: gói ml_porosity/ (geometry, LAS, TDR, SEG-Y, resample, model và loss v2), scripts 00–03, manifest SHA-256, khoá môi trường, 41 unit test. Code tái tạo đúng số liệu plan mục 1.2a–c. Phát hiện delay 4 ms của SEG-Y. Còn thiếu outputs/ của luận văn."],
["2026-10-26","Kiểm tra outputs/ của luận văn: dataset xác nhận vị trí giếng sai; checkpoint và dự đoán là bản v1 (PCC 0.18, dự đoán gần hằng số), không khớp số trong luận văn; file volume rỗng."], ["2026-10-26","Kiểm tra outputs/ của luận văn: dataset xác nhận giếng đặt sai chỗ; checkpoint và dự đoán là bản v1 (PCC 0.18, dự đoán gần hằng số), không khớp số trong luận văn; file volume rỗng."],
["2026-10-26","P1: khoá protocol v2; wavelet và synthetic 4 giếng (tie r 0.33–0.70); misregistration không phân giải được dưới ngưỡng nhiễu 8–14 ms; kiểm kê Volve (không có cube); LOWO 5 seed cho B0a, B0b, B1, B2, B3a, B3b. Không baseline nào hơn trend. G-A: điều kiện pivot không thoả, chờ GVHD xác nhận."], ["2026-10-26","P1: khoá protocol v2; wavelet và synthetic 4 giếng (tie r 0.33–0.70); sai lệch còn lại không phân giải được dưới ngưỡng nhiễu 8–14 ms; kiểm kê Volve (lúc này chưa có cube); LOWO 5 seed cho B0a, B0b, B1, B2, B3a, B3b. Không baseline nào hơn đường xu hướng. G-A: điều kiện chuyển hướng không thoả, chờ GVHD xác nhận."],
["2026-10-26","Volve Geophysical_Interpretations và bài Gunning & Glinsky (2006): volve_io.py, scripts/07_volve_interp_qc.py, 5 test mới (52 pass). Marker TWT cho cả 10 giếng nên hết thiếu TD; chọn subset cube ST10010 (đang tải). F3 chuyển vào data/F3_Demo_2023/."], ["2026-10-26","Volve Geophysical_Interpretations và bài Gunning & Glinsky (2006): volve_io.py, scripts/07_volve_interp_qc.py, 5 test mới (52 pass). Marker TWT cho cả 10 giếng nên hết thiếu dữ liệu thời gian–độ sâu; chọn tập con cube ST10010 (đang tải). F3 chuyển vào data/F3_Demo_2023/."],
["2026-10-26","Cube ST10010 về: SeismicCube đọc được cube thiếu trace và bỏ qua scalar thời gian sai (t0 4 ms thay vì 12 ms); scripts/07 kiểm toạ độ và lag horizon (0 đến +2 ms); 1 test mới (53 pass)."], ["2026-10-26","Cube ST10010 về: SeismicCube đọc được cube thiếu trace và bỏ qua hệ số thời gian sai (t0 4 ms thay vì 12 ms); scripts/07 kiểm toạ độ và lag horizon (0 đến +2 ms); 1 test mới (53 pass)."],
["2026-10-26","D-1: tải 11 file LAS và TZ của NLOG; scripts/08_d1_label_check.py so φ_D (RHOB đo) với PHIE_DT: R² 0.27–0.59. Chốt PHIE_DT chính, PHIE phụ, giữ 4 giếng. Bỏ các bước chờ GVHD: G-A không pivot, sang P2; D-2 đến D-4 theo đề xuất."], ["2026-10-26","D-1: tải 11 file LAS và TZ của NLOG; scripts/08_d1_label_check.py so φ_D (RHOB đo) với PHIE_DT: R² 0.27–0.59. Chốt PHIE_DT là nhãn chính, PHIE phụ, giữ 4 giếng. Bỏ các bước chờ GVHD: G-A không chuyển hướng, sang P2; D-2 đến D-4 theo đề xuất."],
["2026-10-26","Toàn bộ Seismic/ST10010 về data/Volve (120 GB, kiểm tra cấu trúc SEG-Y đạt); config Volve đọc hết từ data/Volve; manifest Volve 28 738 file. Commit P0 + P1, tag protocol-v2."] ["2026-10-26","Toàn bộ Seismic/ST10010 về data/Volve (120 GB, kiểm tra cấu trúc SEG-Y đạt); config Volve đọc hết từ data/Volve; manifest Volve 28 738 file. Commit P0 + P1, tag protocol-v2."],
["2026-10-26","P2: docs/theory.md (Mệnh đề 1–2, Bổ đề 1–5, λ = 1/τ_c); prior warp GP fit trên marker F3 (scripts/09); bộ sinh D2 và QC (scripts/10); registration/ (prior GP, Laplace + elliptical slice, likelihood tie có pha, tempering theo ESS), RML M1/M2, B3c/B3d, B4a–d, B5; khoá protocol_p2 trước lưới chính. Lưới D2 128 ô trên cuda:1 (89 phút). G-B không đạt (c = 1: 0/4 ô; drift = 0: 1.039 so với ngưỡng 1.02); H1 không bị bác, H3 bị bác, H4 không bị bác. 90 test pass. Chưa commit."],
["2026-10-26","Chẩn đoán sau G-B trên dev 900/901: registration/smc.py (SMC tempering + elliptical slice, ước lượng lại pha, γ theo tự tương quan phần dư) và smc_torch.py trên cuda:1 (cùng luồng ngẫu nhiên, trùng bản numpy tới 1e-11, nhanh hơn bản GPU đầu khoảng 10 lần, có trần bộ nhớ mỗi worker); scripts/14–15. Sai số căn chỉnh về mức trần wavelet thật. Nhãn SMC đạt gate kiểu G-B với tập đối thủ của protocol_p2 (RMSE băng thấp hơn B3c 22–23% ở c = 1) nhưng không hơn nhãn warp trung bình cùng posterior (B3d-S), đúng như Mệnh đề 1. 103 test pass. Chưa khoá protocol mới, chưa commit."],
["2026-10-27","Viết docs/technical_overview.md (giải thích dự án cho người mới). Viết lại phần chữ của báo cáo này cho dễ đọc và gọn hơn; giữ nguyên cấu trúc và số liệu."],
["2026-10-27","Nén lịch: mục tiêu xong toàn bộ bài trước thứ 7, 31/10/2026 (thay lịch 24 tuần đến 02/05/2027). Chẩn đoán sau G-B đến hết 27/10; P3 F3 ngày 28/10 (G-C); P4 Volve 28–29/10 (G-D); viết 29–30/10; review và nộp 31/10. Ngưỡng các cổng giữ nguyên; thứ tự cắt phạm vi nếu trễ ghi ở plan §6. Cập nhật plan.md, technical_overview.md và báo cáo này. Thêm việc p2-p2r."],
["2026-10-27","Dev cho bản chạy lại P2 (H2a/H2b, ổn định SMC P = 1024, stress σ_a, H3 với posterior SMC, F3 trên trục σ_post) và khoá protocol. Bản khoá đầu tên protocol_p3, trùng với pha P3 F3 nên đổi thành protocol_p2r (P2 rerun) trước khi sinh realization 8–15. Thêm mục Chốt P2."],
["2026-10-27","Bắt đầu lưới chính P2r trên realization 8–15 (cuda:1): runner scripts/run_p2r_main.sh, tổng hợp scripts/18_summarize_p2r.py (chạy thử trên dev khớp số dev đã ghi trong protocol). Scripts 14/15 chỉ nhận 8–15 khi protocol_p2r và input khớp SHA-256. Sửa trạng thái công việc: lựa chọn thủ công lưu trong trình duyệt không còn che cập nhật mới trong DATA."]
]; ];
/* ===================== HẾT DATA ===================== */ /* ===================== HẾT DATA ===================== */
@@ -322,12 +466,20 @@ const KEY = "ml-porosity-progress-v1";
let saved = {}; let saved = {};
try { saved = JSON.parse(localStorage.getItem(KEY) || "{}"); } catch(e) {} try { saved = JSON.parse(localStorage.getItem(KEY) || "{}"); } catch(e) {}
function persist(){ try { localStorage.setItem(KEY, JSON.stringify(saved)); } catch(e) {} } function persist(){ try { localStorage.setItem(KEY, JSON.stringify(saved)); } catch(e) {} }
const stateOf = t => saved[t.id] || t.s; // A manual override is stored with the status in DATA at the time it was made ({s, base}); once DATA changes, the
// override no longer applies, so status updates in DATA are not masked. Legacy string overrides apply only while DATA is "todo".
const stateOf = t => { const v = saved[t.id];
if (v && typeof v === "object") return v.base === t.s ? v.s : t.s;
return (typeof v === "string" && t.s === "todo") ? v : t.s; };
const TASK = Object.fromEntries(PHASES.flatMap(p => p.tasks).map(t => [t.id, t]));
const $ = s => document.querySelector(s); const $ = s => document.querySelector(s);
const d = s => new Date(s + "T00:00:00"); const d = s => new Date(s + "T00:00:00");
const DAY = 864e5; const DAY = 864e5;
const total = (d(END) - d(START)) / DAY; const total = (d(END) - d(START)) / DAY + 1; // số ngày, tính cả ngày cuối
const pos = s => Math.max(0, Math.min(100, (d(s) - d(START)) / DAY / total * 100)); const posT = t => Math.max(0, Math.min(100, (t - d(START)) / DAY / total * 100));
const pos = s => posT(d(s)); // đầu ngày s
const posEnd = s => posT(d(s).getTime() + DAY); // cuối ngày s
const WD = ["CN","T2","T3","T4","T5","T6","T7"];
const fmt = s => d(s).toLocaleDateString("vi-VN", {day:"2-digit", month:"2-digit", year:"numeric"}); const fmt = s => d(s).toLocaleDateString("vi-VN", {day:"2-digit", month:"2-digit", year:"numeric"});
const now = new Date(); now.setHours(0,0,0,0); const now = new Date(); now.setHours(0,0,0,0);
const nowStr = now.getFullYear()+"-"+String(now.getMonth()+1).padStart(2,"0")+"-"+String(now.getDate()).padStart(2,"0"); const nowStr = now.getFullYear()+"-"+String(now.getMonth()+1).padStart(2,"0")+"-"+String(now.getDate()).padStart(2,"0");
@@ -344,13 +496,13 @@ function renderTiles(){
const done = all.filter(t => stateOf(t)==="done").length; const done = all.filter(t => stateOf(t)==="done").length;
const doing = all.filter(t => stateOf(t)==="doing").length; const doing = all.filter(t => stateOf(t)==="doing").length;
const blocked = all.filter(t => stateOf(t)==="blocked").length; const blocked = all.filter(t => stateOf(t)==="blocked").length;
const week = Math.min(24, Math.max(0, Math.floor((now - d(START)) / DAY / 7) + 1)); const day = Math.min(total, Math.max(0, Math.floor((now - d(START)) / DAY) + 1));
const xmDone = XM.filter(x => x.s==="done").length, xmLive = XM.filter(x => x.s!=="drop").length; const xmDone = XM.filter(x => x.s==="done").length, xmLive = XM.filter(x => x.s!=="drop").length;
const nextGate = PHASES.filter(p => p.gate && d(p.gate.date) >= now).map(p => p.gate)[0]; const nextGate = PHASES.filter(p => p.gate && !p.gate.res && d(p.gate.date) >= now).map(p => p.gate)[0];
const daysTo = nextGate ? Math.round((d(nextGate.date) - now) / DAY) : null; const daysTo = nextGate ? Math.round((d(nextGate.date) - now) / DAY) : null;
$("#tiles").innerHTML = ` $("#tiles").innerHTML = `
<div class="tile"><div class="k">Tuần hiện tại</div><div class="v">${week} / 24</div> <div class="tile"><div class="k">Ngày hiện tại</div><div class="v">${day} / ${total}</div>
<div class="n">${fmt(START)} đến ${fmt(END)}</div><div class="bar"><i style="width:${week/24*100}%"></i></div></div> <div class="n">${fmt(START)} đến ${fmt(END)} · xong bài trước T7</div><div class="bar"><i style="width:${day/total*100}%"></i></div></div>
<div class="tile"><div class="k">Công việc xong</div><div class="v">${done} / ${all.length}</div> <div class="tile"><div class="k">Công việc xong</div><div class="v">${done} / ${all.length}</div>
<div class="n">${doing} đang làm${blocked ? ", " + blocked + " bị chặn" : ""}</div><div class="bar"><i style="width:${done/all.length*100}%;background:var(--done)"></i></div></div> <div class="n">${doing} đang làm${blocked ? ", " + blocked + " bị chặn" : ""}</div><div class="bar"><i style="width:${done/all.length*100}%;background:var(--done)"></i></div></div>
<div class="tile"><div class="k">Mục [XM] đã xác minh</div><div class="v">${xmDone} / ${xmLive}</div> <div class="tile"><div class="k">Mục [XM] đã xác minh</div><div class="v">${xmDone} / ${xmLive}</div>
@@ -361,18 +513,18 @@ function renderTiles(){
} }
function renderGantt(){ function renderGantt(){
const months = []; const days = [];
for (let y=2026, m=9; ; m++){ if (m>11){m=0; y++;} const s = `${y}-${String(m+1).padStart(2,"0")}-01`; if (d(s) > d(END)) break; if (d(s) >= d(START)) months.push([s, d(s).toLocaleDateString("vi-VN",{month:"short"})]); } for (let i = 0; i < total; i++){ const t = new Date(d(START).getTime() + i * DAY); days.push([(i + 0.5) / total * 100, WD[t.getDay()] + " " + t.getDate() + "/" + (t.getMonth() + 1)]); }
let h = `<div class="months">${months.map(([s,l])=>`<span style="left:${pos(s)}%">${l}</span>`).join("")}</div>`; let h = `<div class="months">${days.map(([x,l])=>`<span style="left:${x}%">${l}</span>`).join("")}</div>`;
PHASES.forEach(p => { PHASES.forEach(p => {
const c = phaseCounts(p), pc = c.done / c.total * 100; const c = phaseCounts(p), pc = c.done / c.total * 100;
const a = pos(p.start), b = pos(p.end); const a = pos(p.start), b = posEnd(p.end);
h += `<div class="grow"><div class="lab">${p.id}<small>${p.weeks}</small></div><div class="track"> h += `<div class="grow"><div class="lab">${p.id}<small>${p.weeks}</small></div><div class="track">
<div class="seg" style="left:${a}%;width:${Math.max(b-a,0.8)}%" title="${p.name}: ${c.done}/${c.total}"><i style="width:${pc}%"></i></div> <div class="seg" style="left:${a}%;width:${Math.max(b-a,0.8)}%" title="${p.name}: ${c.done}/${c.total}"><i style="width:${pc}%"></i></div>
${p.gate ? `<div class="gate" style="left:${pos(p.gate.date)}%"><b>${p.gate.label}</b></div>` : ""} ${p.gate ? `<div class="gate" style="left:${posEnd(p.gate.date)}%"><b>${p.gate.label}</b></div>` : ""}
</div></div>`; </div></div>`;
}); });
h += `<div class="today" style="left:calc(150px + (100% - 150px) * ${pos(nowStr)/100})"><b>hôm nay</b></div>`; h += `<div class="today" style="left:calc(150px + (100% - 150px) * ${posT(Date.now())/100})"><b>bây giờ</b></div>`;
$("#gantt").innerHTML = h; $("#gantt").innerHTML = h;
} }
@@ -383,14 +535,14 @@ function renderPhases(){
return `<details class="phase" ${open?"open":""}> return `<details class="phase" ${open?"open":""}>
<summary><div><div class="t">${p.name}</div><div class="d">${p.weeks} · ${fmt(p.start)} đến ${fmt(p.end)} · đầu ra: ${p.out}</div></div> <summary><div><div class="t">${p.name}</div><div class="d">${p.weeks} · ${fmt(p.start)} đến ${fmt(p.end)} · đầu ra: ${p.out}</div></div>
<div class="pc">${c.done}/${c.total} xong</div> <div class="pc">${c.done}/${c.total} xong</div>
${p.gate ? `<div class="gatebox"><b>Cổng ${p.gate.label}</b> (${fmt(p.gate.date)}): ${p.gate.text}</div>` : ""}</summary> ${p.gate ? `<div class="gatebox"><b>Cổng ${p.gate.label}</b> (${fmt(p.gate.date)}): ${p.gate.text}${p.gate.res ? ` <b>Kết quả:</b> ${p.gate.res}` : ""}</div>` : ""}</summary>
<div class="tasks">${p.tasks.map(t => { const s = stateOf(t); return `<div class="task ${s}"> <div class="tasks">${p.tasks.map(t => { const s = stateOf(t); return `<div class="task ${s}">
<div class="tx"><span>${t.t}</span>${t.n ? `<span class="nt">${t.n}</span>` : ""}</div> <div class="tx"><span>${t.t}</span>${t.n ? `<span class="nt">${t.n}</span>` : ""}</div>
<select class="st ${s}" data-id="${t.id}" aria-label="Trạng thái: ${t.t}">${Object.entries(STATES).map(([k,v]) => `<option value="${k}" ${k===s?"selected":""}>${v}</option>`).join("")}</select></div>`; }).join("")}</div> <select class="st ${s}" data-id="${t.id}" aria-label="Trạng thái: ${t.t}">${Object.entries(STATES).map(([k,v]) => `<option value="${k}" ${k===s?"selected":""}>${v}</option>`).join("")}</select></div>`; }).join("")}</div>
</details>`; </details>`;
}).join(""); }).join("");
document.querySelectorAll("select.st").forEach(sel => sel.addEventListener("change", e => { document.querySelectorAll("select.st").forEach(sel => sel.addEventListener("change", e => {
saved[e.target.dataset.id] = e.target.value; persist(); renderAll(); const id = e.target.dataset.id; saved[id] = {s: e.target.value, base: TASK[id].s}; persist(); renderAll();
})); }));
} }
@@ -399,6 +551,11 @@ function renderStatic(){
$("#dec tbody").innerHTML = DECISIONS.map(x => `<tr><td><b>${x.id}</b></td><td>${x.q}</td><td>${x.p}</td><td>${x.n}</td></tr>`).join(""); $("#dec tbody").innerHTML = DECISIONS.map(x => `<tr><td><b>${x.id}</b></td><td>${x.q}</td><td>${x.p}</td><td>${x.n}</td></tr>`).join("");
$("#finds").innerHTML = FINDS.map(f => `<div class="card find"><h3>${f.h}</h3><p>${f.p}</p></div>`).join(""); $("#finds").innerHTML = FINDS.map(f => `<div class="card find"><h3>${f.h}</h3><p>${f.p}</p></div>`).join("");
$("#p1res tbody").innerHTML = P1RESULTS.map(x => `<tr><td>${x.m}</td><td>${x.rmse}</td><td>${x.pcc}</td><td>${x.band}</td><td>${x.skill}</td><td>${x.wlt}</td></tr>`).join(""); $("#p1res tbody").innerHTML = P1RESULTS.map(x => `<tr><td>${x.m}</td><td>${x.rmse}</td><td>${x.pcc}</td><td>${x.band}</td><td>${x.skill}</td><td>${x.wlt}</td></tr>`).join("");
$("#p2gb tbody").innerHTML = P2CELLS.map(x => `<tr><td>${x.c}</td><td>${x.n}</td><td>${x.best}</td><td>${x.ratio}</td><td>${x.ci}</td><td>${x.dpcc}</td><td>${x.seeds}</td><td>${x.rids}</td><td>${pill(x.pass?"done":"blocked", x.pass?"Đạt":"Trượt")}</td></tr>`).join("");
$("#p2m tbody").innerHTML = P2METHODS.map(x => `<tr><td>${x.m}</td>${x.b.map(v => `<td>${v}</td>`).join("")}<td>${x.pcc1}</td></tr>`).join("");
$("#dgpost tbody").innerHTML = DGPOST.map(x => `<tr><td>${x.c}</td><td>${x.n}</td><td>${x.ph}</td><td>${x.m2}</td><td>${x.b3c}</td><td>${x.b3cr}</td><td>${x.acf_old}</td><td><b>${x.acf}</b></td><td>${x.one}</td><td>${x.ceil}</td><td>${x.cov}</td><td>${x.cov1}</td></tr>`).join("");
$("#dgtrain tbody").innerHTML = DGTRAIN.map(x => `<tr><td>${x.m}</td>${x.b.map(v => `<td>${v}</td>`).join("")}<td>${x.pcc1}</td></tr>`).join("");
$("#dggate tbody").innerHTML = DGGATE.map(x => `<tr><td>${x.m}</td><td>${x.set}</td><td>${x.best}</td><td>${x.r1}</td><td>${x.cells}</td><td>${x.r0}</td><td>${pill(x.pass?"done":"blocked", x.pass?"Đạt":"Trượt")}</td></tr>`).join("");
$("#checks tbody").innerHTML = CHECKS.map(x => `<tr><td>${x.item}</td><td>${x.plan}</td><td>${x.code}</td></tr>`).join(""); $("#checks tbody").innerHTML = CHECKS.map(x => `<tr><td>${x.item}</td><td>${x.plan}</td><td>${x.code}</td></tr>`).join("");
$("#data tbody").innerHTML = DATA.map(x => `<tr><td>${x.n}</td><td>${pill(x.s, x.s==="done"?"Có":x.s==="doing"?"Đang tải":"Thiếu")}</td><td>${x.note}</td></tr>`).join(""); $("#data tbody").innerHTML = DATA.map(x => `<tr><td>${x.n}</td><td>${pill(x.s, x.s==="done"?"Có":x.s==="doing"?"Đang tải":"Thiếu")}</td><td>${x.note}</td></tr>`).join("");
$("#log").innerHTML = LOG.slice().reverse().map(([t,m]) => `<li><time>${fmt(t)}</time>${m}</li>`).join(""); $("#log").innerHTML = LOG.slice().reverse().map(([t,m]) => `<li><time>${fmt(t)}</time>${m}</li>`).join("");

View File

@@ -1,9 +1,9 @@
"""Ghi manifest SHA-256 cho một bộ dữ liệu và đối chiếu với manifest đã commit. """Write a SHA-256 manifest for a dataset and check it against the committed manifest.
python scripts/00_data_manifest.py # tạo/cập nhật manifest F3 python scripts/00_data_manifest.py # create/update the F3 manifest
python scripts/00_data_manifest.py --check # chỉ kiểm tra, exit 1 nếu lệch python scripts/00_data_manifest.py --check # check only; exit 1 on mismatch
python scripts/00_data_manifest.py --dataset volve # tương tự cho data/Volve python scripts/00_data_manifest.py --dataset volve # same for data/Volve
python scripts/00_data_manifest.py --dataset nlog # tương tự cho data/NLOG python scripts/00_data_manifest.py --dataset nlog # same for data/NLOG
""" """
from __future__ import annotations from __future__ import annotations
@@ -20,8 +20,8 @@ from ml_porosity.paths import REPO_ROOT, f3_root, nlog_root, volve_root
DATASETS = { DATASETS = {
"f3": (f3_root, "f3_demo_2023.json", "F3 Demo 2023 (dGB Earth Sciences / TerraNubis), CC BY-SA 3.0"), "f3": (f3_root, "f3_demo_2023.json", "F3 Demo 2023 (dGB Earth Sciences / TerraNubis), CC BY-SA 3.0"),
"volve": (volve_root, "volve.json", "Volve data village (Equinor), giấy phép HRS / CC BY-NC-SA 4.0"), "volve": (volve_root, "volve.json", "Volve data village (Equinor), HRS licence / CC BY-NC-SA 4.0"),
"nlog": (nlog_root, "nlog.json", "NLOG (TNO), LAS và TD công khai của giếng F3; URL ở docs/research/f3-nlog-inventory.xlsx"), "nlog": (nlog_root, "nlog.json", "NLOG (TNO), public LAS and TD data for the F3 wells; URLs in docs/research/f3-nlog-inventory.xlsx"),
} }
@@ -59,10 +59,10 @@ def main() -> int:
missing = sorted(set(ref) - set(current)) missing = sorted(set(ref) - set(current))
changed = sorted(k for k in set(ref) & set(current) if ref[k]["sha256"] != current[k]["sha256"]) changed = sorted(k for k in set(ref) & set(current) if ref[k]["sha256"] != current[k]["sha256"])
extra = sorted(set(current) - set(ref)) extra = sorted(set(current) - set(ref))
for name, items in (("thiếu", missing), ("khác hash", changed), ("thừa", extra)): for name, items in (("missing", missing), ("hash mismatch", changed), ("extra", extra)):
for k in items: for k in items:
print(f"{name}: {k}") print(f"{name}: {k}")
print(f"{len(current)} file, {len(missing)} thiếu, {len(changed)} khác hash, {len(extra)} thừa") print(f"{len(current)} files, {len(missing)} missing, {len(changed)} hash mismatch, {len(extra)} extra")
return 1 if (missing or changed) else 0 return 1 if (missing or changed) else 0
out = { out = {

View File

@@ -1,14 +1,14 @@
"""Dựng bộ dữ liệu giếng F3 trong miền thời gian seismic. """Build the F3 well dataset in the seismic time domain.
python scripts/01_build_wells.py [--config configs/d1_f3.yaml] python scripts/01_build_wells.py [--config configs/d1_f3.yaml]
Đầu ra (trong outputs/): Outputs (in outputs/):
f3_wells.npz khóa phẳng "<giếng>/<mục>", không cần allow_pickle. Mọi chuỗi theo thời gian f3_wells.npz flat keys "<well>/<item>", no allow_pickle needed. All time series lie on
nằm trên cửa sổ mở rộng `ext_window_ms`; `main_mask` đánh dấu cửa sổ chính: the extended window `ext_window_ms`; `main_mask` marks the main window:
seismic_patch (C, L), times_ms (L,), main_mask (L,), il, xl, x, y, seismic_patch (C, L), times_ms (L,), main_mask (L,), il, xl, x, y,
anchors_md, anchors_twt_ms, tdr/<tên>/md, tdr/<tên>/twt_ms, anchors_md, anchors_twt_ms, tdr/<name>/md, tdr/<name>/twt_ms,
<tên TDR>/<curve> (L,), horizon/<tên> (TWT ms tại giếng) <TDR name>/<curve> (L,), horizon/<name> (TWT ms at the well)
f3_wells_summary.json vị trí giếng (thật và của luận văn), số anchor, độ phủ nhãn. f3_wells_summary.json well locations (true and as used in the thesis), anchor counts, label coverage.
""" """
from __future__ import annotations from __future__ import annotations
@@ -43,7 +43,7 @@ def build_tdrs(well: Well, names: list[str]) -> dict[str, TDR]:
elif name == "wlt": elif name == "wlt":
out[name] = TDR.from_pairs(load_td_source(well.name, "wlt"), "wlt", drop_flat=True) out[name] = TDR.from_pairs(load_td_source(well.name, "wlt"), "wlt", drop_flat=True)
else: else:
raise ValueError(f"TDR không hỗ trợ: {name}") raise ValueError(f"unsupported TDR: {name}")
return out return out
@@ -64,7 +64,7 @@ def main() -> None:
main = (t_win >= t0) & (t_win <= t1) main = (t_win >= t0) & (t_win <= t1)
for name in cfg["wells"]: for name in cfg["wells"]:
w = load_well(name) w = load_well(name)
# Nhãn hài hoà theo plan mục 1.2d / D-1: PHIE_DT = −0.2018 + 0.0011·DT cho cả 4 giếng. # Harmonized label per plan §1.2d / D-1: PHIE_DT = −0.2018 + 0.0011·DT for all 4 wells.
w.logs["PHIE_DT"] = -0.2018 + 0.0011 * w.logs["DT"] w.logs["PHIE_DT"] = -0.2018 + 0.0011 * w.logs["DT"]
il, xl = geom.nearest_bin(w.x, w.y) il, xl = geom.nearest_bin(w.x, w.y)
patch = cube.patch(il, xl, cfg["patch_radius"])[:, win] patch = cube.patch(il, xl, cfg["patch_radius"])[:, win]
@@ -101,10 +101,10 @@ def main() -> None:
info["legacy_offset_km"] = round(float(np.hypot(lx - w.x, ly - w.y)) / 1000, 2) info["legacy_offset_km"] = round(float(np.hypot(lx - w.x, ly - w.y)) / 1000, 2)
summary["wells"][name] = info summary["wells"][name] = info
print(f"{name}: IL/XL {il}/{xl}" print(f"{name}: IL/XL {il}/{xl}"
+ (f" (luận văn {info['legacy_il_xl'][0]}/{info['legacy_il_xl'][1]}, lệch {info['legacy_offset_km']} km)" + (f" (thesis {info['legacy_il_xl'][0]}/{info['legacy_il_xl'][1]}, offset {info['legacy_offset_km']} km)"
if "legacy_il_xl" in info else "") if "legacy_il_xl" in info else "")
+ f", {info['n_anchors_in_window']} anchor trong cửa sổ, " + f", {info['n_anchors_in_window']} anchors in window, "
+ f"phủ PHIE (calibrated) {coverage.get('calibrated/PHIE', float('nan')):.0%}") + f"PHIE coverage (calibrated) {coverage.get('calibrated/PHIE', float('nan')):.0%}")
out = outputs_dir() out = outputs_dir()
np.savez_compressed(out / "f3_wells.npz", **arrays) np.savez_compressed(out / "f3_wells.npz", **arrays)

View File

@@ -1,8 +1,8 @@
"""QC các nguồn TD so với marker TD (bản nháp hình F2 và bảng mục 1.2b–c). """QC of the TD sources against the TD markers (draft of figure F2 and the tables in §1.2b–c).
python scripts/02_td_qc.py python scripts/02_td_qc.py
Đầu ra: outputs/figures/td_drift.png, outputs/td_qc.csv Outputs: outputs/figures/td_drift.png, outputs/td_qc.csv
""" """
from __future__ import annotations from __future__ import annotations
@@ -20,7 +20,7 @@ from ml_porosity.paths import outputs_dir
WINDOW_MS = (600.0, 1100.0) WINDOW_MS = (600.0, 1100.0)
SOURCES = { SOURCES = {
"legacy": "Tích phân DT (luận văn)", "legacy": "Integrated DT (thesis)",
"wlt": "OpendTect .wlt", "wlt": "OpendTect .wlt",
"dt_model": "DT_model", "dt_model": "DT_model",
} }
@@ -50,13 +50,13 @@ def main() -> None:
}) })
ax.axvline(0, color="k", lw=0.8) ax.axvline(0, color="k", lw=0.8)
ax.axhspan(*WINDOW_MS, color="#f0c040", alpha=0.15, lw=0) ax.axhspan(*WINDOW_MS, color="#f0c040", alpha=0.15, lw=0)
ax.set_title(f"{name} ({int(inwin.sum())} anchor trong cửa sổ)", fontsize=10) ax.set_title(f"{name} ({int(inwin.sum())} anchors in window)", fontsize=10)
ax.set_xlabel("TWT nguồn − TWT marker (ms)") ax.set_xlabel("source TWT − marker TWT (ms)")
ax.grid(alpha=0.3) ax.grid(alpha=0.3)
axes[0].set_ylabel("TWT marker (ms)") axes[0].set_ylabel("TWT marker (ms)")
axes[0].set_ylim(1300, 400) axes[0].set_ylim(1300, 400)
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=3, fontsize=9) fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=3, fontsize=9)
fig.suptitle("Lệch của các nguồn TD so với marker TD; dải vàng: cửa sổ 600–1100 ms", fontsize=11) fig.suptitle("Offset of the TD sources from the TD markers; yellow band: 600–1100 ms window", fontsize=11)
out = outputs_dir() out = outputs_dir()
(out / "figures").mkdir(exist_ok=True) (out / "figures").mkdir(exist_ok=True)

View File

@@ -1,10 +1,10 @@
"""Huấn luyện CNN–GRU v2 với loss gốc trên bộ dữ liệu từ 01_build_wells.py (B2). """Train CNN–GRU v2 with the original loss on the dataset from 01_build_wells.py (B2).
python scripts/03_train.py --config configs/b2_smoke.yaml [--epochs N] [--seed S] python scripts/03_train.py --config configs/b2_smoke.yaml [--epochs N] [--seed S]
So với `test 2/train_open_patch_v2.py`: vị trí giếng đúng, TDR chọn được, giếng validation Differences from `test 2/train_open_patch_v2.py`: correct well locations, selectable TDR, validation well
tách khỏi giếng train, không clip nhãn, không ước lượng lag bằng tương quan seismic–PHIE, separate from the train wells, no label clipping, no lag estimated from seismic–PHIE correlation,
metric tính ở thang thật. Đầu ra: outputs/runs/<tên config>_s<seed>/. metrics computed on the true scale. Outputs: outputs/runs/<config name>_s<seed>/.
""" """
from __future__ import annotations from __future__ import annotations
@@ -34,7 +34,7 @@ def load_split(D, wells: list[str], tdr: str, label: str):
X = np.stack([zscore_rows(D[f"{w}/seismic_patch"].astype(np.float64)) for w in wells]) X = np.stack([zscore_rows(D[f"{w}/seismic_patch"].astype(np.float64)) for w in wells])
Y = np.stack([D[f"{w}/{tdr}/{label}"] for w in wells]) Y = np.stack([D[f"{w}/{tdr}/{label}"] for w in wells])
if not np.all(np.isfinite(Y)): if not np.all(np.isfinite(Y)):
raise ValueError(f"nhãn {tdr}/{label} có NaN trong cửa sổ ở {wells}; cần chọn cửa sổ khác") raise ValueError(f"label {tdr}/{label} contains NaN in the window at {wells}; choose a different window")
return X, Y return X, Y
@@ -52,7 +52,7 @@ def main() -> None:
test, val, train = cfg["test_well"], cfg["val_well"], cfg["train_wells"] test, val, train = cfg["test_well"], cfg["val_well"], cfg["train_wells"]
if test in train or val in train or test == val: if test in train or val in train or test == val:
raise ValueError("giếng train, validation và test phải tách rời") raise ValueError("train, validation and test wells must be disjoint")
torch.manual_seed(cfg["seed"]) torch.manual_seed(cfg["seed"])
np.random.seed(cfg["seed"]) np.random.seed(cfg["seed"])
@@ -62,7 +62,7 @@ def main() -> None:
Xtr, Ytr = load_split(D, train, cfg["tdr"], cfg["label"]) Xtr, Ytr = load_split(D, train, cfg["tdr"], cfg["label"])
Xva, Yva = load_split(D, [val], cfg["tdr"], cfg["label"]) Xva, Yva = load_split(D, [val], cfg["tdr"], cfg["label"])
Xte, Yte = load_split(D, [test], cfg["tdr"], cfg["label"]) Xte, Yte = load_split(D, [test], cfg["tdr"], cfg["label"])
mu, sd = float(Ytr.mean()), float(Ytr.std() + 1e-8) # chỉ dùng thống kê train mu, sd = float(Ytr.mean()), float(Ytr.std() + 1e-8) # train statistics only
def T(a): def T(a):
return torch.tensor(a, dtype=torch.float32, device=device) return torch.tensor(a, dtype=torch.float32, device=device)
@@ -82,7 +82,7 @@ def main() -> None:
model.train() model.train()
opt.zero_grad() opt.zero_grad()
pred = model(xtr) pred = model(xtr)
if ep <= 50: # nhiễu nhỏ những epoch đầu như luận văn if ep <= 50: # small noise in the first epochs, as in the thesis
pred = pred + 0.01 * torch.randn_like(pred) pred = pred + 0.01 * torch.randn_like(pred)
loss = loss_fn(pred, ytr) loss = loss_fn(pred, ytr)
loss.backward() loss.backward()
@@ -105,7 +105,7 @@ def main() -> None:
yp = model(T(Xte)).cpu().numpy()[0, 0] * sd + mu yp = model(T(Xte)).cpu().numpy()[0, 0] * sd + mu
yt = Yte[0] yt = Yte[0]
m = point_metrics(yt, yp) m = point_metrics(yt, yp)
m_const = point_metrics(yt, np.full_like(yt, mu)) # dự đoán bằng trung bình train m_const = point_metrics(yt, np.full_like(yt, mu)) # prediction = train mean
result = {"config": cfg, "device": device, "best_epoch": best_ep, "best_val_loss": best, result = {"config": cfg, "device": device, "best_epoch": best_ep, "best_val_loss": best,
"train_seconds": round(time.time() - t_start, 1), "train_seconds": round(time.time() - t_start, 1),
@@ -113,7 +113,7 @@ def main() -> None:
(run_dir / "metrics.json").write_text(json.dumps(result, indent=1, ensure_ascii=False)) (run_dir / "metrics.json").write_text(json.dumps(result, indent=1, ensure_ascii=False))
np.savez_compressed(run_dir / "pred_test.npz", times_ms=D[f"{test}/times_ms"], y_true=yt, y_pred=yp) np.savez_compressed(run_dir / "pred_test.npz", times_ms=D[f"{test}/times_ms"], y_true=yt, y_pred=yp)
print(f"[test {test}] RMSE {m['rmse']:.4f} PCC {m['pcc']:.3f} R² {m['r2']:.2f} " print(f"[test {test}] RMSE {m['rmse']:.4f} PCC {m['pcc']:.3f} R² {m['r2']:.2f} "
f"(hằng số: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}") f"(constant: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}")
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -1,13 +1,13 @@
"""Wavelet, synthetic seismogram 4 giếng và misregistration còn lại sau tie (P1, cổng G-A). """Wavelets, synthetic seismograms for the 4 wells, and residual misregistration after the tie (P1, gate G-A).
python scripts/04_wavelet_tie.py python scripts/04_wavelet_tie.py
Với mỗi giếng và mỗi TDR: synthetic = wavelet ∗ r(AI theo TDR), so với trace seismic tại giếng. For each well and each TDR: synthetic = wavelet ∗ r(AI under the TDR), compared with the seismic trace at the well.
Báo cáo tương quan với pha chung ở shift 0, tie tốt nhất theo từng giếng (pha hằng + bulk shift) Reports the correlation with a common phase at zero shift, the best per-well tie (constant phase + bulk shift),
và lệch cục bộ còn lại sau tie tốt nhất (cửa sổ trượt 120 ms, chỉ tính cửa sổ có r > 0.5). and the residual local shift after the best tie (120 ms sliding window, only windows with r > 0.5 counted).
Phép đo dùng log của cả 4 giếng nên chỉ là QC/audit, không dùng cho huấn luyện. The measurement uses the logs of all 4 wells, so it is QC/audit only and is not used for training.
Đầu ra: outputs/tie_qc.csv, outputs/tie_local_shifts.csv, outputs/figures/ties.png, Outputs: outputs/tie_qc.csv, outputs/tie_local_shifts.csv, outputs/figures/ties.png,
outputs/figures/wavelets.png, outputs/wavelets.npz outputs/figures/wavelets.png, outputs/wavelets.npz
""" """
@@ -27,7 +27,7 @@ from ml_porosity.paths import outputs_dir
DT = 4.0 DT = 4.0
TDRS = ["calibrated", "wlt", "anchors", "legacy"] TDRS = ["calibrated", "wlt", "anchors", "legacy"]
F_DOM_HZ = 50.0 # tần số trội trung bình đo ở plan mục 2.3 (49–60 Hz) F_DOM_HZ = 50.0 # mean dominant frequency measured in plan §2.3 (49–60 Hz)
def main() -> None: def main() -> None:
@@ -39,18 +39,18 @@ def main() -> None:
def refl(w, tdr): def refl(w, tdr):
return reflectivity_from_ai(np.nan_to_num(D[f"{w}/{tdr}/AI"], nan=np.nanmean(D[f"{w}/{tdr}/AI"]))) return reflectivity_from_ai(np.nan_to_num(D[f"{w}/{tdr}/AI"], nan=np.nanmean(D[f"{w}/{tdr}/AI"])))
# Wavelet thống kê (chỉ seismic) và wavelet LS từ 4 giếng với tie calibrated. # Statistical wavelet (seismic only) and LS wavelet from the 4 wells with the calibrated tie.
w_stat = statistical_wavelet(np.stack([seis[w][main_m] for w in F3_WELLS]), DT) w_stat = statistical_wavelet(np.stack([seis[w][main_m] for w in F3_WELLS]), DT)
w_ls = estimate_wavelet_ls([refl(w, "calibrated")[main_m] for w in F3_WELLS], w_ls = estimate_wavelet_ls([refl(w, "calibrated")[main_m] for w in F3_WELLS],
[seis[w][main_m] for w in F3_WELLS], DT) [seis[w][main_m] for w in F3_WELLS], DT)
# Pha hằng chung cho wavelet thống kê: cực đại tương quan trung bình (calibrated, shift 0). # Common constant phase for the statistical wavelet: maximizes the mean correlation (calibrated, zero shift).
phases = np.arange(-180, 180, 5) phases = np.arange(-180, 180, 5)
score = [np.mean([ncc(convolve_same(refl(w, "calibrated"), rotate_phase(w_stat, p))[main_m], seis[w][main_m]) score = [np.mean([ncc(convolve_same(refl(w, "calibrated"), rotate_phase(w_stat, p))[main_m], seis[w][main_m])
for w in F3_WELLS]) for p in phases] for w in F3_WELLS]) for p in phases]
phase = float(phases[int(np.argmax(score))]) phase = float(phases[int(np.argmax(score))])
w_use = rotate_phase(w_stat, phase) w_use = rotate_phase(w_stat, phase)
print(f"Pha hằng tốt nhất của wavelet thống kê: {phase:+.0f}°, r trung bình {max(score):.3f}") print(f"Best constant phase of the statistical wavelet: {phase:+.0f}°, mean r {max(score):.3f}")
rows, lrows = [], [] rows, lrows = [], []
fig, axes = plt.subplots(1, 2 * len(F3_WELLS), figsize=(16, 8), sharey=True, fig, axes = plt.subplots(1, 2 * len(F3_WELLS), figsize=(16, 8), sharey=True,
@@ -63,7 +63,7 @@ def main() -> None:
for tdr in TDRS: for tdr in TDRS:
r_w = refl(w, tdr) r_w = refl(w, tdr)
r0 = ncc(convolve_same(r_w, w_use)[main_m], s[main_m]) r0 = ncc(convolve_same(r_w, w_use)[main_m], s[main_m])
# Tie tốt nhất theo từng giếng: pha hằng và bulk shift tìm đồng thời (lưới 10° × 0.5 ms). # Best per-well tie: constant phase and bulk shift searched jointly (10° × 0.5 ms grid).
best = (-np.inf, 0.0, 0.0) best = (-np.inf, 0.0, 0.0)
for p in range(-180, 180, 10): for p in range(-180, 180, 10):
syn_p = convolve_same(r_w, rotate_phase(w_stat, p)) syn_p = convolve_same(r_w, rotate_phase(w_stat, p))
@@ -73,7 +73,7 @@ def main() -> None:
best = (rr, float(p), float(sh)) best = (rr, float(p), float(sh))
r_best, p_best, sh_best = best r_best, p_best, sh_best = best
syn = shift_signal(convolve_same(r_w, rotate_phase(w_stat, p_best)), sh_best, DT) syn = shift_signal(convolve_same(r_w, rotate_phase(w_stat, p_best)), sh_best, DT)
# Lệch còn lại sau tie tốt nhất: lệch cục bộ của synthetic đã dịch bulk và xoay pha. # Residual shift after the best tie: local shift of the bulk-shifted, phase-rotated synthetic.
c, ls, lr = local_shifts(syn, s, DT, win_ms=120, hop_ms=20, max_ms=24) c, ls, lr = local_shifts(syn, s, DT, win_ms=120, hop_ms=20, max_ms=24)
tc = t[c] tc = t[c]
inwin = (tc >= t[main_m][0] + 60) & (tc <= t[main_m][-1] - 60) inwin = (tc >= t[main_m][0] + 60) & (tc <= t[main_m][-1] - 60)
@@ -83,8 +83,8 @@ def main() -> None:
"local_n": int(good.sum()), "local_n_total": int(inwin.sum()), "local_n": int(good.sum()), "local_n_total": int(inwin.sum()),
"local_rms_ms": round(float(np.sqrt(np.mean(ls[good] ** 2))), 1) if good.any() else np.nan, "local_rms_ms": round(float(np.sqrt(np.mean(ls[good] ** 2))), 1) if good.any() else np.nan,
"local_range_ms": round(float(np.ptp(ls[good])), 1) if good.any() else np.nan}) "local_range_ms": round(float(np.ptp(ls[good])), 1) if good.any() else np.nan})
# Ngưỡng nhiễu của phép đo: synthetic + nhiễu băng hạn chế (nhiễu trắng ∗ wavelet) sao cho # Noise floor of the measurement: synthetic + band-limited noise (white noise ∗ wavelet) such that
# tương quan toàn cục bằng r_best_tie; lệch thật = 0 nên RMS đo được là sai số của phép đo. # the global correlation equals r_best_tie; the true shift is 0, so the measured RMS is the measurement error.
rng = np.random.default_rng(0) rng = np.random.default_rng(0)
floor = [] floor = []
for _ in range(20): for _ in range(20):
@@ -107,7 +107,7 @@ def main() -> None:
ax_sh.axvline(0, color="k", lw=0.7) ax_sh.axvline(0, color="k", lw=0.7)
ax_sh.axvspan(-1000 / F_DOM_HZ / 8, 1000 / F_DOM_HZ / 8, color="#f0c040", alpha=0.3, lw=0) ax_sh.axvspan(-1000 / F_DOM_HZ / 8, 1000 / F_DOM_HZ / 8, color="#f0c040", alpha=0.3, lw=0)
ax_sh.set_xlim(-26, 26) ax_sh.set_xlim(-26, 26)
ax_sh.set_xlabel("lệch cục bộ (ms)", fontsize=8) ax_sh.set_xlabel("local shift (ms)", fontsize=8)
for a in (ax_tr, ax_sh): for a in (ax_tr, ax_sh):
a.axhspan(t[main_m][0], t[main_m][-1], color="#eee", zorder=-1, lw=0) a.axhspan(t[main_m][0], t[main_m][-1], color="#eee", zorder=-1, lw=0)
axes[0].set_ylim(t[-1], t[0]) axes[0].set_ylim(t[-1], t[0])
@@ -115,16 +115,16 @@ def main() -> None:
h1, l1 = axes[0].get_legend_handles_labels() h1, l1 = axes[0].get_legend_handles_labels()
h2, l2 = axes[1].get_legend_handles_labels() h2, l2 = axes[1].get_legend_handles_labels()
fig.legend(h1 + h2, l1 + l2, loc="outside lower center", ncol=7, fontsize=9) fig.legend(h1 + h2, l1 + l2, loc="outside lower center", ncol=7, fontsize=9)
fig.suptitle("Synthetic (tie tốt nhất từng giếng) vs seismic; " fig.suptitle("Synthetic (best per-well tie) vs seismic; "
"cột hẹp: lệch cục bộ còn lại, dải vàng ±T/8 ở 50 Hz", fontsize=11) "narrow column: residual local shift, yellow band ±T/8 at 50 Hz", fontsize=11)
out = outputs_dir() out = outputs_dir()
(out / "figures").mkdir(exist_ok=True) (out / "figures").mkdir(exist_ok=True)
fig.savefig(out / "figures" / "ties.png", dpi=130) fig.savefig(out / "figures" / "ties.png", dpi=130)
fw, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True) fw, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
tw = (np.arange(len(w_stat)) - len(w_stat) // 2) * DT tw = (np.arange(len(w_stat)) - len(w_stat) // 2) * DT
ax.plot(tw, w_use / np.abs(w_use).max(), label=f"thống kê, pha {phase:+.0f}°") ax.plot(tw, w_use / np.abs(w_use).max(), label=f"statistical, phase {phase:+.0f}°")
ax.plot(tw, w_ls / np.abs(w_ls).max(), label="LS từ 4 giếng (calibrated)") ax.plot(tw, w_ls / np.abs(w_ls).max(), label="LS from 4 wells (calibrated)")
ax.set_xlabel("ms") ax.set_xlabel("ms")
ax.legend() ax.legend()
ax.grid(alpha=0.3) ax.grid(alpha=0.3)
@@ -135,9 +135,9 @@ def main() -> None:
df.to_csv(out / "tie_qc.csv", index=False) df.to_csv(out / "tie_qc.csv", index=False)
pd.DataFrame(lrows).to_csv(out / "tie_local_shifts.csv", index=False) pd.DataFrame(lrows).to_csv(out / "tie_local_shifts.csv", index=False)
print(df.to_string(index=False)) print(df.to_string(index=False))
print(f"T/8 ở {F_DOM_HZ:.0f} Hz = {1000 / F_DOM_HZ / 8:.1f} ms") print(f"T/8 at {F_DOM_HZ:.0f} Hz = {1000 / F_DOM_HZ / 8:.1f} ms")
# Đối chiếu thời gian marker với horizon tại giếng (mốc thời gian SEG-Y, XM delay 4 ms). # Compare marker times with horizons at the wells (SEG-Y time datum, XM delay 4 ms).
names = {"FS8": "FS8", "FS7": "FS7", "Truncation": "Truncation 1", "FS6": "FS6", "MFS4": "MFS4"} names = {"FS8": "FS8", "FS7": "FS7", "Truncation": "Truncation 1", "FS6": "FS6", "MFS4": "MFS4"}
from ml_porosity.data.las_io import load_well from ml_porosity.data.las_io import load_well
hrows = [] hrows = []
@@ -155,7 +155,7 @@ def main() -> None:
hd = pd.DataFrame(hrows) hd = pd.DataFrame(hrows)
hd.to_csv(out / "marker_vs_horizon.csv", index=False) hd.to_csv(out / "marker_vs_horizon.csv", index=False)
print(hd.to_string(index=False)) print(hd.to_string(index=False))
print(f"horizon − marker: trung vị {hd.diff_ms.median():+.1f} ms, |Δ| trung vị {hd.diff_ms.abs().median():.1f} ms") print(f"horizon − marker: median {hd.diff_ms.median():+.1f} ms, median |Δ| {hd.diff_ms.abs().median():.1f} ms")
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -1,10 +1,10 @@
"""LOWO cho các baseline P1 theo configs/protocol.yaml (B0a, B0b, B1, B2, B3a, B3b). """LOWO for the P1 baselines per configs/protocol.yaml (B0a, B0b, B1, B2, B3a, B3b).
python scripts/05_lowo.py [--workers 12] [--device cuda] [--only B2,B3a] python scripts/05_lowo.py [--workers 12] [--device cuda] [--only B2,B3a]
Từ chối chạy nếu SHA-256 của protocol.yaml khác configs/protocol.sha256. Refuses to run if the SHA-256 of protocol.yaml differs from configs/protocol.sha256.
Đầu ra: outputs/p1/results.csv (mỗi dòng: method, label, test_well, seed, reference, metric), Outputs: outputs/p1/results.csv (one row per method, label, test_well, seed, reference, metric),
outputs/p1/preds.npz (μ, σ cho từng method/label/giếng/seed), outputs/p1/selection.csv. outputs/p1/preds.npz (μ, σ per method/label/well/seed), outputs/p1/selection.csv.
""" """
from __future__ import annotations from __future__ import annotations
@@ -30,7 +30,7 @@ def check_protocol() -> dict:
expected = (REPO_ROOT / "configs" / "protocol.sha256").read_text().split()[0] expected = (REPO_ROOT / "configs" / "protocol.sha256").read_text().split()[0]
actual = hashlib.sha256(PROTO.read_bytes()).hexdigest() actual = hashlib.sha256(PROTO.read_bytes()).hexdigest()
if actual != expected: if actual != expected:
raise SystemExit(f"protocol.yaml đã đổi sau khi khoá ({actual[:12]} ≠ {expected[:12]}); tạo phiên bản mới và khoá lại") raise SystemExit(f"protocol.yaml changed after locking ({actual[:12]} ≠ {expected[:12]}); create a new version and lock it again")
return yaml.safe_load(PROTO.read_text()) | {"sha256": actual} return yaml.safe_load(PROTO.read_text()) | {"sha256": actual}
@@ -44,7 +44,7 @@ class Data:
self.D = {k: D[k] for k in D.files} self.D = {k: D[k] for k in D.files}
def X(self, w): def X(self, w):
"""Patch z-score theo kênh trên cửa sổ chính, shape (C, L).""" """Per-channel z-scored patch over the main window, shape (C, L)."""
p = self.D[f"{w}/seismic_patch"][:, self.m].astype(np.float64) p = self.D[f"{w}/seismic_patch"][:, self.m].astype(np.float64)
return (p - p.mean(1, keepdims=True)) / (p.std(1, keepdims=True) + 1e-8) return (p - p.mean(1, keepdims=True)) / (p.std(1, keepdims=True) + 1e-8)
@@ -92,11 +92,11 @@ def run_classical(d: Data, label: str, test: str, seeds: list[int]):
def ytrain(ws): def ytrain(ws):
return np.concatenate([d.y(w, "calibrated", label) for w in ws]) return np.concatenate([d.y(w, "calibrated", label) for w in ws])
# B0a: trend tuyến tính theo TWT # B0a: linear trend in TWT
lr = LinearRegression().fit(np.tile(tt, len(train))[:, None], ytrain(train)) lr = LinearRegression().fit(np.tile(tt, len(train))[:, None], ytrain(train))
out.append(("B0a", -1, lr.predict(tt[:, None]), None)) out.append(("B0a", -1, lr.predict(tt[:, None]), None))
# B0b: attribute từ trace trung bình của patch (z-score), tính trên cửa sổ mở rộng # B0b: attributes from the patch mean trace (z-scored), computed on the extended window
def feats(w): def feats(w):
p = d.ext(w, "seismic_patch").astype(float) p = d.ext(w, "seismic_patch").astype(float)
p = (p - p[:, d.m].mean(1, keepdims=True)) / (p[:, d.m].std(1, keepdims=True) + 1e-8) p = (p - p[:, d.m].mean(1, keepdims=True)) / (p[:, d.m].std(1, keepdims=True) + 1e-8)
@@ -178,7 +178,7 @@ def run_cnn(job):
Y = np.stack([d.y(w, tdr_train, label) for w in ws]) Y = np.stack([d.y(w, tdr_train, label) for w in ws])
return X, Y return X, Y
# vòng inner: chọn epoch # inner loop: epoch selection
curves = [] curves = []
for v in train: for v in train:
tr2 = [w for w in train if w != v] tr2 = [w for w in train if w != v]
@@ -187,7 +187,7 @@ def run_cnn(job):
Xv, Yv = XY([v]) Xv, Yv = XY([v])
_, c = train_cnn(Xa, (Ya - mu_) / sd_, cfg, kind, seed, cfg["max_epochs"], device, _, c = train_cnn(Xa, (Ya - mu_) / sd_, cfg, kind, seed, cfg["max_epochs"], device,
Xv, (Yv - mu_) / sd_, cfg["eval_every"]) Xv, (Yv - mu_) / sd_, cfg["eval_every"])
curves.append([m * sd_**2 for _, m in c]) # MSE theo đơn vị nhãn gốc curves.append([m * sd_**2 for _, m in c]) # MSE in original label units
eps = [e for e, _ in c] eps = [e for e, _ in c]
best_ep = int(eps[int(np.argmin(np.mean(curves, axis=0)))]) best_ep = int(eps[int(np.argmin(np.mean(curves, axis=0)))])
@@ -235,7 +235,7 @@ def main() -> None:
sel += s sel += s
for method, seed, mu, sigma in out: for method, seed, mu, sigma in out:
record(method, label, test, seed, mu, sigma) record(method, label, test, seed, mu, sigma)
print(f"B0a/B0b/B1 xong sau {time.time() - t0:.0f} s") print(f"B0a/B0b/B1 done after {time.time() - t0:.0f} s")
cnn = [m for m in ("B2", "B3a", "B3b") if not only or m in only] cnn = [m for m in ("B2", "B3a", "B3b") if not only or m in only]
jobs = [(m, lab, w, s, args.device, proto) for m in cnn for lab in labels for w in d.wells for s in seeds] jobs = [(m, lab, w, s, args.device, proto) for m in cnn for lab in labels for w in d.wells for s in seeds]
@@ -253,7 +253,7 @@ def main() -> None:
pd.DataFrame(rows).assign(protocol_sha256=proto["sha256"][:12]).to_csv(out_dir / f"results_{tag}.csv", index=False) pd.DataFrame(rows).assign(protocol_sha256=proto["sha256"][:12]).to_csv(out_dir / f"results_{tag}.csv", index=False)
pd.DataFrame(sel).to_csv(out_dir / f"selection_{tag}.csv", index=False) pd.DataFrame(sel).to_csv(out_dir / f"selection_{tag}.csv", index=False)
np.savez_compressed(out_dir / f"preds_{tag}.npz", **preds) np.savez_compressed(out_dir / f"preds_{tag}.npz", **preds)
print(f"-> {out_dir} ({len(rows)} dòng, {time.time() - t0:.0f} s)") print(f"-> {out_dir} ({len(rows)} rows, {time.time() - t0:.0f} s)")
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -1,8 +1,8 @@
"""Tổng hợp kết quả LOWO P1: bảng theo giếng và macro, độ nhạy tham chiếu, calibration B3, cổng G-A. """Summarize the P1 LOWO results: per-well and macro tables, reference sensitivity, B3 calibration, gate G-A.
python scripts/06_summarize_p1.py python scripts/06_summarize_p1.py
Đầu ra: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png Outputs: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png
""" """
from __future__ import annotations from __future__ import annotations
@@ -43,7 +43,7 @@ def per_well(res, label, ref):
def macro(res, label, ref): def macro(res, label, ref):
mean, _, r = per_well(res, label, ref) mean, _, r = per_well(res, label, ref)
# macro theo giếng cho từng seed rồi lấy mean ± sd theo seed (phương pháp tất định có sd = 0) # macro over wells for each seed, then mean ± sd over seeds (deterministic methods have sd = 0)
cols = ["rmse", "pcc", "r2", "band_pcc", "skill"] cols = ["rmse", "pcc", "r2", "band_pcc", "skill"]
by_seed = r.groupby(["method", "seed"])[cols].mean() by_seed = r.groupby(["method", "seed"])[cols].mean()
out = by_seed.groupby("method").agg(["mean", "std"]).fillna(0.0) out = by_seed.groupby("method").agg(["mean", "std"]).fillna(0.0)
@@ -68,16 +68,16 @@ def main() -> None:
key = f"{label}/{ref}" key = f"{label}/{ref}"
summary[key] = {m: {c: [round(mt.loc[m, (c, "mean")], 3), round(mt.loc[m, (c, "std")], 3)] summary[key] = {m: {c: [round(mt.loc[m, (c, "mean")], 3), round(mt.loc[m, (c, "std")], 3)]
for c in ("rmse", "pcc", "r2", "band_pcc", "skill")} for m in mt.index} for c in ("rmse", "pcc", "r2", "band_pcc", "skill")} for m in mt.index}
lines.append(f"\n### Macro 4 giếng: nhãn {label}, tham chiếu {ref}\n") lines.append(f"\n### Macro over 4 wells: label {label}, reference {ref}\n")
lines.append("| Phương pháp | RMSE (p.u.) | PCC | R² | PCC băng seismic | Skill vs B0a |") lines.append("| Method | RMSE (p.u.) | PCC | R² | Seismic-band PCC | Skill vs B0a |")
lines.append("| --- | --- | --- | --- | --- | --- |") lines.append("| --- | --- | --- | --- | --- | --- |")
for m in mt.index: for m in mt.index:
lines.append("| " + " | ".join([m] + [fmt(mt.loc[m, (c, "mean")], mt.loc[m, (c, "std")]) lines.append("| " + " | ".join([m] + [fmt(mt.loc[m, (c, "mean")], mt.loc[m, (c, "std")])
for c in ("rmse", "pcc", "r2", "band_pcc", "skill")]) + " |") for c in ("rmse", "pcc", "r2", "band_pcc", "skill")]) + " |")
mean, sd, _ = per_well(res, lab1, "calibrated") mean, sd, _ = per_well(res, lab1, "calibrated")
lines.append(f"\n### Theo giếng: nhãn {lab1}, tham chiếu calibrated (RMSE p.u. / PCC / PCC băng)\n") lines.append(f"\n### Per well: label {lab1}, calibrated reference (RMSE p.u. / PCC / band PCC)\n")
lines.append("| Phương pháp | " + " | ".join(wells) + " |") lines.append("| Method | " + " | ".join(wells) + " |")
lines.append("| --- |" + " --- |" * len(wells)) lines.append("| --- |" + " --- |" * len(wells))
summary["per_well"] = {} summary["per_well"] = {}
for m in ORDER: for m in ORDER:
@@ -95,7 +95,7 @@ def main() -> None:
if len(cal): if len(cal):
cc = ["nll", "crps", "coverage_50", "coverage_80", "coverage_90", "coverage_95", "mean_sigma"] cc = ["nll", "crps", "coverage_50", "coverage_80", "coverage_90", "coverage_95", "mean_sigma"]
cm = cal.groupby(["method", "seed"])[cc].mean().groupby("method").agg(["mean", "std"]) cm = cal.groupby(["method", "seed"])[cc].mean().groupby("method").agg(["mean", "std"])
lines.append(f"\n### Calibration B3 (nhãn {lab1}, macro)\n") lines.append(f"\n### B3 calibration (label {lab1}, macro)\n")
lines.append("| | " + " | ".join(cc) + " |") lines.append("| | " + " | ".join(cc) + " |")
lines.append("| --- |" + " --- |" * len(cc)) lines.append("| --- |" + " --- |" * len(cc))
summary["calibration"] = {} summary["calibration"] = {}
@@ -103,7 +103,7 @@ def main() -> None:
lines.append(f"| {m} | " + " | ".join(fmt(cm.loc[m, (c, 'mean')], cm.loc[m, (c, 'std')]) for c in cc) + " |") lines.append(f"| {m} | " + " | ".join(fmt(cm.loc[m, (c, 'mean')], cm.loc[m, (c, 'std')]) for c in cc) + " |")
summary["calibration"][m] = {c: round(cm.loc[m, (c, "mean")], 3) for c in cc} summary["calibration"][m] = {c: round(cm.loc[m, (c, "mean")], 3) for c in cc}
# G-A: B3a so với B3b # G-A: B3a vs B3b
mt = macro(res, lab1, "calibrated") mt = macro(res, lab1, "calibrated")
if {"B3a", "B3b"} <= set(mt.index): if {"B3a", "B3b"} <= set(mt.index):
ra, rb = mt.loc["B3a", ("rmse", "mean")], mt.loc["B3b", ("rmse", "mean")] ra, rb = mt.loc["B3a", ("rmse", "mean")], mt.loc["B3b", ("rmse", "mean")]
@@ -113,9 +113,9 @@ def main() -> None:
summary["G-A"] = {"B3a_vs_B3b_rmse_pct": round(d_rmse, 1), "B3a_minus_B3b_pcc": round(pa - pb, 3), summary["G-A"] = {"B3a_vs_B3b_rmse_pct": round(d_rmse, 1), "B3a_minus_B3b_pcc": round(pa - pb, 3),
"B3a_approx_B3b": bool(equal)} "B3a_approx_B3b": bool(equal)}
lines.append(f"\n**G-A:** RMSE B3a − B3b = {d_rmse:+.1f}%, PCC B3a − B3b = {pa - pb:+.3f} → " lines.append(f"\n**G-A:** RMSE B3a − B3b = {d_rmse:+.1f}%, PCC B3a − B3b = {pa - pb:+.3f} → "
f"{'B3a ≈ B3b' if equal else 'B3a khác B3b'} theo ngưỡng protocol (|ΔRMSE| < 5%, |ΔPCC| < 0.05).") f"{'B3a ≈ B3b' if equal else 'B3a differs from B3b'} under the protocol thresholds (|ΔRMSE| < 5%, |ΔPCC| < 0.05).")
# QC nhãn trong cửa sổ (D-1) # Label QC within the window (D-1)
m_ = D[f"{wells[0]}/main_mask"].astype(bool) m_ = D[f"{wells[0]}/main_mask"].astype(bool)
lq = {} lq = {}
for w in wells: for w in wells:
@@ -123,8 +123,8 @@ def main() -> None:
lq[w] = {"r2": round(float(np.corrcoef(a, b)[0, 1] ** 2), 4), "max_abs_diff_pu": round(float(np.max(np.abs(a - b)) * 100), 2), lq[w] = {"r2": round(float(np.corrcoef(a, b)[0, 1] ** 2), 4), "max_abs_diff_pu": round(float(np.max(np.abs(a - b)) * 100), 2),
"std_pu": round(float(np.std(b) * 100), 2)} "std_pu": round(float(np.std(b) * 100), 2)}
summary["label_qc"] = lq summary["label_qc"] = lq
lines.append("\n### QC nhãn trong 600–1100 ms (PHIE so với PHIE_DT, calibrated)\n") lines.append("\n### Label QC in 600–1100 ms (PHIE vs PHIE_DT, calibrated)\n")
lines.append("| Giếng | R² | max |Δ| (p.u.) | std PHIE_DT (p.u.) |\n| --- | --- | --- | --- |") lines.append("| Well | R² | max |Δ| (p.u.) | std PHIE_DT (p.u.) |\n| --- | --- | --- | --- |")
for w, v in lq.items(): for w, v in lq.items():
lines.append(f"| {w} | {v['r2']} | {v['max_abs_diff_pu']} | {v['std_pu']} |") lines.append(f"| {w} | {v['r2']} | {v['max_abs_diff_pu']} | {v['std_pu']} |")
@@ -133,20 +133,20 @@ def main() -> None:
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False)) (out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
print("\n".join(lines)) print("\n".join(lines))
# Hình: dự đoán tại 4 giếng (nhãn chính) # Figure: predictions at the 4 wells (primary label)
t = D[f"{wells[0]}/times_ms"][m_] t = D[f"{wells[0]}/times_ms"][m_]
fig, axes = plt.subplots(1, 4, figsize=(14, 7), sharey=True, constrained_layout=True) fig, axes = plt.subplots(1, 4, figsize=(14, 7), sharey=True, constrained_layout=True)
style = {"B0a": ("#8a93a3", "--"), "B0b-ridge": ("#2a9d8f", "-"), "B1": ("#8a5cc2", "-"), style = {"B0a": ("#8a93a3", "--"), "B0b-ridge": ("#2a9d8f", "-"), "B1": ("#8a5cc2", "-"),
"B2": ("#c47a00", "-"), "B3b": ("#1f5fbf", "-")} "B2": ("#c47a00", "-"), "B3b": ("#1f5fbf", "-")}
for ax, w in zip(axes, wells): for ax, w in zip(axes, wells):
ax.plot(100 * D[f"{w}/calibrated/{lab1}"][m_], t, "k", lw=1.6, label="tham chiếu (calibrated)") ax.plot(100 * D[f"{w}/calibrated/{lab1}"][m_], t, "k", lw=1.6, label="reference (calibrated)")
ax.plot(100 * D[f"{w}/wlt/{lab1}"][m_], t, color="k", lw=0.8, ls=":", label="tham chiếu (.wlt)") ax.plot(100 * D[f"{w}/wlt/{lab1}"][m_], t, color="k", lw=0.8, ls=":", label="reference (.wlt)")
for meth, (c, ls) in style.items(): for meth, (c, ls) in style.items():
ks = [k for k in preds if k.startswith(f"{lab1}/{w}/{meth}/") and k.endswith("/mu")] ks = [k for k in preds if k.startswith(f"{lab1}/{w}/{meth}/") and k.endswith("/mu")]
if not ks: if not ks:
continue continue
mu = 100 * np.mean([preds[k] for k in ks], axis=0) mu = 100 * np.mean([preds[k] for k in ks], axis=0)
ax.plot(mu, t, color=c, ls=ls, lw=1.1, label=meth + (" (TB 5 seed)" if len(ks) > 1 else "")) ax.plot(mu, t, color=c, ls=ls, lw=1.1, label=meth + (" (mean of 5 seeds)" if len(ks) > 1 else ""))
if meth == "B3b": if meth == "B3b":
sig = 100 * np.mean([preds[k.replace("/mu", "/sigma")] for k in ks], axis=0) sig = 100 * np.mean([preds[k.replace("/mu", "/sigma")] for k in ks], axis=0)
ax.fill_betweenx(t, mu - 1.645 * sig, mu + 1.645 * sig, color=c, alpha=0.12, lw=0, label="B3b 90%") ax.fill_betweenx(t, mu - 1.645 * sig, mu + 1.645 * sig, color=c, alpha=0.12, lw=0, label="B3b 90%")
@@ -156,7 +156,7 @@ def main() -> None:
axes[0].set_ylim(t[-1], t[0]) axes[0].set_ylim(t[-1], t[0])
axes[0].set_ylabel("TWT (ms)") axes[0].set_ylabel("TWT (ms)")
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=8, fontsize=8.5) fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=8, fontsize=8.5)
fig.suptitle(f"LOWO P1, nhãn {lab1}: dự đoán tại giếng test", fontsize=11) fig.suptitle(f"LOWO P1, label {lab1}: predictions at the test wells", fontsize=11)
fig.savefig(outputs_dir() / "figures" / "p1_lowo.png", dpi=130) fig.savefig(outputs_dir() / "figures" / "p1_lowo.png", dpi=130)

View File

@@ -1,11 +1,11 @@
"""QC dữ liệu minh giải Volve (Geophysical_Interpretations) trước khi có cube. """QC of the Volve interpretation data (Geophysical_Interpretations) before the cube is available.
python scripts/07_volve_interp_qc.py python scripts/07_volve_interp_qc.py
Kiểm tra: lưới các horizon, số anchor TWT của well picks tại 10 giếng D3 (9 giếng PHIF và F-15 A), độ lệch pick − horizon Checks: horizon grids, number of TWT anchors from the well picks at the 10 D3 wells (9 PHIF wells and F-15 A), pick − horizon
tại toạ độ pick, độ lệch pick − checkshot (F-11 T2, F-15 A), ROI theo IL/XL của lưới ST10010; nếu đã có cube: offset at the pick coordinates, pick − checkshot offset (F-11 T2, F-15 A), ROI in IL/XL of the ST10010 grid; if the cube is present:
toạ độ header so với lưới horizon, và lag của cực trị biên độ trung bình dọc mỗi horizon (≈ 0 nếu trục thời gian đúng). header coordinates vs the horizon grid, and the lag of the mean-amplitude extremum along each horizon (≈ 0 if the time axis is correct).
Đầu ra: outputs/volve/{horizons,anchors,pick_vs_horizon,pick_vs_checkshot,horizon_lag}.csv, summary.json Outputs: outputs/volve/{horizons,anchors,pick_vs_horizon,pick_vs_checkshot,horizon_lag}.csv, summary.json
""" """
from __future__ import annotations from __future__ import annotations
@@ -28,7 +28,7 @@ def main() -> None:
hdir = root / cfg["horizons_twt"] hdir = root / cfg["horizons_twt"]
summary = {} summary = {}
# lưới horizon # horizon grids
rows, hors = [], {} rows, hors = [], {}
for f in sorted(hdir.parent.rglob("*.dat")): for f in sorted(hdir.parent.rglob("*.dat")):
h = read_horizon(f) h = read_horizon(f)
@@ -46,7 +46,7 @@ def main() -> None:
summary["grid"] = {"x_coef": geom.x_coef, "y_coef": geom.y_coef, "bin_m": geom.bin_spacing(), summary["grid"] = {"x_coef": geom.x_coef, "y_coef": geom.y_coef, "bin_m": geom.bin_spacing(),
"max_affine_residual_m_all_horizons": float(H.affine_res_m.max())} "max_affine_residual_m_all_horizons": float(H.affine_res_m.max())}
# anchor TWT tại giếng chính # TWT anchors at the main wells
P = read_well_picks(root / cfg["picks"]) P = read_well_picks(root / cfg["picks"])
P["il"], P["xl"] = geom.xy_to_bin(P.x, P.y) P["il"], P["xl"] = geom.xy_to_bin(P.x, P.y)
ok = (P.twt_ms.notna() & ~P.qlf.isin(cfg["anchor_exclude_qlf"]) ok = (P.twt_ms.notna() & ~P.qlf.isin(cfg["anchor_exclude_qlf"])
@@ -60,12 +60,12 @@ def main() -> None:
"n_faulted": int((a.qlf == "FP").sum())} "n_faulted": int((a.qlf == "FP").sum())}
summary["anchors"] = per_well summary["anchors"] = per_well
# TWT nông: cùng MD, khác nhánh khoan # shallow TWT: same MD, different well branches
sh = P[P.surface.isin(["Utsira Fm. Top", "HORDALAND GP. Top"]) & P.twt_ms.notna()] sh = P[P.surface.isin(["Utsira Fm. Top", "HORDALAND GP. Top"]) & P.twt_ms.notna()]
summary["shallow_twt_spread_ms"] = {s: [float(g.twt_ms.min()), float(g.twt_ms.max())] summary["shallow_twt_spread_ms"] = {s: [float(g.twt_ms.min()), float(g.twt_ms.max())]
for s, g in sh.groupby("surface")} for s, g in sh.groupby("surface")}
# pick − horizon tại toạ độ pick # pick − horizon at the pick coordinates
C = [] C = []
for s, f in cfg["pick_horizons"].items(): for s, f in cfg["pick_horizons"].items():
h = hors[f"{hdir.name}/{f}"] h = hors[f"{hdir.name}/{f}"]
@@ -81,7 +81,7 @@ def main() -> None:
s: {"n": len(g), "median": round(float(g.d_ms.median()), 1), "mad": round(float((g.d_ms - g.d_ms.median()).abs().median()), 1), s: {"n": len(g), "median": round(float(g.d_ms.median()), 1), "mad": round(float((g.d_ms - g.d_ms.median()).abs().median()), 1),
"max_abs": round(float(g.d_ms.abs().max()), 1)} for s, g in clean.groupby("surface")} "max_abs": round(float(g.d_ms.abs().max()), 1)} for s, g in clean.groupby("surface")}
# pick − checkshot (theo TVDSS để không phụ thuộc mốc MD) # pick − checkshot (in TVDSS, independent of the MD datum)
D = [] D = []
for w, files in cfg["checkshots"].items(): for w, files in cfg["checkshots"].items():
p = P[(P.well == w) & P.twt_ms.notna()] p = P[(P.well == w) & P.twt_ms.notna()]
@@ -98,14 +98,14 @@ def main() -> None:
summary["pick_minus_checkshot_ms"] = {f"{w} {k}": [round(float(g.d_tvd_ms.min()), 1), round(float(g.d_tvd_ms.max()), 1)] summary["pick_minus_checkshot_ms"] = {f"{w} {k}": [round(float(g.d_tvd_ms.min()), 1), round(float(g.d_tvd_ms.max()), 1)]
for (w, k), g in deep.groupby(["well", "checkshot"])} for (w, k), g in deep.groupby(["well", "checkshot"])}
# ROI theo IL/XL # ROI in IL/XL
x0, x1, y0, y1 = cfg["roi_xy"] x0, x1, y0, y1 = cfg["roi_xy"]
il, xl = geom.xy_to_bin([x0, x1, x1, x0], [y0, y0, y1, y1]) il, xl = geom.xy_to_bin([x0, x1, x1, x0], [y0, y0, y1, y1])
summary["roi_ilxl"] = {"il": [int(np.floor(il.min())), int(np.ceil(il.max()))], summary["roi_ilxl"] = {"il": [int(np.floor(il.min())), int(np.ceil(il.max()))],
"xl": [int(np.floor(xl.min())), int(np.ceil(xl.max()))]} "xl": [int(np.floor(xl.min())), int(np.ceil(xl.max()))]}
summary["anchor_twt_range_ms"] = [float(A.twt_ms.min()), float(A.twt_ms.max())] summary["anchor_twt_range_ms"] = [float(A.twt_ms.min()), float(A.twt_ms.max())]
# cube: header so với lưới horizon; horizon pick trên peak/trough nên cực trị phải ở lag ≈ 0 # cube: header vs horizon grid; horizons are picked on peaks/troughs, so the extremum should be at lag ≈ 0
cube_path = root / cfg["cube"] cube_path = root / cfg["cube"]
if cube_path.exists(): if cube_path.exists():
(i0, i1), (j0, j1) = summary["roi_ilxl"]["il"], summary["roi_ilxl"]["xl"] (i0, i1), (j0, j1) = summary["roi_ilxl"]["il"], summary["roi_ilxl"]["xl"]

View File

@@ -1,15 +1,15 @@
"""Kiểm tra D-1 (định nghĩa nhãn F3) bằng density đo của NLOG. """Check D-1 (the F3 label definition) against the measured NLOG density.
python scripts/08_d1_label_check.py python scripts/08_d1_label_check.py
PHIE của bộ demo ở F03-2, F03-4, F06-1 là hàm tuyến tính của DT (plan mục 1.2d). Script so porosity theo density đo The demo PHIE at F03-2, F03-4, F06-1 is a linear function of DT (plan §1.2d). This script compares the porosity from
φ_D = (2650 − RHOB)/1600 (RHOB từ LAS NLOG) với nhãn sonic PHIE_DT = −0.2018 + 0.0011·DT trong cửa sổ 600–1100 ms, measured density φ_D = (2650 − RHOB)/1600 (RHOB from the NLOG LAS) with the sonic label PHIE_DT = −0.2018 + 0.0011·DT
trên lưới 4 ms như nhãn huấn luyện: in the 600–1100 ms window, on the same 4 ms grid as the training labels:
- F02-1, F03-4: giếng demo, TD calibrated từ outputs/f3_wells.npz; độ sâu NLOG căn theo tương quan DT; - F02-1, F03-4: demo wells, calibrated TD from outputs/f3_wells.npz; NLOG depth aligned by DT correlation;
- F03-03, F03-06: giếng NLOG ngoài bộ demo, TD theo file TZ (giả định MD − APD ≈ TVDSS ở đoạn nông); - F03-03, F03-06: NLOG wells outside the demo set, TD from the TZ file (assuming MD − APD ≈ TVDSS in the shallow section);
- F03-2, F06-1: RHOB đo của NLOG bắt đầu ở 1641 và 1836 m MD, dưới cửa sổ, nên không có φ_D. - F03-2, F06-1: measured NLOG RHOB starts at 1641 and 1836 m MD, below the window, so no φ_D.
Kèm chỉ số chất lượng trong cửa sổ: |DRHO| và caliper (từ composite LAS; chưa có bit size nên chưa kết luận washout). Also reports in-window quality indicators: |DRHO| and caliper (from the composite LAS; no bit size yet, so no washout conclusion).
Đầu ra: outputs/d1/label_check.csv, summary.json Outputs: outputs/d1/label_check.csv, summary.json
""" """
from __future__ import annotations from __future__ import annotations
@@ -26,7 +26,7 @@ from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import TDR from ml_porosity.data.tdr import TDR
from ml_porosity.paths import REPO_ROOT, nlog_root, outputs_dir from ml_porosity.paths import REPO_ROOT, nlog_root, outputs_dir
# (LAS composite có RHOB/DRHO, LAS composite có CALI theo feet, file TZ); tên gốc NLOG có tiền tố giếng # (composite LAS with RHOB/DRHO, composite LAS with CALI in feet, TZ file); original NLOG names carry a well prefix
NLOG_FILES = { NLOG_FILES = {
"F02-1": ("F02-01__8727_f0201_1976_comp.las", "F02-01-S1__F021_Composite-TOTAL~LF1.las", None), "F02-1": ("F02-01__8727_f0201_1976_comp.las", "F02-01-S1__F021_Composite-TOTAL~LF1.las", None),
"F03-4": ("F03-04__7035_f0304_1976_comp.las", "F03-04__F034_Composite-TOTAL~LF1.las", None), "F03-4": ("F03-04__7035_f0304_1976_comp.las", "F03-04__F034_Composite-TOTAL~LF1.las", None),
@@ -35,7 +35,7 @@ NLOG_FILES = {
} }
WINDOW_MS = (600.0, 1100.0) WINDOW_MS = (600.0, 1100.0)
T = np.arange(WINDOW_MS[0], WINDOW_MS[1] + 0.1, 4.0) T = np.arange(WINDOW_MS[0], WINDOW_MS[1] + 0.1, 4.0)
SOS_BAND = signal.butter(4, 6 / 125, "high", output="sos") # băng seismic > 6 Hz (plan mục 2.3) trên lưới 4 ms SOS_BAND = signal.butter(4, 6 / 125, "high", output="sos") # seismic band > 6 Hz (plan §2.3) on the 4 ms grid
def phi_d(rhob): def phi_d(rhob):
@@ -47,7 +47,7 @@ def phi_dt(dt):
def read_nlog(comp: str, composite: str) -> tuple[pd.DataFrame, float]: def read_nlog(comp: str, composite: str) -> tuple[pd.DataFrame, float]:
"""MD (m, từ LMF) → DT µs/m, RHOB và DRHO kg/m³, CALI inch; kèm APD (m trên MSL).""" """MD (m, from LMF) → DT µs/m, RHOB and DRHO kg/m³, CALI inch; plus APD (m above MSL)."""
raw = nlog_root() / "raw" raw = nlog_root() / "raw"
las = lasio.read(raw / comp) las = lasio.read(raw / comp)
df = las.df().sort_index() df = las.df().sort_index()
@@ -71,7 +71,7 @@ def corr(a: np.ndarray, b: np.ndarray) -> float:
def compare(a: np.ndarray, b: np.ndarray) -> dict: def compare(a: np.ndarray, b: np.ndarray) -> dict:
"""a, b theo p.u. trên lưới T; r băng tính trên đoạn liên tục chung.""" """a, b in p.u. on grid T; band r computed over the common contiguous segment."""
ok = np.isfinite(a) & np.isfinite(b) ok = np.isfinite(a) & np.isfinite(b)
r = corr(a, b) r = corr(a, b)
i = np.flatnonzero(ok) i = np.flatnonzero(ok)
@@ -99,7 +99,7 @@ def main() -> None:
for w, (comp, composite, tz) in NLOG_FILES.items(): for w, (comp, composite, tz) in NLOG_FILES.items():
df, apd = read_nlog(comp, composite) df, apd = read_nlog(comp, composite)
info = {"apd_m": apd} info = {"apd_m": apd}
if tz is None: # giếng demo: căn độ sâu NLOG theo DT, so với LAS demo if tz is None: # demo well: align NLOG depth by DT against the demo LAS
W = load_well(w) W = load_well(w)
tdr = TDR(Z[f"{w}/tdr/calibrated/md"], Z[f"{w}/tdr/calibrated/twt_ms"], "calibrated") tdr = TDR(Z[f"{w}/tdr/calibrated/md"], Z[f"{w}/tdr/calibrated/twt_ms"], "calibrated")
d0, d1 = tdr.depth_at(WINDOW_MS) d0, d1 = tdr.depth_at(WINDOW_MS)
@@ -116,7 +116,7 @@ def main() -> None:
"rms": round(float(np.sqrt(np.mean(d ** 2))), 1)} "rms": round(float(np.sqrt(np.mean(d ** 2))), 1)}
labels = {"PHIE_DT": log_to_time(W.md, phi_dt(W.curve("DT")), tdr, T), labels = {"PHIE_DT": log_to_time(W.md, phi_dt(W.curve("DT")), tdr, T),
"PHIE": log_to_time(W.md, W.curve("PHIE"), tdr, T)} "PHIE": log_to_time(W.md, W.curve("PHIE"), tdr, T)}
else: # giếng NLOG mới: chỉ có DT của NLOG else: # new NLOG well: only the NLOG DT is available
tdr = read_tz(tz, apd) tdr = read_tz(tz, apd)
d0, d1 = tdr.depth_at(WINDOW_MS) d0, d1 = tdr.depth_at(WINDOW_MS)
md, shift = df.index.to_numpy(), 0.0 md, shift = df.index.to_numpy(), 0.0
@@ -134,7 +134,7 @@ def main() -> None:
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False)) (out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
print(R.to_string(index=False)) print(R.to_string(index=False))
print(json.dumps(summary["wells"], indent=1, ensure_ascii=False)) print(json.dumps(summary["wells"], indent=1, ensure_ascii=False))
print("ghi:", out.relative_to(REPO_ROOT) if out.is_relative_to(REPO_ROOT) else out) print("written:", out.relative_to(REPO_ROOT) if out.is_relative_to(REPO_ROOT) else out)
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -0,0 +1,103 @@
"""Fit the GP warp prior (plan §4.1) on the F3 anchors and run a leave-one-anchor-out check (§5.4).
python scripts/09_fit_warp_prior_f3.py
τ = integrated DT passing through the first TD marker (as for the base of the calibrated TDR); anchors = TD markers
in the extended 400–1300 ms window; d_k = t_k − τ_k. Type-II ML fit on all 4 wells (used to calibrate the D2 drift)
and on each LOWO fold (3 train wells). Outputs: outputs/p2/warp_prior_f3.json, figures/p2_f3_drift.png.
"""
from __future__ import annotations
import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import yaml
from ml_porosity.data.las_io import load_well
from ml_porosity.data.tdr import sonic_tdr
from ml_porosity.paths import REPO_ROOT, outputs_dir
from ml_porosity.registration.warp_prior import (WarpGrid, WarpHyper, fit_hyper, linear_posterior,
loao_zscores)
TAU_RANGE = (300.0, 1400.0)
def f3_anchor_wells(cfg: dict) -> list[dict]:
e0, e1 = cfg["ext_window_ms"]
out = []
for name in cfg["wells"]:
w = load_well(name)
cs = w.checkshot
base = sonic_tdr(w.md, w.curve("DT"), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
tk = cs.twt_ms.to_numpy()
tau = base.time_at(cs.md.to_numpy())
m = (tk >= e0) & (tk <= e1)
out.append({"name": name, "grid": WarpGrid(*TAU_RANGE, 4.0), "tau_k": tau[m], "d_k": tk[m] - tau[m]})
return out
def z_summary(z: np.ndarray) -> dict:
return {"n": int(len(z)), "mean_z2": round(float(np.mean(z**2)), 3),
"coverage_90": round(float(np.mean(np.abs(z) < 1.6449)), 3),
"max_abs_z": round(float(np.max(np.abs(z))), 2)}
def main() -> None:
cfg = yaml.safe_load(open(REPO_ROOT / "configs" / "d1_f3.yaml"))
wells = f3_anchor_wells(cfg)
# The "tau" and "note" strings below are written verbatim into warp_prior_f3.json, whose SHA-256 is locked in
# protocol_p2/protocol_p2r; they are deliberately left untranslated so that a re-run reproduces the locked file.
res = {"tau": "sonic_tdr qua marker TD đầu tiên", "anchors_window_ms": cfg["ext_window_ms"],
"tau_range_ms": TAU_RANGE, "n_anchors": {w["name"]: int(len(w["tau_k"])) for w in wells}, "fits": {}}
for kern in ["matern32", "se"]:
h, info = fit_hyper(wells, WarpHyper(kernel=kern), n_starts=8)
z = loao_zscores(wells, h)
folds = {}
for i, w in enumerate(wells):
hi, _ = fit_hyper([v for j, v in enumerate(wells) if j != i], WarpHyper(kernel=kern), n_starts=6)
zi = loao_zscores([w], hi)[0]
folds[w["name"]] = {"hyper": hi.as_dict(), "loao_test_well": z_summary(zi)}
res["fits"][kern] = {"hyper": h.as_dict(), "log_marginal": round(info["log_marginal"], 3),
"at_bound": info["at_bound"],
"loao": z_summary(np.concatenate(z)) | {"per_well": {w["name"]: z_summary(zw) for w, zw in zip(wells, z)}},
"lowo_folds": folds}
print(kern, h, "logML", round(info["log_marginal"], 2), "LOAO", z_summary(np.concatenate(z)))
best = max(res["fits"], key=lambda k: res["fits"][k]["log_marginal"])
res["selected_kernel"] = "matern32"
res["note"] = ("Chọn Matérn-3/2 (chốt trước trong configs/d2_synth.yaml) — log-marginal hai kernel chênh "
f"{abs(res['fits']['matern32']['log_marginal'] - res['fits']['se']['log_marginal']):.2f} "
f"(cao hơn: {best}).")
out = outputs_dir() / "p2"
out.mkdir(parents=True, exist_ok=True)
(out / "warp_prior_f3.json").write_text(json.dumps(res, indent=2, ensure_ascii=False))
h = WarpHyper(**res["fits"]["matern32"]["hyper"])
fig, axes = plt.subplots(1, 4, figsize=(14, 4), sharey=True)
for ax, w in zip(axes, wells):
grid = w["grid"]
mu, S = linear_posterior(grid, h, w["tau_k"], w["d_k"])
A = grid.anchor_operator(grid.tau)
m = A @ mu
sd = np.sqrt(np.einsum("ij,jk,ik->i", A, S, A))
ax.fill_between(grid.tau, m - 2 * sd, m + 2 * sd, color="C0", alpha=0.25, label="±2σ posterior")
ax.plot(grid.tau, m, "C0", label="posterior mean")
ax.plot(w["tau_k"], w["d_k"], "ko", ms=3, label="anchor")
ax.set_title(w["name"])
ax.set_xlabel("τ sonic (ms)")
ax.set_xlim(380, 1320)
axes[0].set_ylabel("t − τ (ms)")
axes[0].legend(fontsize=7)
fig.suptitle(f"F3 drift under the GP prior (Matérn-3/2, σ_g={h.sigma_g:.3f}, ℓ={h.ell_ms:.0f} ms, σ_a={h.sigma_a_ms:.2f} ms)")
fig.tight_layout()
(outputs_dir() / "figures").mkdir(exist_ok=True)
fig.savefig(outputs_dir() / "figures" / "p2_f3_drift.png", dpi=130)
print("→", out / "warp_prior_f3.json")
if __name__ == "__main__":
main()

177
scripts/10_build_d2.py Normal file
View File

@@ -0,0 +1,177 @@
"""QC of D2 against F3 (plan §5.1, §5.5): label, anchor and drift statistics; figure of one example well.
Labels on the extended 400–1300 ms window, 4 ms grid. F3: calibrated PHIE_DT of the 4 wells (linear in DT).
D2: anti-aliased φ of the central trace in true time, all wells (8 test + 16 pool) of the main realizations.
Per-well statistics: residual std after a linear trend, std of the > 6 Hz band, τ_c (rml.effective_lambda), PSD slope
over 10–80 Hz (log–log, Hann periodogram of the residual). Drift: max − min range of t − τ at the anchors in the extended
window (F3: TD markers as in scripts/09; D2: true warp at unit boundaries, no pick noise) and anchors per well.
python scripts/10_build_d2.py
→ outputs/d2/qc.json, outputs/figures/p2_d2_qc.png
"""
from __future__ import annotations
import importlib.util
import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import yaml
from scipy import signal
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.eval import figstyle as fs
from ml_porosity.eval.metrics import split_bands
from ml_porosity.losses.rml import effective_lambda
from ml_porosity.paths import REPO_ROOT, outputs_dir
from ml_porosity.registration.labels import antialias
from ml_porosity.registration.warp_prior import WarpHyper
STATS = {"resid_std": "residual std (linear trend)", "band_std": "std of > 6 Hz band",
"tau_c": "τ_c (samples)", "psd_slope": "PSD slope 10–80 Hz"}
def label_stats(y: np.ndarray, dt: float = 4.0, f_c: float = 6.0) -> dict:
k = np.arange(len(y))
res = y - np.polyval(np.polyfit(k, y, 1), k)
f, P = signal.periodogram(res, fs=1000.0 / dt, window="hann")
m = (f >= 10) & (f <= 80)
return {"resid_std": float(res.std()), "band_std": float(split_bands(y, f_c, dt)[1].std()),
"tau_c": effective_lambda([y], f_c, dt)[1], "psd_slope": float(np.polyfit(np.log10(f[m]), np.log10(P[m]), 1)[0])}
def summary(v) -> dict:
v = np.asarray(v, dtype=float)
return {"n": int(len(v)), "median": float(np.median(v)), "q05": float(np.quantile(v, 0.05)),
"q95": float(np.quantile(v, 0.95)), "min": float(v.min()), "max": float(v.max())}
def f3_side() -> dict:
spec = importlib.util.spec_from_file_location("fit09", REPO_ROOT / "scripts" / "09_fit_warp_prior_f3.py")
fit09 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fit09)
cfg = yaml.safe_load(open(REPO_ROOT / "configs" / "d1_f3.yaml"))
z = np.load(outputs_dir() / "f3_wells.npz", allow_pickle=True)
out = {}
for w in fit09.f3_anchor_wells(cfg):
y = z[f"{w['name']}/calibrated/PHIE_DT"].astype(float)
out[w["name"]] = label_stats(y) | {"n_anchors": int(len(w["tau_k"])),
"drift_range_ms": float(np.ptp(w["d_k"]))}
return out
def main() -> None:
P = yaml.safe_load(open(REPO_ROOT / "configs" / "protocol_p2.yaml"))
cfg = yaml.safe_load(open(REPO_ROOT / P["inputs"]["d2_config"]["path"]))
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"]]
drift = WarpHyper(**prior["hyper"])
cs = [c for c in P["grid"]["drift_factors"] if c > 0]
sa, f = cfg["anchors"]["sigma_a_ms"], cfg["fine_dt_ms"]
d2 = {k: [] for k in STATS} | {"n_anchors": [], **{f"drift_range_ms_c{c:g}": [] for c in cs},
**{f"max_abs_g_c{c:g}": [] for c in cs}}
example = None
for rid in P["grid"]["realizations"]:
R = D2Realization(cfg, rid, hg, drift, wav)
win = (R.grid.tau >= R.t_ext[0]) & (R.grid.tau <= R.t_ext[-1])
for w in R.wells:
y = np.interp(R.t_ext, R.t_fine, antialias(w.phi_t, f, R.dt))
for k, v in label_stats(y).items():
d2[k].append(v)
for c in cs:
o = R.observe(w, c, P["grid"]["snr_db"], sa)
d2[f"drift_range_ms_c{c:g}"].append(float(np.ptp(w.boundaries_t - o["tau_k"])))
d2[f"max_abs_g_c{c:g}"].append(float(np.abs(o["g"][win]).max()))
d2["n_anchors"].append(len(w.boundaries_t))
if example is None:
w = R.pool[0]
example = {"R": R, "w": w, "obs": {c: R.observe(w, c, P["grid"]["snr_db"], sa) for c in cs}}
print(f"realization {rid}: {len(R.wells)} wells", flush=True)
f3 = f3_side()
qc = {"window_ms": cfg["ext_window_ms"], "realizations": P["grid"]["realizations"],
"d2": {k: summary(v) for k, v in d2.items()},
"f3": f3, "f3_range": {k: [min(w[k] for w in f3.values()), max(w[k] for w in f3.values())]
for k in list(STATS) + ["n_anchors", "drift_range_ms"]}}
out = outputs_dir() / "d2"
out.mkdir(parents=True, exist_ok=True)
(out / "qc.json").write_text(json.dumps(qc, indent=1, ensure_ascii=False))
for k in list(STATS) + ["n_anchors"]:
s = qc["d2"][k]
print(f"{k:12s} D2 median {s['median']:.4g} [5–95%: {s['q05']:.4g}, {s['q95']:.4g}] F3 {qc['f3_range'][k]}")
for c in cs:
s = qc["d2"][f"drift_range_ms_c{c:g}"]
print(f"drift c={c:g}: D2 median {s['median']:.1f} ms [{s['q05']:.1f}, {s['q95']:.1f}] F3 {qc['f3_range']['drift_range_ms']}")
plot(example, d2, f3, cs, outputs_dir() / "figures" / "p2_d2_qc.png")
def plot(ex, d2, f3, cs, path) -> None:
fs.apply()
R, w, obs = ex["R"], ex["w"], ex["obs"]
fig = plt.figure(figsize=(12, 6.4))
gs = fig.add_gridspec(2, 4, height_ratios=[1.15, 1], hspace=0.55, wspace=0.35)
ax = fig.add_subplot(gs[0, :2])
m = (R.t_fine >= R.t_ext[0]) & (R.t_fine <= R.t_ext[-1])
o1 = obs[1.0] if 1.0 in obs else obs[cs[0]]
ax.plot(R.t_fine[m], 100 * w.phi_t[m], color=fs.INK, lw=1.0, label="true φ in t")
sel = (o1["tau_fine"] >= R.t_ext[0]) & (o1["tau_fine"] <= R.t_ext[-1])
ax.plot(o1["tau_fine"][sel], 100 * o1["phi_log"][sel], color=fs.ORANGE, lw=1.0, label="log placed at τ (no tie, c = 1)")
ax.axvspan(*R.t_main[[0, -1]], color=fs.GRID, alpha=0.5, lw=0)
ax.text(R.t_main[0] + 5, ax.get_ylim()[1], "main window", va="top", fontsize=8, color=fs.INK2)
ax.set(xlabel="time (ms)", ylabel="φ (p.u.)", title=f"(a) Example well {w.name}, realization {R.rid}")
ax.legend(loc="lower left")
ax = fig.add_subplot(gs[0, 2])
gt = R.grid.tau
for c, col in zip(cs, fs.ORDINAL_BLUE):
o = obs[c]
dd = np.interp(gt, o["tau_fine"], o["t_of_tau_true"]) - gt
k = (gt >= R.t_ext[0]) & (gt <= R.t_ext[-1])
ax.plot(gt[k], dd[k], color=col, lw=1.5)
ax.annotate(f"c = {c:g}", (gt[k][-1], dd[k][-1]), xytext=(3, 0), textcoords="offset points",
va="center", fontsize=8, color=fs.INK2)
ax.plot(o1["tau_k"], o1["t_k"] - o1["tau_k"], "o", ms=4, mfc=fs.SURFACE, mec=fs.INK, mew=1.0, label="anchor (c = 1, σ_a = 7 ms)")
ax.set(xlabel="τ sonic (ms)", ylabel="t − τ (ms)", title="(b) True warp and anchors")
ax.set_xlim(R.t_ext[0], R.t_ext[-1] + 120)
lo, hi = ax.get_ylim()
ax.set_ylim(lo, hi + 0.25 * (hi - lo))
ax.legend(loc="upper left")
ax = fig.add_subplot(gs[0, 3])
mid = w.seis_clean.shape[0] // 2
ax.plot(R.t_ext, o1["seis"][mid], color=fs.INK, lw=0.9, label="SNR 10 dB")
ax.plot(R.t_ext, w.seis_clean[mid], color=fs.BLUE, lw=0.9, label="noise-free")
ax.set(xlabel="time (ms)", title="(c) Central seismic trace", yticks=[])
ax.legend(loc="lower left")
rng = np.random.default_rng(0)
for j, (k, lab) in enumerate(STATS.items()):
ax = fig.add_subplot(gs[1, j])
v = np.asarray(d2[k])
x = rng.uniform(-0.18, 0.18, len(v))
ax.plot(x, v, "o", ms=2.5, color=fs.BLUE, alpha=0.35, mec="none")
q = np.quantile(v, [0.05, 0.5, 0.95])
ax.plot([0.28, 0.28], q[[0, 2]], color=fs.INK2, lw=1.2)
ax.plot([0.22, 0.34], [q[1], q[1]], color=fs.INK2, lw=1.2)
fv = [f3[n][k] for n in f3]
ax.plot(np.full(len(fv), 1.0), fv, "D", ms=6, color=fs.ORANGE, mec=fs.SURFACE, mew=1.0)
ax.set_xticks([0, 1], [f"D2 ({len(v)} wells)", "F3 (4 wells)"])
ax.set_xlim(-0.5, 1.5)
ax.grid(axis="x", visible=False)
ax.set_title(f"({'defg'[j]}) {lab}")
fig.suptitle("D2 vs F3: labels over 400–1300 ms (F3: PHIE_DT, linear in DT); D2 shown with median and 5–95% range",
x=0.06, ha="left", fontsize=10, color=fs.INK2)
path.parent.mkdir(exist_ok=True)
fig.savefig(path, dpi=140, bbox_inches="tight")
print("→", path)
if __name__ == "__main__":
main()

242
scripts/11_run_d2.py Normal file
View File

@@ -0,0 +1,242 @@
"""P2 on D2: register the train wells, train every method, score on the 8 test wells (plan §5–6).
python scripts/11_run_d2.py --dev # dev realizations 900, 901: select step budgets → outputs/p2/dev/budgets.json
python scripts/11_run_d2.py --main # main grid (protocol_p2 must match the locked hash) → outputs/p2/main/
Each job is one cell (realization, c, N); seeds run sequentially within a job. Each cell's results are written
immediately to outputs/p2/<mode>/cells/, so a re-run skips completed cells. Cell (c = 1, N = 4) of the main grid also
includes the anchor-free variants M1-na/M2-na (H4).
"""
from __future__ import annotations
import argparse
import dataclasses
import hashlib
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
PROTO = REPO_ROOT / "configs" / "protocol_p2.yaml"
METHODS = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M1", "M2"]
def load_protocol(check: bool) -> dict:
actual = hashlib.sha256(PROTO.read_bytes()).hexdigest()
if check:
f = REPO_ROOT / "configs" / "protocol_p2.sha256"
expected = f.read_text().split()[0] if f.exists() else "(not locked)"
if actual != expected:
raise SystemExit(f"protocol_p2.yaml is not locked or changed after locking ({actual[:12]} ≠ {expected[:12]})")
proto = yaml.safe_load(PROTO.read_text())
for v in proto["inputs"].values():
h = hashlib.sha256((REPO_ROOT / v["path"]).read_bytes()).hexdigest()
if h != v["sha256"]:
raise SystemExit(f"{v['path']} differs from the version recorded in protocol_p2 ({h[:12]} ≠ {v['sha256'][:12]})")
return proto | {"sha256": actual}
def check_rids(rids, P: dict) -> dict | None:
"""Guard for the diagnostic scripts (14, 15): realizations of the protocol_p2 main grid are refused; realizations of
the protocol_p2r main grid are allowed only if protocol_p2r and its inputs match their locked SHA-256 (returns that
protocol, else None). Every other realization is dev."""
bad = sorted(set(rids) & set(P["grid"]["realizations"]))
if bad:
raise SystemExit(f"realizations {bad} belong to the protocol_p2 main grid: diagnostics use dev realizations only")
path = REPO_ROOT / "configs" / "protocol_p2r.yaml"
P2r = yaml.safe_load(path.read_text())
main = set(rids) & set(P2r["grid"]["realizations"])
if not main:
return None
if set(rids) - main:
raise SystemExit("do not mix protocol_p2r main-grid realizations with dev realizations in one run")
expected = (REPO_ROOT / "configs" / "protocol_p2r.sha256").read_text().split()[0]
actual = hashlib.sha256(path.read_bytes()).hexdigest()
if actual != expected:
raise SystemExit(f"protocol_p2r.yaml changed after locking ({actual[:12]} ≠ {expected[:12]})")
for k, v in P2r["inputs"].items():
h = hashlib.sha256((REPO_ROOT / v["path"]).read_bytes()).hexdigest()
if h != v["sha256"]:
raise SystemExit(f"{v['path']} differs from the version recorded in protocol_p2r ({h[:12]} ≠ {v['sha256'][:12]})")
return P2r
def reg_settings(P: dict) -> dict:
r = P["registration"]
keys = ("S", "g_max", "sigma_a_ms", "sigma_b_ms", "kernel", "hyperprior", "hyper_starts", "ess_min_frac",
"shift_K", "wavelet_ms")
return {k: r[k] for k in keys}
def method_specs(out: dict, P: dict, names: list[str]) -> dict:
"""Training spec (bank_train.train_predict) for each method, with normalized labels."""
m0, s0 = out["norm"]
nb = lambda a: (a - m0) / s0
B, lam = out["banks"], out["lam"]
N = len(out["wells"])
T = P["training"]
specs = {}
for m in names:
base = m.removesuffix("-na")
if base in ("Oracle", "B3a", "B3b", "B3c", "B3d"):
specs[m] = {"kind": "bank", "Y": nb(B[base]), "logpi": np.zeros((N, 1)), "lam": lam}
elif base in ("B4a", "B4b"):
K = B["B4"].shape[1]
specs[m] = {"kind": "bank", "Y": nb(B["B4"]), "logpi": np.full((N, K), -np.log(K)),
"lam": None if base == "B4a" else lam}
elif base == "B4c":
specs[m] = {"kind": "softdtw", "Y": nb(B["B3b"])} | T["softdtw"]
elif base == "B4d":
specs[m] = {"kind": "dilate", "Y": nb(B["B3b"])} | T["dilate"]
elif base in ("M1", "M2"):
specs[m] = {"kind": "bank", "Y": nb(B[base]), "logpi": out["logpi"][base], "lam": lam}
elif base == "MSE0": # H1 with σ_δ = 0: Oracle labels, windowed MSE
from ml_porosity.models.bank_train import WIN, window_starts_fixed
Y = nb(B["Oracle"][:, 0])
specs[m] = {"kind": "mse_win", "Ywin": np.stack([Y[:, j: j + WIN] for j in window_starts_fixed(Y.shape[1])], 1)}
else:
raise ValueError(m)
return specs
def evaluate(yt: np.ndarray, mu: np.ndarray, sigma: np.ndarray, f_c: float) -> list[dict]:
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
return [point_metrics(a, m) | band_metrics(a, m, f_c) | gaussian_metrics(a, m, s) for a, m, s in zip(yt, mu, sigma)]
def run_cell(job) -> tuple[list[dict], list[dict], float]:
rid, c, N, seeds, budgets, P, device, out_dir = job
import torch
torch.set_num_threads(2)
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.models.bank_train import train_predict, zscore_patch
from ml_porosity.registration.pipeline import register
from ml_porosity.registration.warp_prior import WarpHyper
t0 = time.time()
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"]]
drift = WarpHyper(**prior["hyper"])
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
R = D2Realization(cfg, rid, hg, drift, wav)
G = P["grid"]
sa = cfg["anchors"]["sigma_a_ms"]
obs = [R.observe(w, c, G["snr_db"], sa, G["anchor_density"]) for w in R.pool[:N]]
test = [R.observe(w, c, G["snr_db"], sa) for w in R.test]
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])
reg = reg_settings(P)
h4 = "M1-na" in budgets
tcfg = P["training"]["model"] | P["training"]["optimizer"]
rows, diag, preds = [], [], {}
key = dict(rid=rid, c=c, n_train=N)
for seed in seeds:
out = register(R, obs, reg, seed)
specs = method_specs(out, P, [m for m in budgets if not m.endswith("-na")])
info = key | {"seed": seed, "phase": out["phase"], "lam": out["lam"], "tau_c": out["tau_c"]} | \
{f"hyper_{k}": v for k, v in out["hyper"].items() if k != "kernel"} | \
{"hyper_log_marginal": out["hyper_info"]["log_marginal"], "hyper_at_bound": ",".join(out["hyper_info"]["at_bound"])}
diag += [info | {"variant": "anchor"} | d for d in out["diag"]]
if h4:
na = register(R, obs, reg, seed, prior=dataclasses.replace(drift.scaled(c), sigma_b_ms=reg["sigma_b_ms"]))
specs |= method_specs(na, P, ["M1-na", "M2-na"])
diag += [key | {"seed": seed, "phase": na["phase"], "lam": na["lam"], "tau_c": na["tau_c"], "variant": "no_anchor"} | d
for d in na["diag"]]
m0, s0 = out["norm"]
for m, sp in specs.items():
bud = budgets[m] if isinstance(budgets[m], list) else [budgets[m]]
for b, (mu, sg) in train_predict(X, Xte, sp, tcfg, seed, bud, device).items():
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
for w, r in zip(R.test, evaluate(yt, mu_p, sg_p, P["metrics"]["bands"]["f_c_hz"])):
rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": w.name} | r)
preds[f"{m}/s{seed}/b{b}/mu"] = mu_p.astype(np.float32)
preds[f"{m}/s{seed}/b{b}/sigma"] = sg_p.astype(np.float32)
tag = f"r{rid}_c{c:g}_n{N}"
np.savez_compressed(out_dir / f"{tag}.npz", y_true=yt.astype(np.float32), test_wells=np.array([w.name for w in R.test]), **preds)
pd.DataFrame(diag).to_csv(out_dir / f"{tag}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{tag}.csv", index=False) # written last: marks the cell as done
return rows, diag, time.time() - t0
def select_budgets(df: pd.DataFrame) -> dict:
"""For each method: the budget with the smallest mean total RMSE (macro over test wells → mean over rid × N × seed)."""
run = df.groupby(["method", "budget", "rid", "n_train", "seed"])["rmse"].mean().groupby(["method", "budget"]).mean()
return {m: int(run.loc[m].idxmin()) for m in run.index.get_level_values(0).unique()}
def main() -> None:
ap = argparse.ArgumentParser()
mode = ap.add_mutually_exclusive_group(required=True)
mode.add_argument("--dev", action="store_true")
mode.add_argument("--main", action="store_true")
ap.add_argument("--workers", type=int, default=6)
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--only-cells", default="", help="cell filter, e.g. 'c=1,n=4' (testing only)")
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "3"}.items():
os.environ.setdefault(k, v)
P = load_protocol(check=args.main)
G = P["grid"]
if args.dev:
tag, rids, cs, ns, seeds = "dev", G["dev_realizations"], [G["realistic_drift"]], [4, 16], [0, 1]
budgets = {m: P["training"]["budget_candidates"] for m in METHODS + ["MSE0"]}
else:
tag, rids, cs, ns, seeds = "main", G["realizations"], G["drift_factors"], G["n_train"], G["seeds"]
budgets = dict(P["training"]["budgets"])
missing = [m for m in METHODS if m not in budgets]
if missing:
raise SystemExit(f"missing budgets for {missing} in protocol_p2")
out_dir = outputs_dir() / "p2" / tag
(out_dir / "cells").mkdir(parents=True, exist_ok=True)
flt = dict(kv.split("=") for kv in args.only_cells.split(",") if kv)
jobs = []
for rid in rids:
for c in cs:
for N in ns:
if ("c" in flt and float(flt["c"]) != c) or ("n" in flt and int(flt["n"]) != N):
continue
if (out_dir / "cells" / f"r{rid}_c{c:g}_n{N}.csv").exists():
continue
b = {m: budgets[m] for m in METHODS + (["MSE0"] if args.dev else [])}
if args.main and c == G["realistic_drift"] and N == 4:
b |= {"M1-na": budgets["M1"], "M2-na": budgets["M2"]}
jobs.append((rid, c, N, seeds, b, P, args.device, out_dir / "cells"))
jobs.sort(key=lambda j: -j[2]) # cells with large N run first for load balancing
print(f"{len(jobs)} cells to run, {args.workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(run_cell, j): j[:3] for j in jobs}
for i, f in enumerate(as_completed(futs), 1):
_, _, dt = f.result()
print(f"[{i}/{len(jobs)}] cell r{futs[f][0]} c={futs[f][1]:g} N={futs[f][2]} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
cells = sorted((out_dir / "cells").glob("r*_n*.csv"))
df = pd.concat([pd.read_csv(f) for f in cells if not f.name.endswith("_diag.csv")], ignore_index=True)
dg = pd.concat([pd.read_csv(f) for f in cells if f.name.endswith("_diag.csv")], ignore_index=True)
df.assign(protocol_sha256=P["sha256"][:12]).to_csv(out_dir / "results.csv", index=False)
dg.to_csv(out_dir / "diag.csv", index=False)
if args.dev:
sel = select_budgets(df)
(out_dir / "budgets.json").write_text(json.dumps(sel, indent=1))
print("selected budgets:", sel)
print(f"-> {out_dir} ({len(df)} rows, {time.time() - t0:.0f} s)")
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

154
scripts/12_h1_blur.py Normal file
View File

@@ -0,0 +1,154 @@
"""H1 (Prop 1): MSE training on labels with a random time shift δ ~ N(0, σ²) yields blurred predictions with
transfer function exp(−2π²σ²f²).
c = 0, N = 16, Oracle labels. Each (well, sub-window) receives one shift δ = σ·z held fixed throughout training
(z shared across all σ: common random numbers); MSE loss on μ. The transfer function is estimated on the test wells:
Ĥ(f) = Σ Re[Y* P_σ] / Σ Re[Y* P_0] (pooled over test wells, realizations, seeds; Hann taper)
and r(σ) = geometric mean of Ĥ/theory over the frequencies used (protocol_p2, hypotheses.H1).
python scripts/12_h1_blur.py [--workers 6] [--device cuda:1]
"""
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
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
_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)
NFFT = 256
def run_job(job) -> dict:
rid, seed, sigmas, budget, P, device = job
import torch
torch.set_num_threads(2)
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.models.bank_train import WIN, train_predict, window_starts_fixed, zscore_patch
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.pipeline import label_norm
from ml_porosity.registration.warp_prior import WarpHyper
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)
G, H = P["grid"], P["hypotheses"]["H1"]
sa = cfg["anchors"]["sigma_a_ms"]
obs = [R.observe(w, 0.0, G["snr_db"], sa) for w in R.pool[:16]]
test = [R.observe(w, 0.0, G["snr_db"], sa) for w in R.test]
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])
m0, s0 = label_norm(R, obs)
starts = window_starts_fixed(len(R.t_main))
tw = R.t_main[starts[:, None] + np.arange(WIN)] # (J, WIN)
z = np.random.default_rng([rid, seed, 7]).standard_normal((len(obs), len(starts)))
f = cfg["fine_dt_ms"]
tcfg = P["training"]["model"] | P["training"]["optimizer"]
preds = {}
for sg in sigmas:
Yw = np.stack([labels_for_warps(R.tau_fine, antialias(o["phi_log"], f, R.dt), o["t_of_tau_true"],
(tw + sg * z[i][:, None]).ravel()).reshape(tw.shape)
for i, o in enumerate(obs)])
mu = train_predict(X, Xte, {"kind": "mse_win", "Ywin": (Yw - m0) / s0}, tcfg, seed, [budget], device)[budget][0]
preds[sg] = 100 * (mu * s0 + m0)
return {"rid": rid, "seed": seed, "y_true": 100 * np.stack([o["y_true"] for o in test]),
"wells": [w.name for w in R.test], "preds": preds}
def cross_spectrum(Y: np.ndarray, Pr: 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((Pr - Pr.mean(1, keepdims=True)) * w, NFFT)
return np.real(np.conj(Fy) * Fp).sum(0)
def transfer(S: dict, f: np.ndarray, f_c: float) -> dict:
"""S[σ]: accumulated cross-spectrum Re[Y* P_σ]. Returns Ĥ, the theoretical curve, r(σ) and the number of frequencies used."""
band = f >= f_c
out = {"H_hat": {}, "theory": {}, "r": {}, "n_freq": {}}
for sg, Ss in S.items():
th = np.exp(-2 * np.pi**2 * (sg / 1000.0) ** 2 * f**2)
use = band & (th >= 0.1) & (S[0.0] >= 0.1 * S[0.0][band].max())
Hh = Ss / S[0.0]
out["H_hat"][sg], out["theory"][sg] = Hh.tolist(), th.tolist()
out["r"][sg] = float(np.exp(np.mean(np.log(np.clip(Hh[use] / th[use], 1e-3, None))))) if use.any() else float("nan")
out["n_freq"][sg] = int(use.sum())
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=6)
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--n-boot", type=int, default=2000)
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
P = run_d2.load_protocol(check=True)
H = P["hypotheses"]["H1"]
sigmas = [float(s) for s in H["sigma_ms"]]
budget = int(P["training"]["budgets"]["MSE0"])
rids, seeds = P["grid"]["realizations"], P["grid"]["seeds"]
out_dir = outputs_dir() / "p2" / "h1"
out_dir.mkdir(parents=True, exist_ok=True)
jobs = [(rid, s, sigmas, budget, P, args.device) for rid in rids for s in seeds]
t0 = time.time()
results = []
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
for i, fut in enumerate(as_completed([ex.submit(run_job, j) for j in jobs]), 1):
results.append(fut.result())
print(f"[{i}/{len(jobs)}] {time.time() - t0:.0f} s", flush=True)
results.sort(key=lambda r: (r["rid"], r["seed"]))
from ml_porosity.eval.metrics import band_metrics, point_metrics
f_c = P["metrics"]["bands"]["f_c_hz"]
rows = [{"rid": r["rid"], "seed": r["seed"], "sigma_ms": sg, "test_well": w} | point_metrics(y, p) | band_metrics(y, p, f_c)
for r in results for sg in sigmas for w, y, p in zip(r["wells"], r["y_true"], r["preds"][sg])]
pd.DataFrame(rows).assign(protocol_sha256=P["sha256"][:12]).to_csv(out_dir / "results.csv", index=False)
np.savez_compressed(out_dir / "preds.npz", **{f"r{r['rid']}/s{r['seed']}/sigma{sg:g}": r["preds"][sg] for r in results for sg in sigmas},
**{f"r{r['rid']}/y_true": r["y_true"] for r in results})
f = np.fft.rfftfreq(NFFT, 4.0 / 1000.0)
cs = {r["rid"]: {sg: 0.0 for sg in sigmas} for r in results} # cross-spectrum accumulated per realization
for r in results:
for sg in sigmas:
cs[r["rid"]][sg] = cs[r["rid"]][sg] + cross_spectrum(r["y_true"], r["preds"][sg])
tf = {"f_hz": f.tolist()} | transfer({sg: sum(cs[i][sg] for i in cs) for sg in sigmas}, f, f_c)
rng = np.random.default_rng(0)
boot = {sg: [] for sg in sigmas}
for _ in range(args.n_boot): # bootstrap over realizations
pick = rng.choice(list(cs), len(cs))
for sg, v in transfer({sg: sum(cs[i][sg] for i in pick) for sg in sigmas}, f, f_c)["r"].items():
boot[sg].append(v)
tf["r_ci95"] = {sg: [float(np.nanpercentile(boot[sg], 2.5)), float(np.nanpercentile(boot[sg], 97.5))] for sg in sigmas}
lo, hi = 0.5, 2.0
tf["reject_H1"] = bool(any(not (lo <= tf["r"][sg] <= hi) for sg in sigmas if sg > 0))
tf["budget"] = budget
tf["protocol_sha256"] = P["sha256"][:12]
(out_dir / "h1.json").write_text(json.dumps(tf, indent=1))
print("r(σ):", {sg: round(v, 3) for sg, v in tf["r"].items()}, "CI:", tf["r_ci95"], "reject H1:", tf["reject_H1"])
print(f"-> {out_dir} ({time.time() - t0:.0f} s)")
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

494
scripts/13_summarize_p2.py Normal file
View File

@@ -0,0 +1,494 @@
"""P2 summary per protocol_p2: gate G-B, v1 phase map, H1, H3, H4 and warp diagnostics.
Reads each cell in outputs/p2/<mode>/cells, so it can run before the grid is finished (the gate then records
complete = false). A run is (realization, c, N, method, seed); a run's metric is the mean over the 8 test wells at
the method's locked budget. 95% CIs are bootstrapped over realizations (each realization averaged over seeds); the
cell's best competitor is held fixed during bootstrapping.
python scripts/13_summarize_p2.py [--mode main|dev] [--n-boot 2000]
→ outputs/p2/summary/<mode>/: gate_gb.json, cells.csv, methods.csv, h3.csv, h3.json, h4.json, warp.csv, h1.csv, summary.md
figures outputs/figures/p2_{phase,band_lines,h3,h1}.png (dev mode: in the summary directory)
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import math
import re
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.patches import Rectangle
from ml_porosity.eval import figstyle as fs
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
from ml_porosity.paths import REPO_ROOT, outputs_dir
METRICS = ["rmse", "pcc", "low_rmse", "band_rmse", "band_pcc", "band_std_ratio", "nll", "crps", "mean_sigma",
"coverage_50", "coverage_80", "coverage_90", "coverage_95"]
LEVELS = (50, 80, 90, 95)
# thresholds stated verbally in protocol_p2 (gates.G-B, hypotheses.H3, H4)
RATIO_MAX, DPCC_MIN, GUARD, SEED_FRAC, N_FRAC = 0.90, 0.05, 1.02, 4 / 5, 3 / 4
H3_WIDTH, H4_WARP, H4_BAND = 1.2, 1.10, 1.02
RAMP4 = ["#86b6ef", "#5598e7", "#256abf", "#104281"] # 4-step ordinal ramp (σ of H1), validated
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
def parse_tag(stem: str) -> tuple[int, float, int]:
rid, c, n = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)", stem).groups()
return int(rid), float(c), int(n)
def ce(d):
"""Calibration error: mean |coverage − nominal| over 50/80/90/95%."""
return sum(abs(d[f"coverage_{q}"] - q / 100) for q in LEVELS) / len(LEVELS)
def boot(num: np.ndarray, den: np.ndarray | None, n_boot: int, rng) -> list[float]:
"""95% CI of mean(num)/mean(den) (den = None: of mean(num)) under resampling of realizations."""
idx = rng.integers(0, len(num), (n_boot, len(num)))
s = num[idx].mean(1) if den is None else num[idx].mean(1) / den[idx].mean(1)
return np.percentile(s, [2.5, 97.5]).tolist()
def load_runs(cell_dir, budgets: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
files = sorted(f for f in cell_dir.glob("r*_c*_n*.csv") if not f.name.endswith("_diag.csv"))
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
df = df[df["budget"] == df["method"].map(lambda m: budgets[m.removesuffix("-na")])]
run = df.groupby(["rid", "c", "n_train", "method", "seed"], as_index=False)[METRICS].mean()
diag = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True)
return run, diag
# ---------------------------------------------------------------- G-B
def improves(m2: pd.DataFrame, best: pd.DataFrame) -> pd.Series:
return (m2["band_rmse"] <= RATIO_MAX * best["band_rmse"]) | (m2["band_pcc"] >= best["band_pcc"] + DPCC_MIN)
def gate_gb(run: pd.DataFrame, P: dict, n_boot: int, rng) -> tuple[pd.DataFrame, dict]:
G, grid = P["gates"]["G-B"], P["grid"]
rows = []
for (c, N), d in run.groupby(["c", "n_train"]):
mean = d.groupby("method")[["band_rmse", "band_pcc"]].mean()
comp = mean.loc[mean.index.intersection(G["competitors"]), "band_rmse"].sort_values()
best = comp.index[0]
a = d[d.method == "M2"].set_index(["rid", "seed"])[["band_rmse", "band_pcc"]]
b = d[d.method == best].set_index(["rid", "seed"])[["band_rmse", "band_pcc"]].reindex(a.index)
ok = b.notna().all(axis=1)
a, b = a[ok], b[ok]
imp = {lvl: improves(a.groupby(lvl).mean(), b.groupby(lvl).mean()) for lvl in ("seed", "rid")}
ar, br = a.groupby("rid").mean(), b.groupby("rid").mean()
n_s, n_r = len(imp["seed"]), len(imp["rid"])
rows.append({
"c": c, "n_train": N, "best": best, "runner_up": comp.index[1], "n_rid": n_r, "n_seed": n_s,
"m2_band_rmse": a["band_rmse"].mean(), "best_band_rmse": b["band_rmse"].mean(),
"ratio": a["band_rmse"].mean() / b["band_rmse"].mean(),
**dict(zip(("ratio_lo", "ratio_hi"), boot(ar["band_rmse"].to_numpy(), br["band_rmse"].to_numpy(), n_boot, rng))),
"dpcc": a["band_pcc"].mean() - b["band_pcc"].mean(),
**dict(zip(("dpcc_lo", "dpcc_hi"), boot((ar["band_pcc"] - br["band_pcc"]).to_numpy(), None, n_boot, rng))),
"seeds_improve": int(imp["seed"].sum()), "rids_improve": int(imp["rid"].sum()),
"cell_pass": bool(imp["seed"].sum() >= math.ceil(SEED_FRAC * n_s - 1e-9) and imp["rid"].sum() > n_r / 2),
"ratio_vs_B3b": a["band_rmse"].mean() / mean.loc["B3b", "band_rmse"],
})
cells = pd.DataFrame(rows)
real, zero = cells[cells.c == grid["realistic_drift"]], cells[cells.c == 0]
need = math.ceil(N_FRAC * len(grid["n_train"]) - 1e-9)
macro = zero.m2_band_rmse.mean() / zero.best_band_rmse.mean() if len(zero) else float("nan")
guard = bool(len(zero) == len(grid["n_train"]) and macro <= GUARD and (zero.ratio <= GUARD).all())
complete = bool(len(cells) == len(grid["drift_factors"]) * len(grid["n_train"])
and (cells.n_rid == len(grid["realizations"])).all() and (cells.n_seed == len(grid["seeds"])).all())
verdict = {
"complete": complete, "cells": len(cells),
"realistic_cells_pass": f"{int(real.cell_pass.sum())}/{len(real)}",
"realistic_pass": bool(real.cell_pass.sum() >= need),
"zero_drift_macro_ratio": macro, "zero_drift_ratio_per_N": {int(r.n_train): r.ratio for r in zero.itertuples()},
"zero_drift_guard": guard,
}
verdict["pass"] = verdict["realistic_pass"] and guard
return cells, verdict
# ---------------------------------------------------------------- H3, H4, warp
def h3_table(cell_dir, P: dict, budgets: dict, pairs=(("B5", "B3b"), ("M2-ens", "M2")), pattern=None) -> pd.DataFrame:
"""B5 / M2-ens: μ = mean of μ_s, σ² = mean of σ_s² + variance of μ_s over 5 seeds (from saved predictions).
pairs: (ensemble name, method); pattern: defaults to the c = 1 cells."""
f_c, c1 = P["metrics"]["bands"]["f_c_hz"], P["grid"]["realistic_drift"]
rows = []
for f in sorted(cell_dir.glob(pattern or f"r*_c{c1:g}_n*.npz")):
rid, c, N = parse_tag(f.stem)
z = np.load(f)
yt = z["y_true"].astype(float)
for name, m in pairs:
ks = sorted(k for k in z.files if k.startswith(f"{m}/s") and k.endswith(f"/b{budgets[m]}/mu"))
if not ks:
continue
mu = np.stack([z[k] for k in ks]).astype(float)
sg = np.stack([z[k[:-2] + "sigma"] for k in ks]).astype(float)
mu_e, sg_e = mu.mean(0), np.sqrt((sg**2).mean(0) + mu.var(0))
per_well = [point_metrics(y, a) | band_metrics(y, a, f_c) | gaussian_metrics(y, a, s) for y, a, s in zip(yt, mu_e, sg_e)]
rows.append({"rid": rid, "c": c, "n_train": N, "method": name, "members": len(ks)}
| pd.DataFrame(per_well)[METRICS].mean().to_dict())
e = pd.DataFrame(rows)
return e.assign(ce=ce(e))
def h3_verdict(e: pd.DataFrame, run: pd.DataFrame, P: dict, n_boot: int, rng) -> dict:
def judge(d):
m = d.groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean()
a, b = m.loc["M2-ens"], m.loc["B5"]
width = a.mean_sigma / b.mean_sigma
return {"ce_m2ens": a.ce, "ce_b5": b.ce, "width_ratio": width, "nll_m2ens": a.nll, "nll_b5": b.nll,
"crps_m2ens": a.crps, "crps_b5": b.crps,
"reject_H3": bool(a.ce >= b.ce or (width > H3_WIDTH and a.nll >= b.nll and a.crps >= b.crps))}
out = {"pooled": judge(e), "per_N": {int(N): judge(d) for N, d in e.groupby("n_train")}}
per_rid = e.groupby(["method", "rid"])["ce"].mean()
diff = (per_rid.loc["M2-ens"] - per_rid.loc["B5"]).to_numpy()
out["pooled"] |= {"dce": float(diff.mean()), "dce_ci95": boot(diff, None, n_boot, rng)}
s = run[(run.c == P["grid"]["realistic_drift"]) & run.method.isin(["B3b", "M2"])]
out["single_model"] = s.assign(ce=ce(s)).groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean().to_dict("index")
return out
def h4(run: pd.DataFrame, diag: pd.DataFrame, n_boot: int, rng) -> dict:
d = diag[(diag.c == 1) & (diag.n_train == 4)]
if "no_anchor" not in set(d.variant):
return {"available": False}
w = d.groupby(["variant", "rid"])[["M1_warp_rmse_ms", "M2_warp_rmse_ms", "M1_warp_cov90", "M2_warp_cov90"]].mean()
r = run[(run.c == 1) & (run.n_train == 4)].groupby(["method", "rid"])[["band_rmse", "band_pcc"]].mean()
out = {"available": True}
for m in ("M1", "M2"):
wa, wn = w.loc["anchor", f"{m}_warp_rmse_ms"].to_numpy(), w.loc["no_anchor", f"{m}_warp_rmse_ms"].to_numpy()
ba, bn = r.loc[m, "band_rmse"].to_numpy(), r.loc[f"{m}-na", "band_rmse"].to_numpy()
out[m] = {"warp_rmse_anchor_ms": wa.mean(), "warp_rmse_no_anchor_ms": wn.mean(), "warp_ratio": wn.mean() / wa.mean(),
"warp_ratio_ci95": boot(wn, wa, n_boot, rng),
"warp_cov90_anchor": w.loc["anchor", f"{m}_warp_cov90"].mean(),
"warp_cov90_no_anchor": w.loc["no_anchor", f"{m}_warp_cov90"].mean(),
"band_rmse_anchor": ba.mean(), "band_rmse_no_anchor": bn.mean(), "band_ratio": bn.mean() / ba.mean(),
"band_ratio_ci95": boot(bn, ba, n_boot, rng),
"band_pcc_anchor": r.loc[m, "band_pcc"].mean(), "band_pcc_no_anchor": r.loc[f"{m}-na", "band_pcc"].mean()}
out["reject_H4"] = bool(out["M2"]["warp_ratio"] <= H4_WARP and out["M2"]["band_ratio"] <= H4_BAND)
return out
def warp_table(diag: pd.DataFrame) -> pd.DataFrame:
"""Means per (variant, c, N): per-well warp error; phase, λ, τ_c and hyperparameters per registration run."""
cols = [c for c in diag.columns if c.endswith("_warp_rmse_ms")] + \
["M1_warp_cov90", "M2_warp_cov90", "M2_warp_width90_ms", "n_anchor", "n_valid", "gamma", "ess", "ess_gamma1"]
per_well = diag.groupby(["variant", "c", "n_train"])[cols].mean()
reg = diag.drop_duplicates(["variant", "rid", "c", "n_train", "seed"])
per_reg = reg.groupby(["variant", "c", "n_train"]).agg(
phase_zero=("phase", lambda p: float(np.mean(p == 0))), phase_within15=("phase", lambda p: float(np.mean(np.abs(p) <= 15))),
lam=("lam", "mean"), tau_c=("tau_c", "mean"), m_g=("hyper_m_g", "mean"), sigma_g=("hyper_sigma_g", "mean"),
ell_ms=("hyper_ell_ms", "mean"), at_bound=("hyper_at_bound", lambda s: float(s.notna().mean())))
return per_well.join(per_reg).reset_index()
# ---------------------------------------------------------------- H1
def h1_summary(P: dict, s12) -> dict | None:
d = outputs_dir() / "p2" / "h1"
if not (d / "h1.json").exists():
return None
h = json.loads((d / "h1.json").read_text())
res = pd.read_csv(d / "results.csv")
tab = res.groupby(["rid", "seed", "sigma_ms"])[["rmse", "band_rmse", "band_pcc", "band_std_ratio"]].mean() \
.groupby("sigma_ms").mean()
# cross-spectrum rebuilt from saved predictions to recover the frequencies used (same rule as scripts/12) and to check r(σ)
z = np.load(d / "preds.npz")
f, f_c = np.array(h["f_hz"]), P["metrics"]["bands"]["f_c_hz"]
S = {}
for k in z.files:
rid, _, sg = k.split("/") if k.count("/") == 2 else (None, None, None)
if sg is not None:
S[float(sg[5:])] = S.get(float(sg[5:]), 0.0) + s12.cross_spectrum(z[f"{rid}/y_true"], z[k])
tf = s12.transfer(S, f, f_c)
assert all(abs(tf["r"][sg] - h["r"][str(sg)]) < 1e-9 for sg in S), "rebuilt r(σ) differs from h1.json"
use = {sg: (f >= f_c) & (np.array(tf["theory"][sg]) >= 0.1) & (S[0.0] >= 0.1 * S[0.0][f >= f_c].max()) for sg in S}
tab["r"] = [h["r"][str(sg)] for sg in tab.index]
tab["r_lo"], tab["r_hi"] = zip(*[h["r_ci95"][str(sg)] for sg in tab.index])
tab["n_freq"] = [h["n_freq"][str(sg)] for sg in tab.index]
return {"json": h, "table": tab, "f": f, "use": use, "H": tf["H_hat"], "theory": tf["theory"]}
# ---------------------------------------------------------------- figures
def text_on(rgba) -> str:
lum = 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]
return fs.INK if lum > 0.55 else fs.SURFACE
def plot_phase(cells: pd.DataFrame, verdict: dict, P: dict, path) -> None:
fs.apply()
cs, Ns = sorted(cells.c.unique()), sorted(cells.n_train.unique())
fig, axes = plt.subplots(1, 2, figsize=(13, 1.2 + 1.25 * len(cs)), layout="constrained") # leave room for colorbar labels
panels = [("ratio", "(a) Band RMSE: M2 / best competitor", fs.diverging_norm(0.8, 1.0, 1.2), fs.DIVERGING,
"{:.3f}", [RATIO_MAX, 1.0], "ratio (< 1: M2 better; threshold 0.90)"),
("dpcc", "(b) Band PCC: M2 − best competitor", fs.diverging_norm(-0.1, 0.0, 0.1), fs.DIVERGING.reversed(),
"{:+.3f}", [0.0, DPCC_MIN], "difference (> 0: M2 better; threshold +0.05)")]
ix = cells.set_index(["c", "n_train"])
for ax, (k, title, norm, cmap, fmt, ticks, clabel) in zip(axes, panels):
Z = ix[k].unstack("n_train").reindex(index=cs, columns=Ns).to_numpy()
im = ax.imshow(Z, cmap=cmap, norm=norm, origin="lower", aspect="auto")
for i, c in enumerate(cs):
for j, N in enumerate(Ns):
if (c, N) not in ix.index:
continue
r = ix.loc[(c, N)]
col = text_on(cmap(norm(r[k])))
ax.text(j, i + 0.2, fmt.format(r[k]), ha="center", va="center", fontsize=11, color=col)
ax.text(j, i - 0.02, f"[{fmt.format(r[k + '_lo'])}, {fmt.format(r[k + '_hi'])}]", ha="center",
va="center", fontsize=7, color=col)
if k == "ratio":
ax.text(j, i - 0.22, f"vs {r.best}", ha="center", va="center", fontsize=8, color=col)
ax.text(j, i - 0.38, f"{'✓' if r.cell_pass else '✗'} {r.seeds_improve}/{r.n_seed} seed · "
f"{r.rids_improve}/{r.n_rid} rz", ha="center", va="center", fontsize=6.5, color=col)
c1 = P["grid"]["realistic_drift"]
ax.set_xticks(range(len(Ns)), [str(n) for n in Ns])
ax.set_yticks(range(len(cs)), [f"{c:g}" + ("\n(realistic)" if c == c1 else "") for c in cs])
ax.set(xlabel="number of training wells N", ylabel="drift factor c (× F3 prior)", title=title)
ax.grid(False)
if c1 in cs:
ax.add_patch(Rectangle((-0.5, cs.index(c1) - 0.5), len(Ns), 1, fill=False, ec=fs.INK, lw=1.6))
cb = fig.colorbar(im, ax=ax, shrink=0.9, extend="both", pad=0.1)
for t in ticks:
cb.ax.axhline(t, color=fs.INK, lw=1.0)
cb.set_label(clabel, color=fs.INK2)
cb.outline.set_visible(False)
v = verdict
head = (f"Gate G-B: {'PASS' if v['pass'] else 'FAIL'} — c = 1: {v['realistic_cells_pass']} cells pass (required ≥ 3/4); "
f"c = 0: macro ratio {v['zero_drift_macro_ratio']:.3f} (required ≤ 1.02 both macro and per N) → "
f"{'held' if v['zero_drift_guard'] else 'violated'}{'' if v['complete'] else ' · INCOMPLETE GRID'}")
fig.suptitle(head, x=0.02, ha="left", fontsize=10, color=fs.INK)
fig.text(0.02, -0.02, "Each cell: mean over 8 realizations × 5 seeds (8 test wells per run); [95% CI, bootstrap over realizations, "
"competitor fixed]; ✓/✗: a cell passes if M2 improves (ratio ≤ 0.90 or PCC +0.05) in ≥ 4/5 seeds and > 1/2 of realizations (rz).",
fontsize=7.5, color=fs.INK2)
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
def direct_labels(ax, items, x, gap_frac=0.08) -> None:
"""items: [(y, label)] at the right edge; spread vertically to avoid overlap, in ink colour."""
lo, hi = ax.get_ylim()
items = sorted(items)
ys = [items[0][0]]
for y, _ in items[1:]:
ys.append(max(y, ys[-1] + gap_frac * (hi - lo)))
for (y0, t), y in zip(items, ys):
ax.annotate(t, (x, y0), xytext=(x + 0.12, y), textcoords="data", fontsize=8, color=fs.INK2, va="center",
annotation_clip=False)
def plot_lines(run: pd.DataFrame, cells: pd.DataFrame, path, n_boot: int, rng) -> None:
fs.apply()
cs, Ns = sorted(run.c.unique()), sorted(run.n_train.unique())
per_rid = run.groupby(["c", "n_train", "method", "rid"])[["band_rmse", "band_pcc"]].mean()
best = cells.set_index(["c", "n_train"])["best"]
series = [("M2", fs.BLUE, "o", "-", "M2"), ("best", fs.ORANGE, "s", "-", "best competitor in cell"),
("B3b", fs.AQUA, "^", "-", "B3b (tie marker)"), ("Oracle", fs.MUTED, None, "--", "Oracle (true warp; upper bound)")]
fig, axes = plt.subplots(2, len(Ns), figsize=(2.7 * len(Ns) + 1.2, 6.0), sharey="row", squeeze=False)
for i, (k, ylab) in enumerate([("band_rmse", "band RMSE (p.u.)"), ("band_pcc", "band PCC")]):
for j, N in enumerate(Ns):
ax = axes[i, j]
ends = []
for name, col, mk, ls, lab in series:
pts = []
for c in cs:
m = best.get((c, N)) if name == "best" else name
if m is None or (c, N, m) not in per_rid.index:
continue
v = per_rid.loc[(c, N, m), k].to_numpy()
pts.append((c, v.mean(), *boot(v, None, n_boot, rng), m))
if not pts:
continue
x, y, lo, hi, who = zip(*pts)
ax.plot(x, y, color=col, marker=mk, ls=ls, ms=5, lw=1.0 if name == "Oracle" else 1.5, label=lab,
zorder=3 if name == "M2" else 2)
if name != "Oracle":
ax.vlines(x, lo, hi, color=col, lw=1.0, zorder=2)
if name == "best":
for xx, yy, ww in zip(x, y, who):
ax.annotate(ww, (xx, yy), xytext=(0, -11 if i == 0 else 7), textcoords="offset points",
ha="center", fontsize=6.5, color=fs.INK2)
ends.append((y[-1], lab.split(" (")[0] if name != "best" else "best"))
ax.axvspan(0.85, 1.15, color=fs.GRID, alpha=0.45, lw=0, zorder=0)
ax.set_xticks(cs, [f"{c:g}" for c in cs])
ax.set_xlim(min(cs) - 0.15, max(cs) + 0.15)
if i == 0:
ax.set_title(f"N = {N} training wells")
if i == 1:
ax.set_xlabel("drift factor c")
if j == 0:
ax.set_ylabel(ylab)
if j == len(Ns) - 1 and ends:
direct_labels(ax, ends, max(cs))
h, l = axes[0, 0].get_legend_handles_labels()
fig.legend(h, l, loc="upper left", ncol=4, bbox_to_anchor=(0.06, 1.02))
fig.text(0.06, -0.03, "Markers: mean over 8 realizations × 5 seeds; bars: 95% CI, bootstrap over realizations. "
"Grey band: realistic drift (c = 1). Labels at orange squares: the competitor with the lowest band RMSE in the cell.",
fontsize=7.5, color=fs.INK2)
fig.tight_layout()
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
def plot_h3(e: pd.DataFrame, path) -> None:
fs.apply()
Ns = sorted(e.n_train.unique())
fig, axes = plt.subplots(1, len(Ns), figsize=(2.6 * len(Ns) + 1.0, 3.2), sharey=True, squeeze=False)
nom = np.array(LEVELS) / 100
for ax, N in zip(axes[0], Ns):
d = e[e.n_train == N].groupby("method")[[f"coverage_{q}" for q in LEVELS] + ["ce"]].mean()
ax.plot([0.4, 1], [0.4, 1], color=fs.AXIS, lw=1.0, ls="--")
for m, col, mk in (("M2-ens", fs.BLUE, "o"), ("B5", fs.ORANGE, "s")):
if m in d.index:
ax.plot(nom, d.loc[m].iloc[:4].to_numpy(), color=col, marker=mk, ms=5, label=m)
ax.set(title=f"N = {N}", xlabel="nominal level", xlim=(0.4, 1.0), ylim=(0, 1.0))
ax.text(0.42, 0.95, "\n".join(f"CE {m}: {d.loc[m, 'ce']:.3f}" for m in ("M2-ens", "B5") if m in d.index),
va="top", fontsize=7.5, color=fs.INK2)
axes[0, 0].set_ylabel("empirical coverage")
axes[0, 0].legend(loc="lower right")
fig.suptitle("H3 (c = 1): coverage of central intervals, 5-seed ensemble; dashed: perfect calibration",
x=0.02, ha="left", fontsize=10)
fig.tight_layout()
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
def plot_h1(h1: dict, path) -> None:
fs.apply()
f, tab = h1["f"], h1["table"]
fig, (ax, bx) = plt.subplots(1, 2, figsize=(11, 3.9), gridspec_kw={"width_ratios": [1.6, 1]})
sig = [s for s in sorted(h1["use"]) if s > 0]
for s, col in zip(sig, RAMP4):
th, H, u = np.array(h1["theory"][s]), np.array(h1["H"][s]), h1["use"][s]
ax.plot(f, th, color=col, lw=1.0, ls="--")
ax.plot(f[u], H[u], color=col, lw=1.8, marker="o", ms=2.5, label=f"σ = {s:g} ms")
ax.annotate(f"σ = {s:g} ms", (f[u][-1], H[u][-1]), xytext=(5, 0), textcoords="offset points", va="center",
fontsize=8, color=fs.INK2)
ax.axvspan(0, 6, color=fs.GRID, alpha=0.6, lw=0)
ax.text(3, -0.12, "< 6 Hz\nnot used", ha="center", fontsize=7, color=fs.INK2)
ax.set(xlim=(0, 80), ylim=(-0.2, 1.3), xlabel="frequency (Hz)", ylabel="transfer function",
title="(a) Estimated Ĥ(f) (solid, frequencies used) and exp(−2π²σ²f²) (dashed)")
ax.legend(loc="upper right")
s = tab.index[tab.index > 0]
bx.axhspan(0.5, 2.0, color=fs.GRID, alpha=0.6, lw=0)
bx.axhline(1.0, color=fs.AXIS, lw=1.0)
bx.vlines(s, tab.loc[s, "r_lo"], tab.loc[s, "r_hi"], color=fs.BLUE, lw=1.5)
bx.plot(s, tab.loc[s, "r"], "o", color=fs.BLUE, ms=6)
for x, r, n in zip(s, tab.loc[s, "r"], tab.loc[s, "n_freq"]):
bx.annotate(f"{r:.2f}\n{n} freq.", (x, r), xytext=(0, 9), textcoords="offset points", ha="center",
va="bottom", fontsize=8, color=fs.INK2)
bx.set_xscale("log", base=2)
bx.set_yscale("log", base=2)
bx.set_xticks(list(s), [f"{x:g}" for x in s])
bx.set_yticks([0.25, 0.5, 1, 2, 4], ["0.25", "0.5", "1", "2", "4"])
bx.set(xlim=(3, 50), ylim=(0.25, 4), xlabel="σ_δ (ms)", ylabel="r(σ) = geometric mean of Ĥ / theory",
title="(b) r(σ), 95% CI over realizations; shaded: non-rejection region [0.5, 2]")
rej = h1["json"]["reject_H1"]
fig.suptitle(f"H1 (Prop 1, c = 0, N = 16, MSE): {'rejected' if rej else 'not rejected'}", x=0.02, ha="left", fontsize=10)
fig.tight_layout()
fig.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
# ---------------------------------------------------------------- markdown
def md(df: pd.DataFrame, fmt: str = ".3f") -> str:
return df.to_markdown(floatfmt=fmt)
def write_md(path, P, verdict, cells, methods, h3j, h4j, warp, h1) -> None:
c1 = P["grid"]["realistic_drift"]
L = [f"# P2 summary (protocol {P['sha256'][:12]})", ""]
L += [f"## Gate G-B: {'PASS' if verdict['pass'] else 'FAIL'}" + ("" if verdict["complete"] else " (incomplete grid)"), "",
f"- c = {c1:g}: {verdict['realistic_cells_pass']} cells pass (required ≥ 3/4) → realistic_pass = {verdict['realistic_pass']}",
f"- c = 0: macro ratio {verdict['zero_drift_macro_ratio']:.4f}, per N "
f"{ {k: round(v, 4) for k, v in verdict['zero_drift_ratio_per_N'].items()} } → guard = {verdict['zero_drift_guard']}", ""]
t = cells.set_index(["c", "n_train"])[["best", "runner_up", "ratio", "ratio_lo", "ratio_hi", "dpcc", "dpcc_lo", "dpcc_hi",
"seeds_improve", "rids_improve", "cell_pass", "ratio_vs_B3b"]]
L += [md(t), ""]
for k, lab in (("band_rmse", "band RMSE (p.u.)"), ("band_pcc", "band PCC"), ("rmse", "total RMSE (p.u.)")):
piv = methods.pivot_table(index="method", columns=["c", "n_train"], values=k)
piv.columns = [f"c{c:g}/N{n}" for c, n in piv.columns]
L += [f"### {lab} by method (mean over realizations × seeds)", "", md(piv), ""]
if h3j:
rows = {"pooled": h3j["pooled"]} | {f"N = {n}": v for n, v in h3j["per_N"].items()}
L += [f"## H3: {'rejected' if h3j['pooled']['reject_H3'] else 'not rejected'} (pooled over all N at c = {c1:g})", "",
md(pd.DataFrame(rows).T.drop(columns="dce_ci95", errors="ignore")), "",
f"ΔCE (M2-ens − B5) = {h3j['pooled']['dce']:.4f}, 95% CI {np.round(h3j['pooled']['dce_ci95'], 4).tolist()}", "",
"Single model (mean over 5 individual seeds):", "", md(pd.DataFrame(h3j["single_model"]).T), ""]
if h4j.get("available"):
L += [f"## H4: {'rejected' if h4j['reject_H4'] else 'not rejected'} (c = 1, N = 4)", "",
md(pd.DataFrame({m: {k: (str(np.round(v, 3).tolist()) if isinstance(v, list) else v) for k, v in h4j[m].items()}
for m in ("M1", "M2")}).T, ".3f"), ""]
if h1 is not None:
L += [f"## H1: {'rejected' if h1['json']['reject_H1'] else 'not rejected'} (budget MSE0 = {h1['json']['budget']})", "",
md(h1["table"]), ""]
L += ["## Warp diagnostics (means over training wells; phase/λ/hyperparameters per registration run)", "",
md(warp.set_index(["variant", "c", "n_train"]).T, ".3f"), ""]
path.write_text("\n".join(L))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--mode", choices=["main", "dev"], default="main")
ap.add_argument("--n-boot", type=int, default=2000)
args = ap.parse_args()
s11, s12 = load_script("11_run_d2.py"), load_script("12_h1_blur.py")
P = s11.load_protocol(check=args.mode == "main")
budgets = P["training"]["budgets"]
cell_dir = outputs_dir() / "p2" / args.mode / "cells"
out = outputs_dir() / "p2" / "summary" / args.mode
out.mkdir(parents=True, exist_ok=True)
figs = outputs_dir() / "figures" if args.mode == "main" else out
rng = np.random.default_rng(0)
run, diag = load_runs(cell_dir, budgets)
methods = run.groupby(["c", "n_train", "method"])[METRICS].mean().reset_index()
cells, verdict = gate_gb(run, P, args.n_boot, rng)
e = h3_table(cell_dir, P, budgets)
h3j = h3_verdict(e, run, P, args.n_boot, rng) if len(e) else None
h4j = h4(run, diag, args.n_boot, rng)
warp = warp_table(diag)
h1 = h1_summary(P, s12)
verdict |= {"protocol_sha256": P["sha256"][:12], "n_boot": args.n_boot}
(out / "gate_gb.json").write_text(json.dumps(verdict, indent=1, ensure_ascii=False))
cells.to_csv(out / "cells.csv", index=False)
methods.to_csv(out / "methods.csv", index=False)
e.to_csv(out / "h3.csv", index=False)
(out / "h3.json").write_text(json.dumps(h3j, indent=1, ensure_ascii=False, default=float))
(out / "h4.json").write_text(json.dumps(h4j, indent=1, ensure_ascii=False, default=float))
warp.to_csv(out / "warp.csv", index=False)
if h1 is not None:
h1["table"].to_csv(out / "h1.csv")
plot_h1(h1, figs / "p2_h1.png")
write_md(out / "summary.md", P, verdict, cells, methods, h3j, h4j, warp, h1)
plot_phase(cells, verdict, P, figs / "p2_phase.png")
plot_lines(run, cells, figs / "p2_band_lines.png", args.n_boot, rng)
if len(e):
plot_h3(e, figs / "p2_h3.png")
print(json.dumps(verdict, indent=1, ensure_ascii=False))
print(cells[["c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]]
.to_string(index=False, float_format="%.3f"))
if h3j:
print("H3:", {k: round(v, 4) if isinstance(v, float) else v for k, v in h3j["pooled"].items() if k != "dce_ci95"})
if h4j.get("available"):
print("H4 rejected:", h4j["reject_H4"], {m: (round(h4j[m]["warp_ratio"], 3), round(h4j[m]["band_ratio"], 3)) for m in ("M1", "M2")})
if h1 is not None:
print("H1:", h1["table"][["r", "r_lo", "r_hi", "n_freq"]].round(3).to_dict("index"))
print("->", out)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,202 @@
"""Post-G-B diagnostics, steps 1–2 (plan §9): seismic-conditioned warp posterior via SMC tempering.
python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --workers 4 --device cuda:1
Dev realizations, or the protocol_p2r main grid (realizations 8–15, only if protocol_p2r and its inputs match the
locked SHA-256; scripts/run_p2r_main.sh); realizations of the protocol_p2 main grid are refused. Each job (rid, c, N, seed): register
as in protocol_p2 (pipeline.register: MAP-II hyperparameters, statistical wavelet + constant phase, old M1/M2, B3b–d),
re-estimate the constant phase by SMC over the training wells (smc.smc_fit_phase), then run SMC per well from P
anchor-posterior samples through the γ milestones: γ of the old M2 (g_old), γ = 1/κ at the best anchor sample (g_acf)
and γ = 1 (g_one). Four wavelets: "est" (statistical spectrum, protocol_p2 phase), "estR" (statistical spectrum,
re-estimated phase — the proposed method), "est0" (statistical spectrum, zero phase = true D2 phase) and "true" (true
D2 wavelet); est0 and true serve only as upper bounds, not as methods. B3c is recomputed for each wavelet. Writes warp
errors (RMSE of τ(t) over the main window — for SMC, the error of the posterior-mean warp, i.e. B3d on the new
posterior — 90% coverage and width), the log-likelihood at the true warp, log Z_w over phase (smc_fit_phase) and the
SMC samples (est, estR) to outputs/p2/diag/posterior/. --device cpu runs smc.py (numpy); any other device runs
smc_torch.py (same algorithm and random streams; matches the numpy version up to rounding error).
Stress tests (dev only; defaults = protocol_p2): --snr and --anchor-density change the observed data; --sigma-a-reg
changes the σ_a used for registration (data are still generated with the σ_a of d2_synth.yaml); --smc-seeds k reruns
the anchor sampling, phase and SMC with random stream k (registration seed kept) to measure run-to-run stability;
--wavelets drops some of the upper-bound wavelets. Each setting should write to its own --out-dir.
"""
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
_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)
OLD = ["B3b", "B3c", "B3d", "M1", "M2"]
SAVE = {("est", "g_acf"), ("estR", "g_acf"), ("estR", "g_one")}
WAVELETS = ("est", "estR", "est0", "true")
def job_tag(rid, c, N, seed, smc_seed=None) -> str:
return f"r{rid}_c{c:g}_n{N}_s{seed}" + ("" if smc_seed is None else f"_k{smc_seed}")
def run_job(job) -> pd.DataFrame:
rid, c, N, seed, n_part, P, out_dir, device, mem_gb, st = job
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
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
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)
obs = [R.observe(w, c, st["snr_db"], cfg["anchors"]["sigma_a_ms"], st["anchor_density"]) for w in R.pool[:N]]
reg = run_d2.reg_settings(P)
if st["sigma_a_reg"] is not None:
reg["sigma_a_ms"] = st["sigma_a_reg"]
k = seed if st["smc_seed"] is None else st["smc_seed"] # random stream for anchor samples, phase and SMC
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 other processes
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)
out = register(R, obs, 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"], n_part, 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])
key = dict(rid=rid, c=c, n_train=N, seed=seed, smc_seed=k, particles=n_part, snr_db=st["snr_db"],
anchor_density=st["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 = {"est": phase_wavelet(B, out["phase"]), "estR": phase_wavelet(B, phase_r),
"est0": phase_wavelet(B, 0.0), "true": R.w_fine}
wavelets = {wn: wf for wn, wf in wavelets.items() if wn in st["wavelets"]}
rows, saved = [], {}
for i, o in enumerate(obs):
d = out["diag"][i]
for m in OLD:
e = {k.removeprefix(f"{m}_"): v for k, v in d.items() if k.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():
if wn != "est":
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 = {"g_old": d["gamma"], "g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
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["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 (wn, name) in SAVE:
saved[f"{o['name']}/{wn}/{name}"] = U.astype(np.float32)
tag = job_tag(rid, c, N, seed, st["smc_seed"])
(out_dir / f"{tag}_phase.json").write_text(json.dumps({"phase0": out["phase"], "phase_R": phase_r} | ph))
np.savez_compressed(out_dir / f"{tag}_particles.npz", **saved)
df = pd.DataFrame(rows)
df.to_csv(out_dir / f"{tag}.csv", index=False)
return df
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--rids", type=int, nargs="+", default=[900, 901])
ap.add_argument("--c", type=float, nargs="+", default=[1.0])
ap.add_argument("--n", type=int, nargs="+", default=[16])
ap.add_argument("--seeds", type=int, nargs="+", default=[0])
ap.add_argument("--particles", type=int, default=256)
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--device", default="cuda:1", help="cpu: smc.py; cuda:k: smc_torch.py")
ap.add_argument("--gpu-mem-gb", type=float, default=2.0, help="per-worker GPU memory allocation cap (GiB)")
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/posterior")
ap.add_argument("--snr", type=float, default=None, help="seismic SNR (dB); default: grid.snr_db of protocol_p2")
ap.add_argument("--anchor-density", default=None, choices=["full", "half", "topbottom"])
ap.add_argument("--sigma-a-reg", type=float, default=None, help="σ_a (ms) used for registration; default as in protocol_p2")
ap.add_argument("--smc-seeds", type=int, nargs="+", default=None,
help="each k: an independent SMC run (random stream k); files get the suffix _k<k>")
ap.add_argument("--wavelets", nargs="+", default=list(WAVELETS), choices=WAVELETS)
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
P = run_d2.load_protocol(check=True)
if run_d2.check_rids(args.rids, P) is not None:
print("protocol_p2r main grid: protocol and inputs match the locked SHA-256", flush=True)
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "posterior"
out_dir.mkdir(parents=True, exist_ok=True)
G = P["grid"]
st = {"snr_db": G["snr_db"] if args.snr is None else args.snr,
"anchor_density": args.anchor_density or G["anchor_density"], "sigma_a_reg": args.sigma_a_reg,
"wavelets": args.wavelets}
jobs = [(r, c, n, s, args.particles, P, out_dir, args.device, args.gpu_mem_gb, st | {"smc_seed": k})
for r in args.rids for c in args.c for n in args.n for s in args.seeds for k in (args.smc_seeds or [None])
if not (out_dir / f"{job_tag(r, c, n, s, k)}.csv").exists()]
jobs.sort(key=lambda j: -j[2])
print(f"{len(jobs)} jobs, {args.workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(run_job, j): j[:4] + (j[-1]["smc_seed"],) for j in jobs}
for i, f in enumerate(as_completed(futs), 1):
f.result()
print(f"[{i}/{len(jobs)}] {futs[f]} done ({time.time() - t0:.0f} s)", flush=True)
df = pd.concat([pd.read_csv(f) for f in sorted(out_dir.glob("r*_s*.csv"))], ignore_index=True)
df.to_csv(out_dir / "warp.csv", index=False)
print(df.groupby(["rid", "c", "n_train"])[["phase", "phase_R", "phase_n", "phase_edge"]].first().to_string())
cols = ["warp_rmse_ms", "warp_cov90", "warp_width90_ms", "gamma"]
print(df.groupby(["c", "n_train", "wavelet", "method"])[cols].mean().round(3).to_string())
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

324
scripts/15_diag_train.py Normal file
View File

@@ -0,0 +1,324 @@
"""Post-G-B diagnostics, step 3 (plan §9): training on dev realizations with labels from the SMC posterior of scripts/14.
python scripts/15_diag_train.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 1 --workers 4
Dev realizations, or the protocol_p2r main grid (realizations 8–15, checked against the locked SHA-256 as in
scripts/14; scripts/run_p2r_main.sh). Each cell (rid, c, N): re-register as in protocol_p2 with a fixed registration seed (default 0,
the same seed as scripts/14, hence the same hyperparameters, old phase and old label bank), load the SMC samples and the
re-estimated phase from outputs/p2/diag/posterior/, then train with the same backbone, optimizer, windows and label
normalization as protocol_p2:
- existing methods (label banks from pipeline.register): Oracle, B3a–d, B4a–d, M2 at their locked budgets;
- M2@1, M2@3, M2@inf: the old M2 label bank with λ = 1, 3, ∞ (hard-min) instead of the cell's λ = 1/τ_c (λ diagnostic
of if_fail);
- B3c-R: B3c with the re-estimated-phase wavelet (smc_fit_phase);
- B3d-S·: mean warp over all SMC particles; M2-S·: label bank of S samples drawn at random from the SMC particles,
uniform π, the cell's λ. Suffixes: "e" old-phase wavelet, γ = 1/κ; "a" new-phase wavelet, γ = 1/κ; "1" new-phase
wavelet, γ = 1;
- M2-Sa@1, M2-Sa@3, M2-Sa@inf: as M2-Sa with λ = 1, 3, ∞.
Methods without a locked budget are run at every candidate budget of protocol_p2 and selected by the protocol's rule
(lowest total RMSE at c = 1, averaged over rid × N × seed; band metrics are not used). The training seed controls only
the network initialization. A G-B-style gate is recomputed for each candidate against two competitor sets: that of
protocol_p2 ("p2"), and that set plus B3c-R and B3d-S from the same posterior ("full"); over 2 realizations × 2 seeds,
cell_pass requires both.
→ outputs/p2/diag/train/: cells/r{rid}_c{c}_n{N}.csv (+ _diag.csv), results.csv, runs.csv, budgets.json, gate.csv,
gate.json
Stress tests (preparation of protocol_p2r, dev only): --snr, --anchor-density and --sigma-a-reg must match the
scripts/14 run in --post-dir (checked via the register phase). The SNR also changes the seismic of the test wells.
--variants selects variants with particles in --post-dir (the scripts/14 stress grid stores only estR: "a" and "1");
--methods restricts the methods; --budgets-from reuses budgets selected in a previous run (budgets.json) instead of
running all candidates and reselecting; --save-preds stores per-seed μ, σ (cells/*.npz) to build seed ensembles as in
H3: B5 (B3b) versus the ensemble of each method, with the same rejection rule as protocol_p2 (→ h3.csv, h3.json).
"""
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")
OLD = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M2"]
VARIANTS = {"e": ("est", "g_acf"), "a": ("estR", "g_acf"), "1": ("estR", "g_one")}
LAMS = {"1": 1.0, "3": 3.0, "inf": None}
CANDIDATES = ["M2", *[f"M2@{k}" for k in LAMS], *[f"M2-S{v}" for v in VARIANTS], *[f"M2-Sa@{k}" for k in LAMS]]
def run_cell(job) -> tuple[list[dict], float]:
rid, c, N, seeds, reg_seed, P, device, post_dir, out_dir, st = job
import torch
torch.set_num_threads(2)
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 train_predict, zscore_patch
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.pipeline import register
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
from ml_porosity.registration.warp_prior import WarpHyper
t0 = time.time()
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, st["snr_db"], sa, st["anchor_density"]) for w in R.pool[:N]]
test = [R.observe(w, c, st["snr_db"], sa) for w in R.test]
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])
reg = run_d2.reg_settings(P)
if st["sigma_a_reg"] is not None:
reg["sigma_a_ms"] = st["sigma_a_reg"]
tcfg = P["training"]["model"] | P["training"]["optimizer"]
variants = {v: VARIANTS[v] for v in st["variants"]}
out = register(R, obs, reg, reg_seed)
tag = f"r{rid}_c{c:g}_n{N}_s{reg_seed}"
ph = json.loads((post_dir / f"{tag}_phase.json").read_text())
if ph["phase0"] != out["phase"]:
raise RuntimeError(f"{tag}: register phase ({out['phase']}) differs from scripts/14 ({ph['phase0']})")
smc = np.load(post_dir / f"{tag}_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)
err = lambda t, o: warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
banks = {m: [] for m in ["B3c-R", *[f"{p}-S{v}" for v in variants for p in ("B3d", "M2")]]}
logpi = {v: [] for v in variants}
key = dict(rid=rid, c=c, n_train=N)
diag = []
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))
d = key | {"reg_seed": reg_seed, "phase": out["phase"], "phase_R": ph["phase_R"], "lam": out["lam"],
"well": o["name"], "B3c-R_warp_rmse_ms": err(t3c, o)}
for v, (wn, gn) in variants.items():
U = smc[f"{o['name']}/{wn}/{gn}"].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[f"B3d-S{v}"].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[f"M2-S{v}"].append(Y)
logpi[v].append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum()))
d |= {f"B3d-S{v}_warp_rmse_ms": err(tm, o), f"M2-S{v}_n_valid": int(ok.sum())}
diag.append(d)
m0, s0 = out["norm"]
cand, locked = P["training"]["budget_candidates"], P["training"]["budgets"]
specs = {m: (sp, [locked[m]]) for m, sp in run_d2.method_specs(out, P, OLD).items()}
nbank = {m: ((np.stack(v) - m0) / s0).astype(np.float32) for m, v in banks.items()}
single = lambda Y: {"kind": "bank", "Y": Y, "logpi": np.zeros((N, 1)), "lam": out["lam"]}
specs |= {f"M2@{k}": (specs["M2"][0] | {"lam": lam}, cand) for k, lam in LAMS.items()}
specs |= {m: (single(nbank[m]), cand) for m in ["B3c-R", *[f"B3d-S{v}" for v in variants]]}
for v in variants:
sp = {"kind": "bank", "Y": nbank[f"M2-S{v}"], "logpi": np.stack(logpi[v]).astype(np.float32), "lam": out["lam"]}
specs[f"M2-S{v}"] = (sp, cand)
if v == "a":
specs |= {f"M2-Sa@{k}": (sp | {"lam": lam}, cand) for k, lam in LAMS.items()}
if st["methods"]:
specs = {m: s for m, s in specs.items() if m in st["methods"]}
if st["budgets"]:
specs = {m: (sp, [st["budgets"][m]] if m in st["budgets"] else bud) for m, (sp, bud) in specs.items()}
rows, preds = [], {}
for seed in seeds:
for m, (sp, bud) in specs.items():
for b, (mu, sg) in train_predict(X, Xte, sp, tcfg, seed, bud, device).items():
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
for w, r in zip(R.test, run_d2.evaluate(yt, mu_p, sg_p, P["metrics"]["bands"]["f_c_hz"])):
rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": w.name} | r)
if st["save_preds"]:
preds[f"{m}/s{seed}/b{b}/mu"] = mu_p.astype(np.float32)
preds[f"{m}/s{seed}/b{b}/sigma"] = sg_p.astype(np.float32)
stem = f"r{rid}_c{c:g}_n{N}"
if preds:
np.savez_compressed(out_dir / f"{stem}.npz", y_true=yt.astype(np.float32),
test_wells=np.array([w.name for w in R.test]), **preds)
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the cell as complete
return rows, time.time() - t0
def summarize(cell_dir: Path, out_dir: Path, P: dict, args) -> None:
sp13 = load_script("13_summarize_p2.py")
files = sorted(f for f in cell_dir.glob("r*_c*_n*.csv") if not f.name.endswith("_diag.csv"))
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
dg = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True)
G = P["grid"]
locked = P["training"]["budgets"]
free = sorted(set(df.method) - set(OLD))
if args.budgets_from:
fixed = json.loads(args.budgets_from.read_text())
budgets = {m: int(locked[m] if m in OLD else fixed[m]) for m in sorted(set(df.method))}
else:
budgets = {m: int(locked[m]) for m in OLD} | run_d2.select_budgets(df[(df.c == G["realistic_drift"]) & df.method.isin(free)])
(out_dir / "budgets.json").write_text(json.dumps(budgets, indent=1))
df.to_csv(out_dir / "results.csv", index=False)
dg.to_csv(out_dir / "diag.csv", index=False)
df = df[df["budget"] == df["method"].map(budgets)]
run = df.groupby(["rid", "c", "n_train", "method", "seed"], as_index=False)[sp13.METRICS].mean()
run.to_csv(out_dir / "runs.csv", index=False)
tab = run.groupby(["c", "n_train", "method"])[["band_rmse", "band_pcc", "rmse"]].mean().unstack("method")
pd.set_option("display.width", 250)
print("budgets:", budgets)
print(tab["band_rmse"].round(3).to_string())
print(tab["band_pcc"].round(3).to_string())
print(dg.groupby(["c", "n_train"])[[k for k in dg.columns if k.endswith("warp_rmse_ms")]].mean().round(2).to_string())
grid = G | {"realizations": sorted(run.rid.unique().tolist()), "seeds": sorted(run.seed.unique().tolist()),
"n_train": sorted(run.n_train.unique().tolist()), "drift_factors": sorted(run.c.unique().tolist())}
comp_p2 = P["gates"]["G-B"]["competitors"]
rng = np.random.default_rng(0)
rows, verdicts = [], {}
for cand in CANDIDATES:
if cand not in set(run.method):
continue
v = cand.split("@")[0].removeprefix("M2-S") if cand.startswith("M2-S") else None
sets = {"p2": comp_p2}
if v is not None:
sets["full"] = comp_p2 + ["B3c-R", f"B3d-S{v}"]
for sname, comp in sets.items():
r = run[run.method.isin(comp) | (run.method == cand)]
if cand != "M2":
r = r[r.method != "M2"].replace({"method": {cand: "M2"}})
Pg = P | {"grid": grid, "gates": {"G-B": P["gates"]["G-B"] | {"competitors": comp}}}
cells, verdict = sp13.gate_gb(r, Pg, args.n_boot, rng)
rows.append(cells.assign(candidate=cand, competitors=sname))
verdicts[f"{cand}/{sname}"] = verdict
if not rows: # e.g. --methods B3d alone: no gate candidate trained
print("no gate candidate among the trained methods; gate skipped")
return
gate = pd.concat(rows, ignore_index=True)
gate.to_csv(out_dir / "gate.csv", index=False)
(out_dir / "gate.json").write_text(json.dumps(verdicts, indent=1, default=float))
cols = ["candidate", "competitors", "c", "n_train", "best", "m2_band_rmse", "best_band_rmse", "ratio", "dpcc",
"seeds_improve", "rids_improve", "cell_pass"]
print(gate[cols].round(3).to_string())
print(pd.DataFrame(verdicts).T[["realistic_cells_pass", "zero_drift_macro_ratio", "zero_drift_guard", "pass"]].to_string())
if any(cell_dir.glob("r*_c*_n*.npz")):
h3_ensembles(cell_dir, out_dir, P, budgets, sp13, args.n_boot, rng)
def h3_ensembles(cell_dir: Path, out_dir: Path, P: dict, budgets: dict, sp13, n_boot: int, rng) -> None:
"""As H3 of protocol_p2, but for every method with saved predictions: seed ensemble (μ = mean of μ_s,
σ² = mean of σ_s² + variance of μ_s) versus B5 in each cell (c, N), with the same rejection rule."""
pairs = [("B5", "B3b")] + [(f"{m}-ens", m) for m in budgets if m != "B3b"]
e = sp13.h3_table(cell_dir, P, budgets, pairs=pairs, pattern="r*_c*_n*.npz")
e.to_csv(out_dir / "h3.csv", index=False)
res = {}
for cand in sorted(set(e.method) - {"B5"}):
for (c, N), d in e.groupby(["c", "n_train"]):
m = d.groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean()
if cand not in m.index or "B5" not in m.index:
continue
a, b = m.loc[cand], m.loc["B5"]
width = a.mean_sigma / b.mean_sigma
per_rid = d.groupby(["method", "rid"])["ce"].mean()
diff = (per_rid.loc[cand] - per_rid.loc["B5"]).to_numpy()
res[f"{cand}/c{c:g}/n{N}"] = {
"ce": a.ce, "ce_b5": b.ce, "dce": float(diff.mean()), "dce_ci95": sp13.boot(diff, None, n_boot, rng),
"width_ratio": width, "nll": a.nll, "nll_b5": b.nll, "crps": a.crps, "crps_b5": b.crps,
"members": int(d.loc[d.method == cand, "members"].min()),
"reject_H3": bool(a.ce >= b.ce or (width > sp13.H3_WIDTH and a.nll >= b.nll and a.crps >= b.crps))}
(out_dir / "h3.json").write_text(json.dumps(res, indent=1, default=float))
print(pd.DataFrame(res).T[["ce", "ce_b5", "dce", "width_ratio", "nll", "nll_b5", "crps", "crps_b5", "members",
"reject_H3"]].to_string())
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--rids", type=int, nargs="+", default=[900, 901])
ap.add_argument("--c", type=float, nargs="+", default=[0.0, 1.0, 2.0])
ap.add_argument("--n", type=int, nargs="+", default=[4, 16])
ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1])
ap.add_argument("--reg-seed", type=int, default=0)
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--device", default="cuda:1")
ap.add_argument("--n-boot", type=int, default=2000)
ap.add_argument("--post-dir", type=Path, default=None, help="default: outputs/p2/diag/posterior")
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/train")
ap.add_argument("--summary-only", action="store_true")
ap.add_argument("--snr", type=float, default=None, help="seismic SNR (dB) for all wells; default as in protocol_p2")
ap.add_argument("--anchor-density", default=None, choices=["full", "half", "topbottom"])
ap.add_argument("--sigma-a-reg", type=float, default=None, help="σ_a (ms) used for registration; default as in protocol_p2")
ap.add_argument("--variants", nargs="+", default=list(VARIANTS), choices=list(VARIANTS))
ap.add_argument("--methods", nargs="+", default=None, help="train only these methods (default: all)")
ap.add_argument("--budgets-from", type=Path, default=None,
help="budgets.json from a previous run: each method listed there is run only at that budget")
ap.add_argument("--save-preds", action="store_true", help="save per-seed μ, σ (cells/*.npz) for H3-style ensembles")
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
P = run_d2.load_protocol(check=True)
if run_d2.check_rids(args.rids, P) is not None:
print("protocol_p2r main grid: protocol and inputs match the locked SHA-256", flush=True)
post_dir = args.post_dir or outputs_dir() / "p2" / "diag" / "posterior"
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "train"
cell_dir = out_dir / "cells"
cell_dir.mkdir(parents=True, exist_ok=True)
G = P["grid"]
st = {"snr_db": G["snr_db"] if args.snr is None else args.snr,
"anchor_density": args.anchor_density or G["anchor_density"], "sigma_a_reg": args.sigma_a_reg,
"variants": args.variants, "methods": args.methods, "save_preds": args.save_preds,
"budgets": json.loads(args.budgets_from.read_text()) if args.budgets_from else None}
jobs = []
for rid in args.rids:
for c in args.c:
for N in args.n:
if (cell_dir / f"r{rid}_c{c:g}_n{N}.csv").exists() or args.summary_only:
continue
if not (post_dir / f"r{rid}_c{c:g}_n{N}_s{args.reg_seed}_particles.npz").exists():
print(f"skipping r{rid} c={c:g} N={N}: no SMC samples yet", flush=True)
continue
jobs.append((rid, c, N, args.seeds, args.reg_seed, P, args.device, post_dir, cell_dir, st))
jobs.sort(key=lambda j: -j[2])
print(f"{len(jobs)} cells, {args.workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(run_cell, j): j[:3] for j in jobs}
for i, f in enumerate(as_completed(futs), 1):
_, dt = f.result()
print(f"[{i}/{len(jobs)}] cell {futs[f]} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
summarize(cell_dir, out_dir, P, args)
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

208
scripts/16_f3_posterior.py Normal file
View File

@@ -0,0 +1,208 @@
"""Placing F3 on the σ_post axis (preparation of protocol_p2r, descriptive only): SMC warp posterior on the 4 real F3 wells.
python scripts/16_f3_posterior.py --device cuda:1
τ is sonic time (DT integrated from the first TD marker, as in scripts/09). Anchors are the TD markers within the
extended window 400–1300 ms; TD markers are not independent checkshots (plan §10). AI in τ is taken from the LAS AI log,
anti-alias filtered onto a 0.5 ms grid. The seismic is the central trace of the 3×3 patch at each well
(outputs/f3_wells.npz).
Registration as for D2 under protocol_p2:
- MAP-II hyperparameters on the anchors of the 4 wells (σ_a = 7 ms, σ_b = 50 ms fixed, hyperprior as in the protocol);
- 128 ms statistical wavelet from the 4 traces;
- initial phase from the old fit_phase, then re-estimated by SMC (log Z);
- SMC up to γ = 1/κ (g_acf) and γ = 1.
The "f3ml" variant uses the type-II ML hyperparameters of scripts/09 (σ_a ≈ 0.4 ms), i.e. treats the TD markers as
nearly exact relative to the seismic.
There is no true warp, hence no warp error. The script reports:
- σ_post: mean over the main window of (q95 − q05)/3.29 of τ(t);
- the particle standard deviation and κ;
- r between the synthetic at the posterior-mean warp and the seismic over the main window (same definition as the
r_post column of script 14);
- r of B3c and the RMS shift of the posterior-mean warp relative to B3b.
K independent SMC runs (--smc-seeds) measure the Monte Carlo error. The results only describe where F3 lies on the
σ_post and r axes of D2; they are not used to select γ, P or λ.
Outputs: outputs/p2/diag/f3_posterior/{wells.csv, phase.json, particles.npz}.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import time
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
_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)
TAU_RANGE = (200.0, 1500.0) # wider than scripts/09 so that τ(t) covers the seismic window ± half a wavelet at every well
PHASES = np.arange(-180, 180, 15)
def f3_wells(cfg: dict, tau_fine: np.ndarray) -> list[dict]:
from ml_porosity.data.las_io import load_well
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import sonic_tdr
D = np.load(outputs_dir() / "f3_wells.npz")
e0, e1 = cfg["ext_window_ms"]
out = []
for name in cfg["wells"]:
w = load_well(name)
cs = w.checkshot
base = sonic_tdr(w.md, w.curve("DT"), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
tk = cs.twt_ms.to_numpy()
tau_k = base.time_at(cs.md.to_numpy())
m = (tk >= e0) & (tk <= e1)
ai = log_to_time(w.md, w.curve("AI"), base, tau_fine, **cfg["resample"])
ok = np.isfinite(ai)
out.append({"name": name, "tau_k": tau_k[m], "t_k": tk[m],
"ai_log": np.interp(tau_fine, tau_fine[ok], ai[ok]), # outside the logged interval: constant (zero reflectivity)
"seis": D[f"{name}/seismic_patch"][4].astype(float), "t": D[f"{name}/times_ms"].astype(float),
"main": D[f"{name}/main_mask"].astype(bool)})
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--particles", type=int, default=256)
ap.add_argument("--smc-seeds", type=int, nargs="+", default=[0, 1, 2, 3])
ap.add_argument("--settings", nargs="+", default=["proto", "f3ml"], choices=["proto", "f3ml"])
ap.add_argument("--device", default="cuda:1", help="cpu: smc.py; cuda:k: smc_torch.py")
ap.add_argument("--gpu-mem-gb", type=float, default=2.0)
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/f3_posterior")
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "4", "MKL_NUM_THREADS": "4", "OPENBLAS_NUM_THREADS": "4"}.items():
os.environ.setdefault(k, v)
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.registration.labels import invert_warps
from ml_porosity.registration.pipeline import fit_cell_hyper
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 fine_wavelet, fit_phase, phase_loglik, synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper
if args.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(args.device)
if dev.type == "cuda":
total = torch.cuda.get_device_properties(dev).total_memory
torch.cuda.set_per_process_memory_fraction(min(1.0, args.gpu_mem_gb * 2**30 / total), dev)
wrap = lambda T: TiePosteriorTorch(T, args.device)
P = run_d2.load_protocol(check=True)
reg = run_d2.reg_settings(P)
cfg_d2 = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
cfg = yaml.safe_load((REPO_ROOT / "configs" / "d1_f3.yaml").read_text())
f, dt = cfg_d2["fine_dt_ms"], cfg_d2["dt_ms"]
fac = int(round(dt / f))
grid = WarpGrid(*TAU_RANGE, cfg_d2["warp_dtau_ms"])
tau_fine = np.arange(TAU_RANGE[0], TAU_RANGE[1] + f / 2, f)
wells = f3_wells(cfg, tau_fine)
t_out, mm = wells[0]["t"], wells[0]["main"]
if not all(np.array_equal(w["t"], t_out) and np.array_equal(w["main"], mm) for w in wells):
raise SystemExit("seismic time axes differ between wells")
t_main = t_out[mm]
t_fine = np.arange(t_out[0] - 300.0, t_out[-1] + 300.0 + f / 2, f)
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
w0 = statistical_wavelet(np.stack([w["seis"] for w in wells]), dt, reg["wavelet_ms"])
B = phase_basis(w0, fac)
qc = pd.read_csv(outputs_dir() / "tie_qc.csv").set_index(["well", "tdr"])["r_best_tie"]
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "f3_posterior"
out_dir.mkdir(parents=True, exist_ok=True)
rows, phases, saved = [], {}, {}
for setting in args.settings:
if setting == "proto":
h, hinfo = fit_cell_hyper(SimpleNamespace(grid=grid), wells, reg, seed=0)
hinfo = {k: hinfo[k] for k in ("log_marginal", "at_bound")}
else:
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())
h, hinfo = WarpHyper(**prior["fits"][P["inputs"]["warp_prior"]["fit"]]["hyper"]), {}
# initial phase as in pipeline.register: old fit_phase on S anchor-posterior samples at γ = 1
LL = []
for i, w in enumerate(wells):
smp = sample_warps(grid, h, w["tau_k"], w["t_k"], reg["S"], reg["g_max"], np.random.default_rng([0, i, 11]))
T = grid.t_of_tau(smp["b"], smp["g"], tau=tau_fine)
LL.append(phase_loglik(synth_for_warps(tau_fine, w["ai_log"], T, t_fine, t_out, fine_wavelet(w0, fac)),
w["seis"], PHASES))
phase0 = float(PHASES[fit_phase(LL, [np.ones(L.shape[1], bool) for L in LL], PHASES)])
for k in args.smc_seeds:
t0 = time.time()
Ts, Z0s = [], []
for i, w in enumerate(wells):
smp = sample_warps(grid, h, w["tau_k"], w["t_k"], args.particles, reg["g_max"],
np.random.default_rng([k, i, 13]))
Ts.append(wrap(TiePosterior(grid, h, w["tau_k"], w["t_k"], reg["g_max"], tau_fine, w["ai_log"], t_fine,
t_out, phase_wavelet(B, phase0), w["seis"], (t_main[0], t_main[-1]))))
Z0s.append(Ts[-1].z(smp["u"]))
phase_r, ph = smc_fit_phase(Ts, Z0s, B, phase0, [k, 19])
phases[f"{setting}/k{k}"] = {"phase0": phase0, "phase_R": phase_r} | ph
wf = phase_wavelet(B, phase_r)
key = {"setting": setting, "smc_seed": k, "particles": args.particles, "phase0": phase0, "phase_R": phase_r,
"phase_edge": ph["edge"]} | {f"hyper_{a}": b for a, b in h.as_dict().items() if a != "kernel"} | hinfo
for i, w in enumerate(wells):
T = Ts[i].with_wavelet(wf)
_, l0 = T.parts(Z0s[i])
cks = {"g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
t1 = time.time()
res = smc_tie_posterior(T, Z0s[i], cks.values(), np.random.default_rng([k, i, 17]))
t_b3b = tie_b3b(w["tau_k"], w["t_k"], tau_fine)
syn_b = synth_for_warps(tau_fine, w["ai_log"], t_b3b, t_fine, t_out, wf)[0]
t_b3c = tie_b3c(t_b3b, tau_fine, syn_b, w["seis"], t_out, dt)
syn_c = synth_for_warps(tau_fine, w["ai_log"], t_b3c[None], t_fine, t_out, wf)[0]
tau_b3b = invert_warps(t_b3b[None], tau_fine, t_main)[0]
info = {"well": w["name"], "n_anchor": len(w["tau_k"]), "kappa0": 1.0 / cks["g_acf"],
"n_stages": len(res["stages"]), "time_s": time.time() - t1, "r_b3b": ncc(syn_b, w["seis"]),
"r_b3c": ncc(syn_c, w["seis"]),
"b3c_vs_b3b_rms_ms": float(np.sqrt(np.nanmean((invert_warps(t_b3c[None], tau_fine, t_main)[0]
- tau_b3b) ** 2))),
"r_best_tie_calibrated": float(qc.get((w["name"], "calibrated"), np.nan))}
post = [("anchor", np.nan, Z0s[i])] + [(nm, g, res["Z"][float(g)]) for nm, g in cks.items()]
for nm, g, Z in post:
U = T.u(Z)
tau_t = invert_warps(grid.t_of_tau(U[:, 0], U[:, 1:], tau=tau_fine), tau_fine, t_main)
q05, q95 = np.nanquantile(tau_t, [0.05, 0.95], axis=0)
mean_tau = np.nanmean(tau_t, 0)
syn_m = T.synth(U.mean(0)[None])[0]
rows.append(key | info | {"posterior": nm, "gamma": g,
"logZ": res["logZ"].get(float(g), np.nan) if nm != "anchor" else np.nan,
"sigma_post_ms": float(np.mean(q95 - q05)) / 3.29,
"sd_post_ms": float(np.mean(np.nanstd(tau_t, 0))),
"shift_vs_b3b_rms_ms": float(np.sqrt(np.nanmean((mean_tau - tau_b3b) ** 2))),
"r_post": ncc(syn_m, w["seis"]), "kappa_post": residual_kappa(syn_m, w["seis"])})
saved[f"{setting}/k{k}/{w['name']}/{nm}/mean_tau"] = mean_tau.astype(np.float32)
if nm == "g_acf":
saved[f"{setting}/k{k}/{w['name']}/{nm}/U"] = U.astype(np.float32)
print(f"{setting} k={k}: φ0 {phase0:+.0f}°, φ_R {phase_r:+.1f}° ({time.time() - t0:.0f} s)", flush=True)
saved["t_main"] = t_main
np.savez_compressed(out_dir / "particles.npz", **saved)
(out_dir / "phase.json").write_text(json.dumps(phases, indent=1, default=float))
df = pd.DataFrame(rows)
df.to_csv(out_dir / "wells.csv", index=False)
cols = ["sigma_post_ms", "sd_post_ms", "r_post", "kappa_post", "kappa0", "shift_vs_b3b_rms_ms", "r_b3c",
"r_best_tie_calibrated"]
print(df.groupby(["setting", "posterior", "well"])[cols].mean().round(3).to_string())
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

View File

@@ -0,0 +1,391 @@
"""Summary of the dev experiments preparing protocol_p2r (scripts/run_p2r_dev.sh). Uses dev realizations 900/901 only.
python scripts/17_summarize_p2r_dev.py # every section with available data
python scripts/17_summarize_p2r_dev.py --only screen
Sections:
screen posterior stress grid (outputs/p2/diag/stress/snr*_{full,half,topbottom}/). Each cell (SNR, anchor
density, c) is averaged over rid × N × well:
- σ_post = width90/3.29 of τ(t);
- warp error, 90% coverage;
- r at the posterior-mean warp and at the true warp; κ; γ.
A cell is "wide" if σ_post (estR wavelet, γ = 1/κ) ≥ 1.5 ms. Threshold from Proposition 1: the transfer
coefficient at 50 Hz is exp(−2π²σ²f²) ≤ 0.90. Wide cells are written to wide_cells.txt, which the train
stage of run_p2r_dev.sh reads.
stability independent SMC runs (stability/p256, p1024; same registration seed):
- |Δτ̄(t)| between each pair of runs over the main window;
- p95 against the 0.5 ms criterion;
- spread of σ_post and of the re-estimated phase.
sigma_a registration with σ_a = 3.5 or 14 ms versus 7 ms; data are always generated with σ_a = 7 ms.
f3 F3 (f3_posterior/), descriptive only: σ_post, r, κ per well; |Δτ̄| between runs.
blur B(σ): band-RMSE penalty when dev Oracle predictions are blurred by σ (Proposition 1); a bound on the
attainable gain for H2b.
train training in the wide cells (train_stress/*) and H3 with the SMC posterior (h3_smc):
- band RMSE of M2-Sa / B3d-Sa / B3c-R / Oracle per cell;
- M2-Sa/B3d-Sa ratio per seed and per realization, joined with the cell's σ_post;
- H3 results written by scripts/15 (h3.json).
→ outputs/p2/diag/p2rdev/: screen.csv, wide_cells.txt, stability.csv, sigma_a.csv, f3.csv, train.csv, blur.csv, summary.md
"""
from __future__ import annotations
import argparse
import itertools
import json
import re
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
Z90 = 3.29 # width of the Gaussian 90% interval = 3.29 σ
WIDE_MS = 1.5
STAB_MS = 0.5
SMC = ["SMC_g_acf", "SMC_g_one"]
DIAG = outputs_dir() / "p2" / "diag"
def load_dir(d: Path, k_files: bool = False) -> pd.DataFrame | None:
files = [f for f in sorted(d.glob("r*_s*.csv")) if bool(re.search(r"_k\d+\.csv$", f.name)) == k_files]
return pd.concat([pd.read_csv(f) for f in files], ignore_index=True) if files else None
def cell_stats(df: pd.DataFrame, by: list[str]) -> pd.DataFrame:
s = df[df.method.isin(SMC)].assign(sigma_post_ms=lambda d: d.warp_width90_ms / Z90)
tab = s.groupby(by + ["wavelet", "method"]).agg(
sigma_post_ms=("sigma_post_ms", "mean"), sigma_post_min=("sigma_post_ms", "min"),
warp_rmse_ms=("warp_rmse_ms", "mean"), warp_cov90=("warp_cov90", "mean"), r_post=("r_post", "mean"),
r_true=("r_true", "mean"), kappa_post=("kappa_post", "mean"), gamma=("gamma", "mean"), n=("well", "size"))
b3c = (df[df.method == "B3c"].groupby(by + ["wavelet"])["warp_rmse_ms"].mean().rename("b3c_warp_rmse_ms"))
return tab.join(b3c, on=by + ["wavelet"]).reset_index()
# ---------------------------------------------------------------- screen
def screen(out: Path) -> pd.DataFrame | None:
parts = [load_dir(d) for d in sorted((DIAG / "stress").glob("snr*_*")) if re.fullmatch(r"snr-?\d+_[a-z]+", d.name)]
parts = [p for p in parts if p is not None]
if not parts:
return None
df = pd.concat(parts, ignore_index=True)
by = ["snr_db", "anchor_density", "c"]
tab = cell_stats(df, by)
per_n = cell_stats(df, by + ["n_train"])
tab.to_csv(out / "screen.csv", index=False)
per_n.to_csv(out / "screen_per_n.csv", index=False)
key = tab[(tab.wavelet == "estR") & (tab.method == "SMC_g_acf")]
wide = key[key.sigma_post_ms >= WIDE_MS]
with open(out / "wide_cells.txt", "w") as fh:
for (snr, dens), d in wide.groupby(["snr_db", "anchor_density"]):
fh.write(f"{snr:g} {dens} {' '.join(f'{c:g}' for c in sorted(d.c))}\n")
return tab
# ---------------------------------------------------------------- stability
def d2_axes() -> tuple:
from ml_porosity.registration.warp_prior import WarpGrid
P = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text())
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
f, dt = cfg["fine_dt_ms"], cfg["dt_ms"]
grid = WarpGrid(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1], cfg["warp_dtau_ms"])
tau_fine = np.arange(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1] + f / 2, f)
t_ext = np.arange(cfg["ext_window_ms"][0], cfg["ext_window_ms"][1] + dt / 2, dt)
m0, m1 = cfg["main_window_ms"]
return grid, tau_fine, t_ext[(t_ext >= m0) & (t_ext <= m1)]
def tau_of_t(U: np.ndarray, grid, tau_fine, t_main) -> np.ndarray:
from ml_porosity.registration.labels import invert_warps
return invert_warps(grid.t_of_tau(U[:, 0], U[:, 1:], tau=tau_fine), tau_fine, t_main)
def pair_diffs(means: dict) -> tuple[np.ndarray, list[float]]:
"""means: {k: τ̄_k(t)} → |Δ| concatenated over all pairs, and max |Δ| of each pair."""
d = [np.abs(means[a] - means[b]) for a, b in itertools.combinations(sorted(means), 2)]
return (np.concatenate(d) if d else np.array([])), [float(np.nanmax(x)) for x in d]
def stability(out: Path) -> pd.DataFrame | None:
dirs = sorted(d for d in (DIAG / "stability").glob("p*") if d.is_dir()) if (DIAG / "stability").exists() else []
if not dirs:
return None
grid, tau_fine, t_main = d2_axes()
rows = []
for d in dirs:
runs = {}
for f in sorted(d.glob("r*_s*_k*_particles.npz")):
rid, c, N, s, k = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)_s(\d+)_k(\d+)_particles", f.stem).groups()
runs.setdefault((int(rid), float(c), int(N)), {})[int(k)] = f
for (rid, c, N), ks in runs.items():
if len(ks) < 2:
continue
zs = {k: np.load(f) for k, f in ks.items()}
ph = {k: json.loads(f.with_name(f.name.replace("_particles.npz", "_phase.json")).read_text())["phase_R"]
for k, f in ks.items()}
wells = sorted({key.split("/")[0] for key in zs[min(zs)].files})
for variant in ("estR/g_acf", "estR/g_one"):
for w in wells:
means, sig = {}, {}
for k, z in zs.items():
T = tau_of_t(z[f"{w}/{variant}"].astype(float), grid, tau_fine, t_main)
means[k] = np.nanmean(T, 0)
q05, q95 = np.nanquantile(T, [0.05, 0.95], axis=0)
sig[k] = float(np.mean(q95 - q05)) / Z90
dd, mx = pair_diffs(means)
rows.append({"particles": d.name, "rid": rid, "c": c, "n_train": N, "variant": variant, "well": w,
"runs": len(ks), "d_p50": float(np.nanmedian(dd)), "d_p95": float(np.nanquantile(dd, 0.95)),
"d_max": float(np.nanmax(dd)), "pairs_max_gt1": int(sum(m > 1 for m in mx)),
"pairs": len(mx), "sigma_post_mean": float(np.mean(list(sig.values()))),
"sigma_post_sd": float(np.std(list(sig.values()))),
"phase_R_range": float(np.ptp(list(ph.values())))})
df = pd.DataFrame(rows)
df.to_csv(out / "stability.csv", index=False)
return df
def stability_table(df: pd.DataFrame) -> pd.DataFrame:
"""The pooled p95 of |Δ| over all wells × t × pairs is not a weighted mean of the per-well p95, so both the
median per-well p95 and the maximum p95 are reported; the criterion applies to the p95 of each cell (rid, c, N)
averaged over wells."""
g = df.groupby(["particles", "variant", "c"])
return g.agg(runs=("runs", "max"), wells=("well", "size"), d_p50=("d_p50", "median"), d_p95_median=("d_p95", "median"),
d_p95_mean=("d_p95", "mean"), d_p95_max=("d_p95", "max"), d_max=("d_max", "max"),
pairs_max_gt1=("pairs_max_gt1", "sum"), pairs=("pairs", "sum"), sigma_post=("sigma_post_mean", "mean"),
sigma_post_sd=("sigma_post_sd", "mean"), phase_R_range=("phase_R_range", "max")).reset_index()
# ---------------------------------------------------------------- σ_a, F3
def sigma_a(out: Path) -> pd.DataFrame | None:
parts = []
for d in [DIAG / "stress" / "snr10_full", *sorted((DIAG / "stress").glob("snr10_full_sa*"))]:
df = load_dir(d) if d.exists() else None
if df is not None:
parts.append(df)
if len(parts) < 2:
return None
df = pd.concat(parts, ignore_index=True)
old = df[df.method.isin(["M1", "M2"])].groupby(["sigma_a_reg", "c", "method"])[["warp_rmse_ms", "warp_cov90", "warp_width90_ms"]].mean()
tab = cell_stats(df, ["sigma_a_reg", "c"])
tab.to_csv(out / "sigma_a.csv", index=False)
old.reset_index().to_csv(out / "sigma_a_anchor.csv", index=False)
return tab
def f3(out: Path) -> tuple[pd.DataFrame, pd.DataFrame] | None:
d = DIAG / "f3_posterior"
if not (d / "wells.csv").exists():
return None
df = pd.read_csv(d / "wells.csv")
cols = ["sigma_post_ms", "sd_post_ms", "r_post", "kappa_post", "kappa0", "shift_vs_b3b_rms_ms", "r_b3b", "r_b3c",
"r_best_tie_calibrated", "n_anchor"]
tab = df.groupby(["setting", "posterior", "well"])[cols].mean()
tab["sigma_post_sd_runs"] = df.groupby(["setting", "posterior", "well"])["sigma_post_ms"].std()
tab = tab.reset_index()
z = np.load(d / "particles.npz")
rows = []
for setting, post, w in tab[["setting", "posterior", "well"]].itertuples(index=False):
means = {int(re.search(r"/k(\d+)/", k).group(1)): z[k] for k in z.files
if k.startswith(f"{setting}/k") and k.endswith(f"/{w}/{post}/mean_tau")}
dd, mx = pair_diffs(means)
if len(dd):
rows.append({"setting": setting, "posterior": post, "well": w, "d_p95": float(np.nanquantile(dd, 0.95)),
"d_max": float(np.nanmax(dd))})
stab = pd.DataFrame(rows)
tab = tab.merge(stab, on=["setting", "posterior", "well"], how="left") if len(stab) else tab
tab.to_csv(out / "f3.csv", index=False)
ph = json.loads((d / "phase.json").read_text())
return tab, pd.DataFrame([{"run": k, "phase0": v["phase0"], "phase_R": v["phase_R"], "edge": v.get("edge")}
for k, v in ph.items()])
# ---------------------------------------------------------------- train
TRAIN_METHODS = ["Oracle", "B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa", "B3d-S1", "M2-S1", "M2"]
def train(out: Path, screen_tab: pd.DataFrame | None) -> pd.DataFrame | None:
dirs = [(re.fullmatch(r"snr(-?\d+)_([a-z]+)", d.name), d) for d in sorted((DIAG / "train_stress").glob("snr*_*"))] \
if (DIAG / "train_stress").exists() else []
srcs = [(float(m.group(1)), m.group(2), d) for m, d in dirs if m and (d / "runs.csv").exists()]
if (DIAG / "h3_smc" / "runs.csv").exists():
srcs.append((10.0, "full", DIAG / "h3_smc"))
if not srcs:
return None
rows = []
for snr, dens, d in srcs:
run = pd.read_csv(d / "runs.csv")
for (c, N), g in run.groupby(["c", "n_train"]):
mean = g.groupby("method")["band_rmse"].mean()
pcc = g.groupby("method")["band_pcc"].mean()
r = {"source": d.name, "snr_db": snr, "anchor_density": dens, "c": c, "n_train": N,
**{f"band_rmse_{m}": mean.get(m, np.nan) for m in TRAIN_METHODS},
**{f"band_pcc_{m}": pcc.get(m, np.nan) for m in TRAIN_METHODS}}
for a, b in (("M2-Sa", "B3d-Sa"), ("M2-S1", "B3d-S1"), ("M2-Sa", "B3c-R"), ("B3d-Sa", "B3c-R")):
if a in mean and b in mean:
x = g[g.method == a].set_index(["rid", "seed"])["band_rmse"]
y = g[g.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index)
r |= {f"ratio_{a}/{b}": mean[a] / mean[b],
f"seeds_better_{a}/{b}": int(((x - y).groupby("seed").mean() < 0).sum()),
f"rids_better_{a}/{b}": int(((x - y).groupby("rid").mean() < 0).sum()),
"n_seed": int(x.index.get_level_values("seed").nunique()),
"n_rid": int(x.index.get_level_values("rid").nunique())}
rows.append(r)
df = pd.DataFrame(rows)
if screen_tab is not None:
key = screen_tab[(screen_tab.wavelet == "estR") & (screen_tab.method == "SMC_g_acf")]
df = df.merge(key[["snr_db", "anchor_density", "c", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]],
on=["snr_db", "anchor_density", "c"], how="left")
df.to_csv(out / "train.csv", index=False)
return df
# ---------------------------------------------------------------- blur
BLUR_SIGMAS = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0]
def blur(P: np.ndarray, sigma_ms: float, dt_ms: float = 4.0, L: int = 512) -> np.ndarray:
"""Gaussian filter of Proposition 1, exp(−2π²σ²f²), along the time axis (reflect padding)."""
n = P.shape[1]
a = L // 2 - n // 2
m = P.mean(1, keepdims=True)
Pp = np.pad(P - m, ((0, 0), (a, L - n - a)), mode="reflect")
f = np.fft.rfftfreq(L, dt_ms / 1000)
out = np.fft.irfft(np.fft.rfft(Pp) * np.exp(-2 * np.pi ** 2 * (sigma_ms / 1000) ** 2 * f ** 2), L)
return out[:, a:a + n] + m
def blur_sources() -> list[tuple[str, Path]]:
"""(source, cells directory) pairs with saved predictions: h3_smc (SNR 10, full) and train_stress/snr*_* (same source names as train())."""
srcs = [("h3_smc", DIAG / "h3_smc" / "cells")]
if (DIAG / "train_stress").exists():
srcs += [(d.name, d / "cells") for d in sorted((DIAG / "train_stress").glob("snr*_*"))]
return [(s, d) for s, d in srcs if d.exists() and any(d.glob("r*_c*_n*.npz"))]
def blur_curve(out: Path) -> pd.DataFrame | None:
"""Band-RMSE penalty when (dev) Oracle predictions are blurred by σ: B(σ) = band_rmse(blur_σ(μ)) / band_rmse(μ).
This bounds the gain from removing label blur: if B3d labels have errors ~ N(0, σ²) and RML removes them fully,
the best attainable M2/B3d ratio is ≈ 1/B(σ). Computed per source (regime), since noisy inputs already make
predictions smoother. Dev realizations only (cells/*.npz of h3_smc and train_stress)."""
from ml_porosity.eval.metrics import band_metrics
rows = []
for src, cells in blur_sources():
for f in sorted(cells.glob("r*_c*_n*.npz")):
rid, c, N = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)", f.stem).groups()
z = np.load(f)
Y = z["y_true"].astype(float)
for k in (k for k in z.files if k.startswith("Oracle/") and k.endswith("/mu")):
P0 = z[k].astype(float)
b0 = np.mean([band_metrics(Y[i], P0[i], 6)["band_rmse"] for i in range(len(Y))])
for s in BLUR_SIGMAS:
Pb = blur(P0, s)
rows.append({"source": src, "rid": int(rid), "c": float(c), "n_train": int(N), "seed": k.split("/")[1],
"sigma_ms": s,
"ratio": np.mean([band_metrics(Y[i], Pb[i], 6)["band_rmse"] for i in range(len(Y))]) / b0})
if not rows:
return None
df = pd.DataFrame(rows).groupby(["source", "n_train", "sigma_ms"])["ratio"].agg(["mean", "min", "max", "size"]).reset_index()
df.to_csv(out / "blur.csv", index=False)
return df
def dose_response(tr: pd.DataFrame, bl: pd.DataFrame | None) -> tuple[pd.DataFrame, pd.DataFrame]:
"""H2b on dev: M2-Sa/B3d-Sa ratio versus σ_post (c > 0), with the bound 1/B(σ_post) of the same source and N
(linear interpolation on the BLUR_SIGMAS grid; σ outside the grid is clamped to the edge). Spearman per N over
all cells."""
from scipy.stats import spearmanr
t = tr[(tr.c > 0) & tr["ratio_M2-Sa/B3d-Sa"].notna() & tr.sigma_post_ms.notna()].copy()
if bl is not None:
def bound(r):
b = bl[(bl.source == r.source) & (bl.n_train == r.n_train)]
return 1.0 / np.interp(r.sigma_post_ms, b.sigma_ms, b["mean"]) if len(b) else np.nan
t["bound_1/B"] = t.apply(bound, axis=1)
rows = []
for N, g in t.groupby("n_train"):
rho, p = spearmanr(g.sigma_post_ms, g["ratio_M2-Sa/B3d-Sa"]) if len(g) > 2 else (np.nan, np.nan)
wide, narrow = g[g.sigma_post_ms >= WIDE_MS], g[g.sigma_post_ms < WIDE_MS]
rows.append({"n_train": N, "cells": len(g), "spearman_rho": rho, "spearman_p": p,
"wide_cells": len(wide), "wide_ratio_mean": wide["ratio_M2-Sa/B3d-Sa"].mean(),
"wide_cells_ratio_lt1": int((wide["ratio_M2-Sa/B3d-Sa"] < 1).sum()),
"narrow_cells": len(narrow), "narrow_ratio_max": narrow["ratio_M2-Sa/B3d-Sa"].max()})
return t, pd.DataFrame(rows)
# ---------------------------------------------------------------- report
def md(df: pd.DataFrame, fmt: str = ".3f") -> str:
return df.to_markdown(index=False, floatfmt=fmt)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--only", nargs="+", default=None, choices=["screen", "stability", "sigma_a", "f3", "train", "blur"])
args = ap.parse_args()
want = lambda s: args.only is None or s in args.only
out = DIAG / "p2rdev"
out.mkdir(parents=True, exist_ok=True)
pd.set_option("display.width", 250)
lines = ["# Dev experiments for protocol_p2r (realizations 900/901)", ""]
tab = screen(out) if want("screen") or want("train") else None
if tab is not None:
key = tab[(tab.wavelet == "estR") & (tab.method == "SMC_g_acf")]
show = key[["snr_db", "anchor_density", "c", "sigma_post_ms", "sigma_post_min", "warp_rmse_ms", "warp_cov90",
"r_post", "r_true", "kappa_post", "gamma", "b3c_warp_rmse_ms"]].sort_values(["c", "anchor_density", "snr_db"])
lines += ["## Stress grid: SMC posterior (estR, γ = 1/κ)", "", md(show), "",
f"Wide cells (σ_post ≥ {WIDE_MS} ms): {len(key[key.sigma_post_ms >= WIDE_MS])}/{len(key)}", ""]
print(show.round(3).to_string(index=False))
if want("stability") and (st := stability(out)) is not None:
t = stability_table(st)
t["pass"] = t.d_p95_max <= STAB_MS
lines += ["## Run-to-run stability of SMC", "", md(t), "",
f"Criterion: p95 of |Δτ̄(t)| ≤ {STAB_MS} ms in every cell (column d_p95_max).", ""]
print(t.round(3).to_string(index=False))
if want("sigma_a") and (sa := sigma_a(out)) is not None:
show = sa[sa.method == "SMC_g_acf"][["sigma_a_reg", "c", "wavelet", "sigma_post_ms", "warp_rmse_ms", "warp_cov90",
"r_post", "gamma"]]
lines += ["## Registration σ_a (data generated with σ_a = 7 ms)", "", md(show), ""]
print(show.round(3).to_string(index=False))
if want("f3") and (r := f3(out)) is not None:
ft, ph = r
lines += ["## F3 (descriptive only)", "", md(ft), "", md(ph), ""]
print(ft.round(3).to_string(index=False))
print(ph.to_string(index=False))
tr = train(out, tab) if want("train") else None
if tr is not None:
cols = [c for c in tr.columns if c.startswith(("source", "snr", "anchor", "c", "n_train", "sigma_post", "ratio_",
"seeds_better", "rids_better"))
or c in {f"band_rmse_{m}" for m in ("Oracle", "B3c-R", "B3d-Sa", "M2-Sa")}]
lines += ["## Training in the wide cells and H3", "", md(tr[cols]), ""]
print(tr[cols].round(3).to_string(index=False))
for src in sorted(set(tr.source)):
for d in (DIAG / "train_stress" / src, DIAG / src):
if (d / "h3.json").exists():
h3 = pd.DataFrame(json.loads((d / "h3.json").read_text())).T
lines += [f"### H3 — {src}", "", md(h3.reset_index(names="ensemble/cell")), ""]
break
bl = blur_curve(out) if want("blur") else None
if bl is not None:
lines += ["## Band-RMSE penalty from blur (Proposition 1) on dev Oracle predictions", "", md(bl), "",
"B(σ) = band_rmse(blurred by σ) / band_rmse(original); 1/B(σ) is the best attainable M2/B3d ratio "
"if RML removes all blur.", ""]
print(bl.round(4).to_string(index=False))
if want("train") and tr is not None:
cells, dr = dose_response(tr, bl)
cols = ["source", "c", "n_train", "sigma_post_ms", "ratio_M2-Sa/B3d-Sa", "seeds_better_M2-Sa/B3d-Sa",
"rids_better_M2-Sa/B3d-Sa", *(["bound_1/B"] if "bound_1/B" in cells else [])]
cells = cells[cols].sort_values(["n_train", "sigma_post_ms"])
cells.to_csv(out / "dose_response.csv", index=False)
lines += ["## H2b on dev: M2-Sa/B3d-Sa versus σ_post", "", md(cells), "", md(dr), ""]
print(cells.round(3).to_string(index=False))
print(dr.round(3).to_string(index=False))
(out / "summary.md").write_text("\n".join(lines))
print(f"→ {out}")
if __name__ == "__main__":
main()

317
scripts/18_summarize_p2r.py Normal file
View File

@@ -0,0 +1,317 @@
"""Verdicts of protocol_p2r (configs/protocol_p2r.yaml) on its main grid (realizations 8–15; scripts/run_p2r_main.sh).
python scripts/18_summarize_p2r.py # reads outputs/p2r/{posterior,train}/<regime>/
python scripts/18_summarize_p2r.py --root DIR # another root with the same layout (e.g. a dry run on dev data)
Every rule below is the locked rule of protocol_p2r; this script only applies it.
H2a per full-anchor regime (R10, R0, Rm5): B3d-Sa against the best point tie {B3b, B3c, B3c-R} with the
protocol_p2 rule (band RMSE ≤ 0.90 × best OR band PCC ≥ best + 0.05; cell_pass ≥ 4/5 seeds AND > 1/2 of
realizations). Regime passes if c = 1 passes for both N and the c = 0 guard holds (≤ 1.02, macro and per N).
H2a passes if R10 passes. Also reported: M2-Sa under the same rule, the secondary competitor set with B3d,
c = 2 cells (flagged: unstable posterior).
σ_a arm the H2a rule at R10, c = 1, N 4/16 with every method registered with σ_a = 3.5 / 14 ms (no guard).
H2b at N = 16 over all cells (regime × c): ratio = band RMSE M2-Sa / B3d-Sa; σ_post from the SMC particles of
the train wells (no labels). a: M2-Sa < B3d-Sa (cell_pass) in ≥ 2/3 of wide cells (σ_post ≥ 1.5 ms);
b: Spearman ρ(σ_post, ratio) < 0 (one-sided permutation p reported); c: mean ratio over narrow cells ≤ 1.02.
N = 4 reported only. Mechanism: the ratio is compared with the blur bound 1/B(σ_post) from the Oracle
predictions of the same regime and N.
H3 descriptive only: CE, coverage 50/80/90/95%, NLL, CRPS, mean σ of each 5-seed ensemble at c = 1.
Ratios carry a 95% bootstrap CI over realizations (2000 resamples).
→ outputs/p2r/summary/: h2a.csv, sigma_a.csv, h2b.csv, h3.csv, sigma_post.csv, warp.csv, blur.csv, band_rmse.csv,
verdict.json, summary.md
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import math
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
sp13 = load_script("13_summarize_p2.py")
sp17 = load_script("17_summarize_p2r_dev.py")
P = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2r.yaml").read_text())
G = P["grid"]
H2A_REGIMES = P["hypotheses"]["H2a"]["regimes"]
POINT_TIES = P["hypotheses"]["H2a"]["competitors"]
WIDE_MS = 1.5
NARROW_GUARD, WIDE_FRAC = 1.02, 2 / 3
Z90 = sp17.Z90
N_PERM = 10000
# ---------------------------------------------------------------- inputs
def load_runs(root: Path) -> dict[str, pd.DataFrame]:
return {d.name: pd.read_csv(d / "runs.csv") for d in sorted((root / "train").glob("*")) if (d / "runs.csv").exists()}
def sigma_post(root: Path) -> pd.DataFrame:
"""σ_post per (setting, c, N): 90% width of τ(t) of the SMC particles (estR, γ = 1/κ), mean over train wells, / 3.29;
then mean over realizations. Warp error and coverage (true warp) are descriptive only."""
rows = []
for d in sorted((root / "posterior").glob("*")):
files = sorted(d.glob("r*_s*.csv"))
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_rid = 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"),
phase_R=("phase_R", "first"))
per_rid["sigma_post_ms"] = per_rid.width90 / Z90
rows.append(per_rid.groupby(["c", "n_train"]).agg(
sigma_post_ms=("sigma_post_ms", "mean"), sigma_post_min=("sigma_post_ms", "min"), sigma_post_max=("sigma_post_ms", "max"),
warp_rmse_ms=("warp_rmse_ms", "mean"), warp_cov90=("warp_cov90", "mean"), kappa_post=("kappa_post", "mean"),
n_rid=("width90", "size")).reset_index().assign(setting=d.name))
return pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
# ---------------------------------------------------------------- H2a
def h2a_cells(run: pd.DataFrame, cand: str, comp: list[str], rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
"""protocol_p2 G-B cell rule (scripts/13 gate_gb) with `cand` in the role of M2 and `comp` as competitors."""
r = run[run.method.isin(comp) | (run.method == cand)].replace({"method": {cand: "M2"}})
grid = G | {"n_train": sorted(r.n_train.unique().tolist()), "drift_factors": sorted(r.c.unique().tolist())}
Pg = {"grid": grid, "gates": {"G-B": {"competitors": comp}}}
return sp13.gate_gb(r, Pg, n_boot, rng)
def h2a(runs: dict, rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
sets = {"point_ties": POINT_TIES, "with_B3d": POINT_TIES + ["B3d"]}
rows, verdicts = [], {}
for reg in H2A_REGIMES:
if reg not in runs:
continue
for cand in ("B3d-Sa", "M2-Sa"):
for sname, comp in sets.items():
run = runs[reg]
if not set(comp + [cand]) <= set(run.method):
continue
cells, gv = h2a_cells(run, cand, comp, rng, n_boot)
c1 = cells[cells.c == G["realistic_drift"]]
ok_n = sorted(int(n) for n in c1.n_train[c1.cell_pass])
passed = bool(len(c1) == len(G["n_train"]) and c1.cell_pass.all() and gv["zero_drift_guard"])
verdicts[f"{reg}/{cand}/{sname}"] = {
"c1_cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}", "c1_pass_n": ok_n,
"zero_drift_macro_ratio": gv["zero_drift_macro_ratio"], "zero_drift_ratio_per_N": gv["zero_drift_ratio_per_N"],
"zero_drift_guard": gv["zero_drift_guard"], "regime_pass": passed,
"complete": bool((cells.n_rid == len(G["realizations"])).all() and (cells.n_seed == len(G["seeds"])).all()
and len(cells) == len(G["drift_factors"]) * len(G["n_train"]))}
rows.append(cells.assign(regime=reg, candidate=cand, competitors=sname,
flag=np.where(cells.c == 2, "unstable posterior", "")))
tab = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
key = "R10/B3d-Sa/point_ties"
verdict = {"pass": verdicts[key]["regime_pass"] if key in verdicts else None,
"regimes_pass": [r for r in H2A_REGIMES if verdicts.get(f"{r}/B3d-Sa/point_ties", {}).get("regime_pass")],
"per_regime": verdicts}
return tab, verdict
def sigma_a_arm(runs: dict, rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
arm = G["sigma_a_arm"]
rows, verdicts = [], {}
for sa in arm["sigma_a_reg_ms"]:
name = f"{arm['regime']}_sa{sa:g}"
if name not in runs:
continue
cells, _ = h2a_cells(runs[name], "B3d-Sa", POINT_TIES, rng, n_boot)
c1 = cells[cells.c.isin(arm["drift_factors"])]
verdicts[f"sa{sa:g}"] = {"cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}",
"pass": bool(len(c1) == len(arm["n_train"]) and c1.cell_pass.all())}
rows.append(c1.assign(sigma_a_reg_ms=sa))
return (pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()), verdicts
# ---------------------------------------------------------------- H2b
def pair_cell(g: pd.DataFrame, a: str, b: str, rng, n_boot: int) -> dict:
"""Ratio mean(a)/mean(b) of band RMSE in one cell, its bootstrap CI over realizations, and the direction rule
(a < b in ≥ 4/5 seeds and > 1/2 of realizations)."""
x = g[g.method == a].set_index(["rid", "seed"])["band_rmse"]
y = g[g.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index)
d = x - y
ds, dr = d.groupby("seed").mean(), d.groupby("rid").mean()
xr, yr = x.groupby("rid").mean(), y.groupby("rid").mean()
lo, hi = sp13.boot(xr.to_numpy(), yr.to_numpy(), n_boot, rng)
return {"ratio": 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),
"cell_pass": bool((ds < 0).sum() >= math.ceil(sp13.SEED_FRAC * len(ds) - 1e-9) and (dr < 0).sum() > len(dr) / 2)}
def h2b(runs: dict, sp: pd.DataFrame, bl: pd.DataFrame | None, rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
from scipy.stats import spearmanr
rows = []
for reg in G["regimes"]:
if reg not in runs or not {"M2-Sa", "B3d-Sa"} <= set(runs[reg].method):
continue
for (c, N), g in runs[reg].groupby(["c", "n_train"]):
rows.append({"regime": reg, "c": c, "n_train": N} | pair_cell(g, "M2-Sa", "B3d-Sa", rng, n_boot))
t = pd.DataFrame(rows)
if t.empty:
return t, {}
t = t.merge(sp.rename(columns={"setting": "regime"})[["regime", "c", "n_train", "sigma_post_ms"]],
on=["regime", "c", "n_train"], how="left")
t["wide"] = t.sigma_post_ms >= WIDE_MS
if bl is not None and len(bl):
def bound(r):
b = bl[(bl.source == r.regime) & (bl.n_train == r.n_train)]
return 1.0 / np.interp(r.sigma_post_ms, b.sigma_ms, b["mean"]) if len(b) else np.nan
t["bound_1/B"] = t.apply(bound, axis=1)
out = {}
for N, g in t.groupby("n_train"):
g = g.dropna(subset=["sigma_post_ms"])
wide, narrow = g[g.wide], g[~g.wide]
rho = spearmanr(g.sigma_post_ms, g.ratio).statistic if len(g) > 2 else np.nan
perm = np.array([spearmanr(g.sigma_post_ms, rng.permutation(g.ratio.to_numpy())).statistic
for _ in range(N_PERM)]) if len(g) > 2 else np.array([np.nan])
a = bool(len(wide) > 0 and wide.cell_pass.sum() >= math.ceil(WIDE_FRAC * len(wide) - 1e-9))
b = bool(rho < 0)
c = bool(len(narrow) == 0 or narrow.ratio.mean() <= NARROW_GUARD)
out[f"n{N}"] = {"role": "primary" if N == P["hypotheses"]["H2b"]["primary_n"] else "reported only",
"cells": len(g), "wide_cells": len(wide), "wide_cells_pass": int(wide.cell_pass.sum()),
"a_wide_gain": a, "spearman_rho": rho, "perm_p_one_sided": float(np.mean(perm <= rho)),
"b_dose": b, "narrow_cells": len(narrow),
"narrow_ratio_mean": narrow.ratio.mean() if len(narrow) else None, "c_narrow_guard": c,
"pass": a and b and c}
out["pass"] = out.get(f"n{P['hypotheses']['H2b']['primary_n']}", {}).get("pass")
return t, out
def blur(root: Path) -> pd.DataFrame | None:
"""B(σ) per regime and N from the Oracle predictions of the main run (scripts/17 blur(), same σ grid)."""
from ml_porosity.eval.metrics import band_metrics
f_c = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text())["metrics"]["bands"]["f_c_hz"]
rows = []
for reg in G["regimes"]:
cells = root / "train" / reg / "cells"
for f in sorted(cells.glob("r*_c*_n*.npz")) if cells.exists() else []:
rid, c, N = sp13.parse_tag(f.stem)
z = np.load(f)
Y = z["y_true"].astype(float)
for k in (k for k in z.files if k.startswith("Oracle/") and k.endswith("/mu")):
P0 = z[k].astype(float)
b0 = np.mean([band_metrics(Y[i], P0[i], f_c)["band_rmse"] for i in range(len(Y))])
for s in sp17.BLUR_SIGMAS:
Pb = sp17.blur(P0, s)
rows.append({"source": reg, "rid": rid, "c": c, "n_train": N, "sigma_ms": s,
"ratio": np.mean([band_metrics(Y[i], Pb[i], f_c)["band_rmse"] for i in range(len(Y))]) / b0})
if not rows:
return None
return pd.DataFrame(rows).groupby(["source", "n_train", "sigma_ms"])["ratio"].agg(["mean", "min", "max", "size"]).reset_index()
# ---------------------------------------------------------------- H3 (descriptive)
def h3(root: Path, rng, n_boot: int) -> pd.DataFrame:
rows = []
for reg in G["regimes"]:
f = root / "train" / reg / "h3.csv"
if not f.exists():
continue
e = pd.read_csv(f)
e = e[e.c == G["realistic_drift"]]
for (N, m), g in e.groupby(["n_train", "method"]):
per = g.groupby("rid")["ce"].mean().to_numpy()
rows.append({"regime": reg, "n_train": N, "method": m, "members": int(g.members.min()), "n_rid": len(per),
**g[["ce", "coverage_50", "coverage_80", "coverage_90", "coverage_95", "nll", "crps", "mean_sigma"]].mean().to_dict(),
**dict(zip(("ce_lo", "ce_hi"), sp13.boot(per, None, n_boot, rng)))})
return pd.DataFrame(rows)
# ---------------------------------------------------------------- report
def md(df: pd.DataFrame, fmt: str = ".3f") -> str:
return df.to_markdown(index=False, floatfmt=fmt) if len(df) else "(no data)"
def write_md(path: Path, v: dict, h2a_tab, sa_tab, h2b_tab, h3_tab, sp, band) -> None:
L = ["# protocol_p2r: main grid (realizations 8–15)", "",
"Locked rules of configs/protocol_p2r.yaml applied as written; nothing here was selected on these results.", ""]
hv = v["H2a"]
L += ["## H2a — posterior-mean labels (B3d-Sa) vs the best point tie {B3b, B3c, B3c-R}", "",
f"**H2a (R10): {'PASS' if hv['pass'] else 'FAIL' if hv['pass'] is not None else 'not available'}**; "
f"regimes that pass: {', '.join(hv['regimes_pass']) or 'none'}", ""]
if len(h2a_tab):
per = pd.DataFrame(hv["per_regime"]).T.reset_index(names="regime/candidate/competitors")
L += [md(per[["regime/candidate/competitors", "c1_cells_pass", "zero_drift_macro_ratio", "zero_drift_guard",
"regime_pass", "complete"]]), ""]
cols = ["regime", "candidate", "competitors", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc",
"seeds_improve", "rids_improve", "cell_pass", "flag"]
L += ["Cells (ratio = band RMSE candidate / best competitor; CI over realizations; c = 2 not primary evidence):", "",
md(h2a_tab[cols]), ""]
L += ["## σ_a arm (R10, c = 1; every method registered with the misspecified σ_a)", "",
json.dumps(v["sigma_a_arm"]), ""]
if len(sa_tab):
L += [md(sa_tab[["sigma_a_reg_ms", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve",
"rids_improve", "cell_pass"]]), ""]
L += ["## H2b — RML on the posterior bank (M2-Sa) vs posterior-mean labels (B3d-Sa)", ""]
for k, x in v["H2b"].items():
if isinstance(x, dict):
L += [f"- N = {k[1:]} ({x['role']}): a {x['a_wide_gain']} ({x['wide_cells_pass']}/{x['wide_cells']} wide cells pass), "
f"b {x['b_dose']} (ρ = {x['spearman_rho']:.3f}, one-sided permutation p = {x['perm_p_one_sided']:.3f}), "
f"c {x['c_narrow_guard']} (narrow mean ratio "
f"{'n/a' if x['narrow_ratio_mean'] is None else format(x['narrow_ratio_mean'], '.3f')}) → {'PASS' if x['pass'] else 'FAIL'}"]
L += ["", f"**H2b: {v['H2b'].get('pass')}**", ""]
if len(h2b_tab):
cols = [c for c in ["regime", "c", "n_train", "sigma_post_ms", "wide", "ratio", "ratio_lo", "ratio_hi", "bound_1/B",
"seeds_better", "rids_better", "cell_pass"] if c in h2b_tab.columns]
L += ["Mechanism: a gain is attributed to deblurring only if the ratio lies within the bound 1/B(σ_post).", "",
md(h2b_tab[cols].sort_values(["n_train", "sigma_post_ms"])), ""]
L += ["## σ_post and warp error of the SMC posterior (train wells; warp error and coverage use the true warp, descriptive)", "",
md(sp), "", "## Band RMSE per method (mean over realization × seed)", "", md(band), "",
"## H3 (descriptive only; no calibration claim) — 5-seed ensembles at c = 1", "", md(h3_tab), ""]
path.write_text("\n".join(L))
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", type=Path, default=outputs_dir() / "p2r")
ap.add_argument("--out-dir", type=Path, default=None, help="default: <root>/summary")
ap.add_argument("--n-boot", type=int, default=2000)
args = ap.parse_args()
out = args.out_dir or args.root / "summary"
out.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(0)
runs = load_runs(args.root)
sp = sigma_post(args.root)
sp.to_csv(out / "sigma_post.csv", index=False)
h2a_tab, h2a_v = h2a(runs, rng, args.n_boot)
h2a_tab.to_csv(out / "h2a.csv", index=False)
sa_tab, sa_v = sigma_a_arm(runs, rng, args.n_boot)
sa_tab.to_csv(out / "sigma_a.csv", index=False)
bl = blur(args.root)
if bl is not None:
bl.to_csv(out / "blur.csv", index=False)
h2b_tab, h2b_v = h2b(runs, sp, bl, rng, args.n_boot)
h2b_tab.to_csv(out / "h2b.csv", index=False)
h3_tab = h3(args.root, rng, args.n_boot)
h3_tab.to_csv(out / "h3.csv", index=False)
band = pd.concat([r.groupby(["c", "n_train", "method"])["band_rmse"].mean().unstack("method").reset_index().assign(setting=k)
for k, r in runs.items()], ignore_index=True) if runs else pd.DataFrame()
if len(band):
band = band[["setting"] + [c for c in band.columns if c != "setting"]]
band.to_csv(out / "band_rmse.csv", index=False)
v = {"protocol": "configs/protocol_p2r.yaml",
"protocol_sha256": (REPO_ROOT / "configs" / "protocol_p2r.sha256").read_text().split()[0],
"settings": sorted(runs), "H2a": h2a_v, "sigma_a_arm": sa_v, "H2b": h2b_v}
(out / "verdict.json").write_text(json.dumps(v, indent=1, default=float))
write_md(out / "summary.md", v, h2a_tab, sa_tab, h2b_tab, h3_tab, sp, band)
print((out / "summary.md").read_text())
if __name__ == "__main__":
main()

View File

@@ -1,10 +1,14 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Chạy toàn bộ pipeline P0: kiểm hash dữ liệu → dựng giếng → QC TD → train thử B2 → unit test. # Run the full P0 pipeline: data hash check → build wells → TD QC → B2 smoke training → unit tests.
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}" PY="${PY:-.venv/bin/python}"
"$PY" scripts/00_data_manifest.py --check # Log + runtime: the whole pipeline goes to logs/runs/<timestamp>_p0/, one subdirectory per step, one row per step in
"$PY" scripts/01_build_wells.py # logs/index.csv (ml_porosity/runlog.py).
"$PY" scripts/02_td_qc.py [[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p0 -- bash "scripts/$(basename "$0")" "$@"
"$PY" scripts/03_train.py --config configs/b2_smoke.yaml step() { "$PY" -m ml_porosity.runlog -- "$@"; }
"$PY" -m pytest -q step "$PY" scripts/00_data_manifest.py --check
step "$PY" scripts/01_build_wells.py
step "$PY" scripts/02_td_qc.py
step "$PY" scripts/03_train.py --config configs/b2_smoke.yaml
step "$PY" -m pytest -q

View File

@@ -1,10 +1,14 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Chạy P1: dựng giếng → wavelet/tie QC → LOWO (cần protocol.yaml khớp hash) → tổng hợp. # Run P1: build wells → wavelet/tie QC → LOWO (requires protocol.yaml to match its hash) → summary.
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}" PY="${PY:-.venv/bin/python}"
"$PY" scripts/01_build_wells.py # Log + runtime: the whole pipeline goes to logs/runs/<timestamp>_p1/, one subdirectory per step, one row per step in
"$PY" scripts/04_wavelet_tie.py # logs/index.csv (ml_porosity/runlog.py).
"$PY" scripts/05_lowo.py --only B0a,B0b,B1 [[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p1 -- bash "scripts/$(basename "$0")" "$@"
"$PY" scripts/05_lowo.py --only B2,B3a,B3b --workers "${WORKERS:-12}" step() { "$PY" -m ml_porosity.runlog -- "$@"; }
"$PY" scripts/06_summarize_p1.py step "$PY" scripts/01_build_wells.py
step "$PY" scripts/04_wavelet_tie.py
step "$PY" scripts/05_lowo.py --only B0a,B0b,B1
step "$PY" scripts/05_lowo.py --only B2,B3a,B3b --workers "${WORKERS:-12}"
step "$PY" scripts/06_summarize_p1.py

26
scripts/run_p2.sh Executable file
View File

@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Run P2: fit F3 warp prior → D2 QC → unit tests → dev round (budget selection) → [lock protocol_p2] → main grid
# → H1 → summary. GPU jobs run on cuda:1 (shared machine; override with DEVICE=...).
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
# Log + runtime: the whole pipeline goes to logs/runs/<timestamp>_p2/, one subdirectory per step, one row per step in
# logs/index.csv (ml_porosity/runlog.py). Re-running after an interruption: 11_run_d2 skips cells that already have a CSV.
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p2 -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m ml_porosity.runlog -- "$@"; }
DEVICE="${DEVICE:-cuda:1}"
WORKERS="${WORKERS:-6}"
# warp_prior_f3.json is an input whose hash is recorded in protocol_p2: do not regenerate if present (changing it ⇒ new protocol lock)
[[ -f outputs/p2/warp_prior_f3.json ]] || step "$PY" scripts/09_fit_warp_prior_f3.py
step "$PY" scripts/10_build_d2.py
step "$PY" -m pytest -q tests/test_losses.py tests/test_registration.py tests/test_d2.py
if ! sha256sum --status -c configs/protocol_p2.sha256 2>/dev/null; then
step "$PY" scripts/11_run_d2.py --dev --workers "$WORKERS" --device "$DEVICE"
step "$PY" scripts/13_summarize_p2.py --mode dev
echo "Dev round finished. Copy training.budgets from outputs/p2/dev/budgets.json into configs/protocol_p2.yaml, lock it with" >&2
echo " sha256sum configs/protocol_p2.yaml > configs/protocol_p2.sha256 (and a git tag), then re-run this script." >&2
exit 1
fi
step "$PY" scripts/11_run_d2.py --main --workers "$WORKERS" --device "$DEVICE"
step "$PY" scripts/12_h1_blur.py --workers "$WORKERS" --device "$DEVICE"
step "$PY" scripts/13_summarize_p2.py --mode main

83
scripts/run_p2r_dev.sh Normal file
View File

@@ -0,0 +1,83 @@
#!/usr/bin/env bash
# Dev experiments in preparation for protocol_p2r (plan §10): dev realizations 900/901 only; main grid 0–7 is not used.
# scripts/run_p2r_dev.sh # all stages in order
# scripts/run_p2r_dev.sh stability sigma_a # only the named stages
# screen SMC posterior over SNR {10, 5, 0, −5} dB × anchor density {full, half, topbottom} × c {1, 2} × N {4, 16}
# train training (scripts/15) in the screen cells with σ_post ≥ 1.5 ms (outputs/p2/diag/p2rdev/wide_cells.txt,
# written by scripts/17): M2-Sa, B3d-Sa, B3c-R, Oracle… 5 seeds, fixed budgets
# stability 4 independent SMC runs with P = 256 and 2 with P = 1024 (SNR 10, full): warp difference between runs
# stability_m5 as stability at SNR −5 dB, full (the F3-like regime): 2 runs with P = 1024 (the chosen setting)
# b3d_old supplementary: old protocol_p2 B3d (point-tie competitor for H2a) at SNR 10/0/−5, full, same seeds and budgets
# sigma_a registration with σ_a = 3.5 and 14 ms when the data are generated with σ_a = 7 ms (plan §5.5)
# train_sa training on the sigma_a posteriors (c 1 2; every method registered with the misspecified σ_a): does H2a hold?
# f3 SMC posterior on the 4 F3 wells (descriptive only, scripts/16)
# h3 H3 with the SMC posterior: 5-seed ensembles of M2-Sa, B3d-Sa… vs B5 in the protocol_p2 setting (c 1, 2)
# GPU jobs run on cuda:1 (override with DEVICE=...). Re-running after an interruption: scripts 14, 15 skip jobs that already have a CSV.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p2rdev -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m ml_porosity.runlog "$@" || echo "step failed: $*" >&2; }
DEVICE="${DEVICE:-cuda:1}"
WORKERS="${WORKERS:-6}"
# The machine environment presets OMP_NUM_THREADS=40 (also MKL, OpenBLAS): unless overridden, each worker opens a 40-thread pool.
THREADS="${THREADS:-2}"
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
NUMBA_NUM_THREADS=$THREADS
OUT=outputs/p2/diag
POST=(scripts/14_diag_posterior.py --rids 900 901 --c 1 2 --n 4 16 --seeds 0 --device "$DEVICE")
TRAIN=(scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --device "$DEVICE" --variants a 1
--methods Oracle B3b B3c M2 B3c-R B3d-Sa M2-Sa B3d-S1 M2-S1 --budgets-from "$OUT/train/budgets.json" --save-preds)
for stage in ${@:-screen train stability sigma_a f3 h3}; do
case "$stage" in
screen)
for snr in 10 5 0 -5; do
for dens in full half topbottom; do
step -n "stress_snr${snr}_${dens}" -- "$PY" "${POST[@]}" --snr "$snr" --anchor-density "$dens" \
--wavelets estR true --workers "$WORKERS" --out-dir "$OUT/stress/snr${snr}_${dens}"
done
done ;;
train)
CUDA_VISIBLE_DEVICES= "$PY" scripts/17_summarize_p2r_dev.py --only screen > /dev/null
while read -r snr dens cs <&3; do
# shellcheck disable=SC2086 # cs is a list of c values and must be word-split
step -n "train_snr${snr}_${dens}" -- "$PY" "${TRAIN[@]}" --snr "$snr" --anchor-density "$dens" --c $cs \
--workers 4 --post-dir "$OUT/stress/snr${snr}_${dens}" --out-dir "$OUT/train_stress/snr${snr}_${dens}"
done 3< "$OUT/p2rdev/wide_cells.txt" ;;
stability)
step -n stab_p256 -- "$PY" "${POST[@]}" --smc-seeds 0 1 2 3 --wavelets estR --workers "$WORKERS" \
--out-dir "$OUT/stability/p256"
step -n stab_p1024 -- "$PY" "${POST[@]}" --particles 1024 --smc-seeds 0 1 --wavelets estR --workers 4 \
--gpu-mem-gb 6 --out-dir "$OUT/stability/p1024" ;;
stability_m5)
step -n stab_p1024_snr-5 -- "$PY" "${POST[@]}" --snr -5 --anchor-density full --particles 1024 --smc-seeds 0 1 \
--wavelets estR --workers 4 --gpu-mem-gb 6 --out-dir "$OUT/stability/p1024_snr-5" ;;
b3d_old)
B3D=(scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 --device "$DEVICE" --variants a
--methods B3d --budgets-from "$OUT/train/budgets.json" --workers 4)
step -n b3d_snr10_full -- "$PY" "${B3D[@]}" --post-dir "$OUT/posterior_gpu" --out-dir "$OUT/train_b3d/snr10_full"
for snr in 0 -5; do
step -n "b3d_snr${snr}_full" -- "$PY" "${B3D[@]}" --snr "$snr" --anchor-density full \
--post-dir "$OUT/stress/snr${snr}_full" --out-dir "$OUT/train_b3d/snr${snr}_full"
done ;;
sigma_a)
for sa in 3.5 14; do
step -n "stress_sa${sa}" -- "$PY" "${POST[@]}" --sigma-a-reg "$sa" --wavelets estR true --workers "$WORKERS" \
--out-dir "$OUT/stress/snr10_full_sa${sa}"
done ;;
train_sa)
for sa in 3.5 14; do
step -n "train_sa${sa}" -- "$PY" scripts/15_diag_train.py --rids 900 901 --n 4 16 --seeds 0 1 2 3 4 --c 1 2 \
--device "$DEVICE" --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --sigma-a-reg "$sa" \
--budgets-from "$OUT/train/budgets.json" --workers 4 --post-dir "$OUT/stress/snr10_full_sa${sa}" \
--out-dir "$OUT/train_sa/sa${sa}"
done ;;
f3)
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 step -n f3_posterior -- "$PY" scripts/16_f3_posterior.py \
--device "$DEVICE" ;;
h3)
step -n h3_smc -- "$PY" "${TRAIN[@]}" --c 1 2 --workers 4 --post-dir "$OUT/posterior_gpu" --out-dir "$OUT/h3_smc" ;;
*) echo "unknown stage: $stage" >&2; exit 2 ;;
esac
done

71
scripts/run_p2r_main.sh Executable file
View File

@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Main grid of protocol_p2r (configs/protocol_p2r.yaml, locked): realizations 8–15, regimes R10 R0 Rm5 R0h R10tb.
# scripts/run_p2r_main.sh # all stages in order
# scripts/run_p2r_main.sh R10 summary # only the named stages
# WORKERS=3 scripts/run_p2r_main.sh check parallel # all regimes and the σ_a arm at once, then the summary
# check pytest tests/test_protocol.py (locked SHA-256 of protocol_p2 / protocol_p2r and their inputs)
# <regime> SMC posterior (scripts/14: P = 1024, K = 1, estR wavelet, c 0 1 2, N 4 16, registration seed 0), then
# training (scripts/15: Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa, 5 seeds, budgets of the protocol, saved
# predictions for H3 and the blur bound) → outputs/p2r/{posterior,train}/<regime>/
# sigma_a grid.sigma_a_arm: R10, c 1, N 4 16, every method registered with σ_a = 3.5 / 14 ms
# → outputs/p2r/{posterior,train}/R10_sa<σ_a>/
# summary scripts/18_summarize_p2r.py: H2a, H2b, H3 (descriptive), σ_a arm, blur bound → outputs/p2r/summary/
# GPU jobs run on cuda:1 (override with DEVICE=...). Scripts 14 and 15 refuse realizations 8–15 unless protocol_p2r and
# its inputs match the locked hashes, and skip jobs that already have a CSV, so the runner can be restarted.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
[[ -n "${RUNLOG_DIR:-}" ]] || exec "$PY" -m ml_porosity.runlog -n p2r_main -- bash "scripts/$(basename "$0")" "$@"
step() { "$PY" -m ml_porosity.runlog "$@"; }
DEVICE="${DEVICE:-cuda:1}"
WORKERS="${WORKERS:-4}"
THREADS="${THREADS:-2}"
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
NUMBA_NUM_THREADS=$THREADS
OUT=outputs/p2r
RIDS=(8 9 10 11 12 13 14 15)
BUDGETS=outputs/p2/diag/train/budgets.json # protocol_p2r inputs.budgets (hash checked by scripts 14/15)
POST=(scripts/14_diag_posterior.py --rids "${RIDS[@]}" --n 4 16 --seeds 0 --particles 1024 --wavelets estR
--device "$DEVICE" --workers "$WORKERS" --gpu-mem-gb 6)
TRAIN=(scripts/15_diag_train.py --rids "${RIDS[@]}" --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device "$DEVICE"
--workers "$WORKERS" --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from "$BUDGETS"
--save-preds)
regime() { # prints "snr_db anchor_density" of a regime from configs/d2_synth_p2r.yaml
"$PY" -c "import sys, yaml; r = yaml.safe_load(open('configs/d2_synth_p2r.yaml'))['regimes'][sys.argv[1]]; \
print(r['snr_db'], r['anchor_density'])" "$1"
}
for stage in ${@:-check R10 R0 Rm5 R0h R10tb sigma_a summary}; do
case "$stage" in
check)
CUDA_VISIBLE_DEVICES= "$PY" -m pytest -q -p no:cacheprovider tests/test_protocol.py ;;
R10|R0|Rm5|R0h|R10tb)
read -r snr dens <<< "$(regime "$stage")"
step -n "p2r_post_$stage" -- "$PY" "${POST[@]}" --c 0 1 2 --snr "$snr" --anchor-density "$dens" \
--out-dir "$OUT/posterior/$stage"
step -n "p2r_train_$stage" -- "$PY" "${TRAIN[@]}" --c 0 1 2 --snr "$snr" --anchor-density "$dens" \
--post-dir "$OUT/posterior/$stage" --out-dir "$OUT/train/$stage" ;;
sigma_a)
read -r snr dens <<< "$(regime R10)"
for sa in 3.5 14; do
step -n "p2r_post_R10_sa$sa" -- "$PY" "${POST[@]}" --c 1 --snr "$snr" --anchor-density "$dens" \
--sigma-a-reg "$sa" --out-dir "$OUT/posterior/R10_sa$sa"
step -n "p2r_train_R10_sa$sa" -- "$PY" "${TRAIN[@]}" --c 1 --snr "$snr" --anchor-density "$dens" \
--sigma-a-reg "$sa" --post-dir "$OUT/posterior/R10_sa$sa" --out-dir "$OUT/train/R10_sa$sa"
done ;;
parallel)
# Each regime and the σ_a arm run as independent pipelines at the same time (WORKERS each), then the summary.
# Results do not depend on scheduling: every job seeds its random streams from (rid, c, N, seed, well).
pids=()
for s in R10 R0 Rm5 R0h R10tb sigma_a; do
bash "scripts/$(basename "$0")" "$s" > "${RUNLOG_DIR}/pipeline_$s.out" 2>&1 & pids+=($!)
done
fail=0
for p in "${pids[@]}"; do wait "$p" || fail=1; done
[[ $fail == 0 ]] || { echo "a pipeline failed (see ${RUNLOG_DIR}/pipeline_*.out)" >&2; exit 1; }
bash "scripts/$(basename "$0")" summary ;;
summary)
CUDA_VISIBLE_DEVICES= step -n p2r_summary -- "$PY" scripts/18_summarize_p2r.py ;;
*) echo "unknown stage: $stage" >&2; exit 2 ;;
esac
done

8
scripts/runlog.sh Executable file
View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Run a command, saving log + runtime to logs/runs/<timestamp>_<name>/ and appending one row to logs/index.csv
# (details: ml_porosity/runlog.py). Examples:
# scripts/runlog.sh scripts/15_diag_train.py --rids 900 901 --device cuda:1 # .py files are run with $PY
# scripts/runlog.sh -n h1_rerun --note "re-run after fixing X" -- scripts/12_h1_blur.py --device cuda:1
# scripts/runlog.sh ls # most recent runs
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
exec "${PY:-$ROOT/.venv/bin/python}" -m ml_porosity.runlog "$@"

85
tests/test_d2.py Normal file
View File

@@ -0,0 +1,85 @@
import json
import numpy as np
import pytest
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_p2.yaml"))
INP = P["inputs"]
CFG = yaml.safe_load(open(REPO_ROOT / INP["d2_config"]["path"]))
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)")
RID = P["grid"]["dev_realizations"][0]
SIGMA_A = CFG["anchors"]["sigma_a_ms"]
@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: D2Realization(CFG, rid, hg, WarpHyper(**prior["hyper"]), wav)
@pytest.fixture(scope="module")
def R(make):
return make(RID)
def test_realization_is_deterministic(make, R):
R2 = make(RID)
for a, b in zip(R.wells, R2.wells):
assert (a.name, a.il, a.xl) == (b.name, b.il, b.xl)
for k in ("seis_clean", "noise_unit", "phi_t", "z_g", "boundaries_t", "eps_a"):
np.testing.assert_array_equal(getattr(a, k), getattr(b, k))
assert a.z_b == b.z_b
assert not np.allclose(make(RID + 1).wells[0].phi_t, R.wells[0].phi_t)
def test_wells_are_spatially_separated(R):
xy = np.array([[w.x, w.y] for w in R.wells])
d = np.hypot(*(xy[:, None] - xy[None]).transpose(2, 0, 1))
np.fill_diagonal(d, np.inf)
nt = CFG["wells"]["n_test"]
assert len(R.test) == nt and len(R.pool) == CFG["wells"]["n_train_pool"]
assert d[:nt].min() >= CFG["wells"]["min_dist_test_m"]
assert d[nt:, nt:].min() >= CFG["wells"]["min_dist_train_m"]
def test_common_random_numbers_across_drift(R):
w = R.pool[0]
obs = {c: R.observe(w, c, P["grid"]["snr_db"], SIGMA_A) for c in P["grid"]["drift_factors"]}
ref = obs[1.0]
for c, o in obs.items():
for k in ("seis", "y_true", "t_k"):
np.testing.assert_array_equal(o[k], ref[k])
np.testing.assert_allclose(o["g"], c * ref["g"], atol=1e-12)
assert o["b"] == pytest.approx(c * ref["b"])
np.testing.assert_allclose(obs[0.0]["t_of_tau_true"], R.tau_fine, atol=1e-9)
np.testing.assert_allclose(obs[0.0]["tau_k"], w.boundaries_t, atol=1e-9)
def test_anchors_and_density_subsets(R):
for w in R.wells:
bt = w.boundaries_t
assert np.all(np.diff(bt) > 0) and R.t_ext[0] <= bt[0] and bt[-1] <= R.t_ext[-1]
assert len(w.eps_a) == len(bt) and 10 <= len(bt) <= 20 # F3: 14–17 markers per well
w = R.pool[0]
n = len(w.boundaries_t)
sizes = {d: len(R.observe(w, 1.0, None, SIGMA_A, d)["tau_k"]) for d in ("full", "half", "topbottom", "none")}
assert sizes == {"full": n, "half": (n + 1) // 2, "topbottom": 2, "none": 0}
def test_max_drift_stays_in_domain(R):
c = max(P["grid"]["drift_factors"])
for w in R.wells:
o = R.observe(w, c, None, SIGMA_A)
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
assert R.tau_fine[0] <= o["tau_k"].min() and o["tau_k"].max() <= R.tau_fine[-1]
assert np.isfinite(R.true_tau_at(o, R.t_ext)).all()

View File

@@ -5,7 +5,7 @@ from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.paths import f3_root from ml_porosity.paths import f3_root
SURVEY = f3_root() / ".survey" SURVEY = f3_root() / ".survey"
pytestmark = pytest.mark.skipif(not SURVEY.exists(), reason="thiếu F3 .survey") pytestmark = pytest.mark.skipif(not SURVEY.exists(), reason="missing F3 .survey")
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
@@ -45,7 +45,7 @@ def test_round_trip_vectorised(geom):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"name,xy,expected", "name,xy,expected",
[ # bảng IL/XL thật ở plan mục 1.2a [ # true IL/XL table in plan §1.2a
("F02-1", (606554, 6080126), (362, 336)), ("F02-1", (606554, 6080126), (362, 336)),
("F03-2", (619101, 6089491), (722, 848)), ("F03-2", (619101, 6089491), (722, 848)),
("F03-4", (623256, 6082586), (442, 1007)), ("F03-4", (623256, 6082586), (442, 1007)),
@@ -59,7 +59,7 @@ def test_well_bins_match_plan(geom, name, xy, expected):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"legacy,xy,km", "legacy,xy,km",
[ # vị trí luận văn dùng và độ lệch ở plan mục 1.2a [ # locations used in the thesis and their offsets, plan §1.2a
((418, 608), (606554, 6080126), 6.94), ((418, 608), (606554, 6080126), 6.94),
((362, 821), (623256, 6082586), 5.05), ((362, 821), (623256, 6082586), 5.05),
((283, 842), (607903, 6077213), 11.42), ((283, 842), (607903, 6077213), 11.42),

143
tests/test_losses.py Normal file
View File

@@ -0,0 +1,143 @@
import math
import numpy as np
import pytest
import torch
from scipy import signal
from ml_porosity.losses.rml import bank_loss, effective_lambda, gather_windows, shift_bank, window_loglik
from ml_porosity.losses.softdtw import dilate_loss, dilate_loss_fast, nll_cost, softdtw_loss, softdtw_loss_fast
WIN = 16
F64 = torch.float64
def bank_data(B=3, L=40, S=5, seed=0):
g = torch.Generator().manual_seed(seed)
mu = torch.randn(B, L, generator=g, dtype=F64)
sigma = 0.5 + torch.rand(B, L, generator=g, dtype=F64)
Y = mu[:, None, :] + torch.randn(B, S, L, generator=g, dtype=F64)
starts = torch.tensor([[0, 6, 24]] * B)
return mu, sigma, Y, starts
def random_logpi(B, S, seed=1):
return torch.log_softmax(torch.randn(B, S, generator=torch.Generator().manual_seed(seed), dtype=F64), -1)
def gauss_nll(mu, sigma, y, starts):
m, s, v = (gather_windows(a, starts, WIN) for a in (mu, sigma, y))
return (torch.log(s) + 0.5 * ((v - m) / s) ** 2 + 0.5 * math.log(2 * math.pi)).mean()
def test_gather_windows_matches_slices():
_, _, Y, starts = bank_data()
w = gather_windows(Y, starts, WIN)
assert w.shape == (3, 3, 5, WIN)
torch.testing.assert_close(w[1, 2], Y[1, :, 24: 24 + WIN])
@pytest.mark.parametrize("lam", [None, 1e-3, 1.0, 50.0])
def test_single_or_identical_members_give_gaussian_nll(lam):
mu, sigma, Y, starts = bank_data()
ref = gauss_nll(mu, sigma, Y[:, 0], starts)
one = bank_loss(mu, sigma, Y[:, :1], torch.zeros(3, 1, dtype=F64), starts, WIN, lam)
same = bank_loss(mu, sigma, Y[:, :1].expand(3, 4, -1), torch.full((3, 4), -math.log(4), dtype=F64),
starts, WIN, lam)
torch.testing.assert_close(one, ref)
torch.testing.assert_close(same, ref)
def test_rml_between_hard_min_and_mixture_mean():
# uniform π: −max ℓ/n ≤ RML_λ ≤ hard-min + log S/(λn), non-increasing in λ; λ → 0 gives −mean ℓ/n
mu, sigma, Y, starts = bank_data()
S = Y.shape[1]
logpi = torch.full((3, S), -math.log(S), dtype=F64)
hard = bank_loss(mu, sigma, Y, logpi, starts, WIN, None)
mean = -(window_loglik(mu, sigma, Y, starts, WIN).mean(-1) / WIN).mean()
lams = [1e-8, 0.01, 0.1, 1.0, 10.0, 1e4]
v = [bank_loss(mu, sigma, Y, logpi, starts, WIN, lam) for lam in lams]
assert all(a >= b - 1e-12 for a, b in zip(v, v[1:]))
for lam, x in zip(lams, v):
assert hard - 1e-12 <= x <= hard + math.log(S) / (lam * WIN) + 1e-12
torch.testing.assert_close(v[0], mean, rtol=0, atol=1e-6)
def test_rml_small_lambda_is_pi_weighted_nll():
mu, sigma, Y, starts = bank_data()
logpi = random_logpi(3, Y.shape[1])
ll = window_loglik(mu, sigma, Y, starts, WIN)
ref = -((ll * logpi.exp()[:, None, :]).sum(-1) / WIN).mean()
torch.testing.assert_close(bank_loss(mu, sigma, Y, logpi, starts, WIN, 1e-7), ref, rtol=0, atol=1e-6)
@pytest.mark.parametrize("lam", [0.05, 1.0])
def test_rml_gradient_is_responsibility_weighted(lam):
# ∇ RML = −(1/n) Σ_s r_s ∇ℓ_s with r = softmax(log π + λℓ)
mu, sigma, Y, starts = bank_data()
logpi = random_logpi(3, Y.shape[1])
mu.requires_grad_(True)
sigma.requires_grad_(True)
g = torch.autograd.grad(bank_loss(mu, sigma, Y, logpi, starts, WIN, lam), (mu, sigma))
ll = window_loglik(mu, sigma, Y, starts, WIN)
r = torch.softmax(logpi[:, None, :] + lam * ll, -1).detach()
g_ref = torch.autograd.grad(-((r * ll).sum(-1) / WIN).mean(), (mu, sigma))
for a, b in zip(g, g_ref):
torch.testing.assert_close(a, b)
def test_shift_bank_rows_are_label_shifts():
y = np.arange(10.0)
bank = shift_bank(y, 2)
assert bank.shape == (5, 10)
np.testing.assert_array_equal(bank[2], y)
np.testing.assert_array_equal(bank[3, :9], y[1:]) # k = +1: y_{i+1}
np.testing.assert_array_equal(bank[0, 2:], y[:8]) # k = −2: y_{i−2}
assert np.isnan(bank[3, 9]) and np.isnan(bank[0, :2]).all()
def dtw_data(B=3, n=12, seed=0):
g = torch.Generator().manual_seed(seed)
mu = torch.randn(B, n, generator=g, dtype=F64)
sigma = 0.3 + torch.rand(B, n, generator=g, dtype=F64)
y = torch.roll(mu, 1, -1) + 0.3 * torch.randn(B, n, generator=g, dtype=F64)
return mu, sigma, y
@pytest.mark.parametrize("fast", [False, True])
def test_band0_reduces_to_nll(fast):
# band 0 leaves only the diagonal: soft-DTW/(2n) = mean NLL, TDI = 0
mu, sigma, y = dtw_data()
nll = torch.diagonal(nll_cost(mu, sigma, y), dim1=1, dim2=2).mean()
sd, dl = (softdtw_loss_fast, dilate_loss_fast) if fast else (softdtw_loss, dilate_loss)
torch.testing.assert_close(sd(mu, sigma, y, gamma=0.1, band=0), nll)
torch.testing.assert_close(dl(mu, sigma, y, alpha=0.3, gamma=0.1, band=0), 0.3 * nll)
@pytest.mark.parametrize("kind", ["softdtw", "dilate"])
@pytest.mark.parametrize("band", [4, None])
@pytest.mark.parametrize("gamma", [0.1, 1.0])
def test_fast_matches_autograd(kind, band, gamma):
mu, sigma, y = dtw_data(seed=2)
if kind == "softdtw":
fns = [lambda m, s: f(m, s, y, gamma=gamma, band=band) for f in (softdtw_loss, softdtw_loss_fast)]
else:
fns = [lambda m, s: f(m, s, y, alpha=0.5, gamma=gamma, band=band) for f in (dilate_loss, dilate_loss_fast)]
out = []
for fn in fns:
m, s = mu.clone().requires_grad_(True), sigma.clone().requires_grad_(True)
v = fn(m, s)
out.append((v.detach(), *torch.autograd.grad(v, (m, s))))
for a, b in zip(*out):
torch.testing.assert_close(b, a, rtol=1e-7, atol=1e-10)
def test_effective_lambda_grows_with_correlation():
rng = np.random.default_rng(0)
white = [rng.standard_normal(400) for _ in range(4)]
sos = signal.butter(4, 20, fs=250, output="sos")
smooth = [signal.sosfiltfilt(sos, w) for w in white]
lam_w, tau_w = effective_lambda(white)
lam_s, tau_s = effective_lambda(smooth)
assert tau_w < 1.3 and tau_s > 2.0
assert lam_w == pytest.approx(1 / tau_w) and lam_s == pytest.approx(1 / tau_s)

View File

@@ -10,7 +10,7 @@ def test_cnn_gru_shape():
def test_shape_loss_redundant_with_pcc(): def test_shape_loss_redundant_with_pcc():
# plan mục 1.1 #7: L_shape = 2·L_PCC − 2/L (z-score dùng std không chệch, Σx² = L − 1) # plan §1.1 #7: L_shape = 2·L_PCC − 2/L (z-score uses the unbiased std, Σx² = L − 1)
torch.manual_seed(0) torch.manual_seed(0)
p, t = torch.randn(4, 1, 126), torch.randn(4, 1, 126) p, t = torch.randn(4, 1, 126), torch.randn(4, 1, 126)
assert torch.allclose(shape_loss(p, t), 2 * pcc_loss(p, t) - 2 / 126, atol=1e-5) assert torch.allclose(shape_loss(p, t), 2 * pcc_loss(p, t) - 2 / 126, atol=1e-5)

View File

@@ -38,7 +38,7 @@ def test_strat_map_identity_and_shift():
h = np.array([600.0, 800.0, 1000.0]) h = np.array([600.0, 800.0, 1000.0])
np.testing.assert_allclose(strat_map(t, h, h), t) np.testing.assert_allclose(strat_map(t, h, h), t)
np.testing.assert_allclose(strat_map(t, h, h + 20), t + 20) np.testing.assert_allclose(strat_map(t, h, h + 20), t + 20)
# giãn tuyến tính giữa hai horizon # linear stretch between two horizons
out = strat_map(np.array([700.0]), np.array([600.0, 800.0]), np.array([600.0, 1000.0])) out = strat_map(np.array([700.0]), np.array([600.0, 800.0]), np.array([600.0, 1000.0]))
assert out[0] == pytest.approx(800.0) assert out[0] == pytest.approx(800.0)
@@ -58,4 +58,4 @@ def test_gaussian_metrics_calibrated():
y = rng.standard_normal(20000) y = rng.standard_normal(20000)
g = gaussian_metrics(y, np.zeros_like(y), np.ones_like(y)) g = gaussian_metrics(y, np.zeros_like(y), np.ones_like(y))
assert g["coverage_90"] == pytest.approx(0.90, abs=0.01) assert g["coverage_90"] == pytest.approx(0.90, abs=0.01)
assert g["crps"] == pytest.approx(1 / np.sqrt(np.pi), abs=0.01) # E[CRPS] khi dự báo đúng N(0, 1) assert g["crps"] == pytest.approx(1 / np.sqrt(np.pi), abs=0.01) # E[CRPS] for a correct N(0, 1) forecast

59
tests/test_protocol.py Normal file
View File

@@ -0,0 +1,59 @@
import yaml
from ml_porosity.paths import REPO_ROOT
CONFIGS = REPO_ROOT / "configs"
def test_d2_p2r_generator_matches_p2():
"""protocol_p2r uses the protocol_p2 D2 generator: only the regimes block may be added."""
p2 = yaml.safe_load((CONFIGS / "d2_synth.yaml").read_text())
p2r = yaml.safe_load((CONFIGS / "d2_synth_p2r.yaml").read_text())
regimes = p2r.pop("regimes")
assert p2r == p2
assert all(set(r) == {"snr_db", "anchor_density"} for r in regimes.values())
def test_p2r_regimes_and_realizations():
P = yaml.safe_load((CONFIGS / "protocol_p2r.yaml").read_text())
regimes = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())["regimes"]
assert set(P["grid"]["regimes"]) <= set(regimes)
p2 = yaml.safe_load((CONFIGS / "protocol_p2.yaml").read_text())["grid"]
used = set(p2["realizations"]) | set(p2["dev_realizations"])
assert not used & set(P["grid"]["realizations"])
def test_locked_protocols_match_sha256():
"""Locked protocols must not change after locking (a change needs a new version)."""
import hashlib
for name in ["protocol_p2", "protocol_p2r"]:
sha, path = (CONFIGS / f"{name}.sha256").read_text().split()
assert hashlib.sha256((REPO_ROOT / path).read_bytes()).hexdigest() == sha
def test_p2r_inputs_match_sha256():
import hashlib
P = yaml.safe_load((CONFIGS / "protocol_p2r.yaml").read_text())
for key in ["d2_config", "budgets", "warp_prior", "wavelet"]:
f = REPO_ROOT / P["inputs"][key]["path"]
if not f.exists(): # outputs/ is not versioned
continue
assert hashlib.sha256(f.read_bytes()).hexdigest() == P["inputs"][key]["sha256"], key
def test_check_rids_guards_main_grids():
"""Scripts 14/15 refuse protocol_p2 main-grid realizations and never mix the protocol_p2r main grid with dev."""
import importlib.util
import pytest
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)
P = yaml.safe_load((CONFIGS / "protocol_p2.yaml").read_text())
assert run_d2.check_rids([900, 901], P) is None
for rids in ([0], [8, 900]):
with pytest.raises(SystemExit):
run_d2.check_rids(rids, P)

262
tests/test_registration.py Normal file
View File

@@ -0,0 +1,262 @@
import numpy as np
import pytest
from ml_porosity.data.wavelet import convolve_same, ricker, rotate_phase
from ml_porosity.registration.labels import invert_warps, labels_for_warps
from ml_porosity.registration.sampler import ess, sample_warps, temper
from ml_porosity.registration.smc import (TiePosterior, ess_moves, next_gamma, phase_basis, phase_wavelet,
residual_kappa, smc_fit_phase, smc_tie_posterior)
from ml_porosity.registration.tie_likelihood import (fine_wavelet, fit_phase, phase_loglik, profile_loglik,
synth_for_warps)
from ml_porosity.registration.ties import clean_monotone, tie_b3a, tie_b3b, warp_errors
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, kernel_matrix
PHASES = np.arange(-180, 180, 15)
def test_invert_warps_linear_map():
tau = np.arange(400.0, 1300.1, 4.0)
t_out = np.array([350.0, 600.0, 1000.0, 1500.0])
T = invert_warps(np.stack([1.1 * tau + 5, tau - 20]), tau, t_out)
np.testing.assert_allclose(T[0, 1:3], (t_out[1:3] - 5) / 1.1)
np.testing.assert_allclose(T[1, 1:3], t_out[1:3] + 20)
assert np.isnan(T[:, [0, 3]]).all()
def test_labels_for_shifted_warps():
tau = np.arange(400.0, 1300.1, 0.5)
t_out = np.arange(600.0, 1100.1, 4.0)
lab = labels_for_warps(tau, np.sin(tau / 30.0), np.stack([tau, tau + 8.0]), t_out)
np.testing.assert_allclose(lab[0], np.sin(t_out / 30.0), atol=1e-12)
np.testing.assert_allclose(lab[1], np.sin((t_out - 8.0) / 30.0), atol=1e-12)
def test_sample_warps_honour_tight_anchors():
grid = WarpGrid(400.0, 1300.0, 4.0)
h = WarpHyper(m_g=0.0, sigma_g=0.1, ell_ms=70.0, sigma_b_ms=20.0, sigma_a_ms=0.5)
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
g = np.linalg.cholesky(K + 1e-8 * np.eye(grid.n)) @ np.random.default_rng(3).standard_normal(grid.n)
b = 15.0
tau_k = np.array([450.0, 610.0, 800.0, 950.0, 1200.0])
t_k = grid.t_of_tau(b, g, tau_k)[0]
out = sample_warps(grid, h, tau_k, t_k, n_samples=32, g_max=1.0, rng=np.random.default_rng(0))
T = grid.t_of_tau(out["b"], out["g"], tau_k)
assert np.sqrt(np.mean((T - t_k) ** 2)) < 2 * h.sigma_a_ms # posterior ≈ σ_a; prior ≥ σ_b = 20 ms
mid = np.array([530.0, 875.0, 1075.0])
err = np.abs(grid.t_of_tau(out["b"], out["g"], mid).mean(0) - grid.t_of_tau(b, g, mid)[0])
assert err.max() < 0.5 * h.sigma_b_ms
def test_temper_equal_loglik_keeps_gamma_one():
lw, g, e = temper(np.full(64, -3.0))
assert g == 1.0 and e == pytest.approx(64)
np.testing.assert_allclose(lw, -np.log(64))
def test_temper_largest_gamma_with_target_ess():
ll = 50 * np.random.default_rng(0).standard_normal(64)
lw, g, e = temper(ll, min_frac=0.25, tol=1e-3)
assert 0.0 < g < 1.0 and e >= 16 - 1e-9
assert ess((g + 1e-3) * ll) < 16
np.testing.assert_allclose(lw, g * ll - np.logaddexp.reduce(g * ll))
def test_clean_monotone_and_point_ties():
tau_k = np.array([800.0, 500.0, 600.0, 700.0, 1000.0])
t_k = np.array([820.0, 510.0, 620.0, 615.0, 1030.0])
tk, ttk = clean_monotone(tau_k, t_k)
assert len(tk) == 4 and np.all(np.diff(tk) > 0) and np.all(np.diff(ttk) > 0)
tau = np.arange(400.0, 1300.1, 0.5)
np.testing.assert_allclose(tie_b3a(tau_k, t_k, tau), tau + 10.0)
t = tie_b3b(tau_k, t_k, tau)
assert np.all(np.diff(t) > 0)
np.testing.assert_allclose(np.interp(tk, tau, t), ttk, atol=1e-6)
def test_warp_errors_perfect_and_bracketing():
tau = np.arange(400.0, 1300.1, 1.0)
t_true = tau + 10.0
t_eval = np.arange(600.0, 1100.1, 4.0)
assert warp_errors(t_true[None], tau, t_true, t_eval)["warp_rmse_ms"] == pytest.approx(0.0, abs=1e-9)
e = warp_errors(t_true[None] + np.linspace(-5, 5, 21)[:, None], tau, t_true, t_eval)
assert e["warp_rmse_ms"] == pytest.approx(0.0, abs=1e-9) and e["warp_cov90"] == 1.0
assert e["warp_width90_ms"] == pytest.approx(9.0)
def synth(seed, n=300):
rng = np.random.default_rng(seed)
return convolve_same(rng.standard_normal(n) * (rng.random(n) < 0.3), ricker(30))
def test_profile_loglik_respects_polarity():
s = synth(0)
seis = s + 0.05 * s.std() * np.random.default_rng(1).standard_normal(len(s))
ll = profile_loglik(np.stack([s, -s, 2.0 * s]), seis)
assert ll[0] > ll[1]
assert ll[2] == pytest.approx(ll[0])
@pytest.mark.parametrize("phase", [0, 45, -90])
def test_fit_phase_recovers_constant_rotation(phase):
rng = np.random.default_rng(2)
ll, ok = [], []
for w in range(2):
s = synth(10 + w)
seis = rotate_phase(s, phase) + 0.1 * s.std() * rng.standard_normal(len(s))
bank = np.stack([np.roll(s, k) for k in (-1, 0, 1)]) # warp samples around the true warp
ll.append(phase_loglik(bank, seis, PHASES))
ok.append(np.ones(3, bool))
assert PHASES[fit_phase(ll, ok, PHASES)] == phase
def tie_toy(seed: int = 0, phase: float = 0.0) -> dict:
"""A toy well: true warp drawn from the prior, blocky AI, seismic = synthetic (30 Hz Ricker rotated by `phase`)
+ 10% white noise, 4 anchors with σ_a = 3 ms."""
rng = np.random.default_rng(seed)
grid = WarpGrid(400.0, 1000.0, 4.0)
h = WarpHyper(m_g=0.0, sigma_g=0.05, ell_ms=80.0, sigma_b_ms=20.0, sigma_a_ms=3.0)
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
g = np.linalg.cholesky(K + 1e-8 * np.eye(grid.n)) @ rng.standard_normal(grid.n)
tau_fine = np.arange(grid.tau[0], grid.tau[-1] + 0.25, 0.5)
ai = np.exp(np.cumsum(0.1 * rng.standard_normal(len(tau_fine)) * (rng.random(len(tau_fine)) < 0.04)))
t_fine, t_out = np.arange(300.0, 1100.0, 0.5), np.arange(500.0, 900.1, 4.0)
w_fine = fine_wavelet(rotate_phase(ricker(30), phase), 8)
tau_k = np.linspace(450.0, 950.0, 4)
t_k = grid.t_of_tau(5.0, g, tau_k)[0] + h.sigma_a_ms * rng.standard_normal(4)
t_true = grid.t_of_tau(5.0, g, tau=tau_fine)[0]
s = synth_for_warps(tau_fine, ai, t_true, t_fine, t_out, w_fine)[0]
seis = s + 0.1 * s.std() * rng.standard_normal(len(s))
T = TiePosterior(grid, h, tau_k, t_k, 1.0, tau_fine, ai, t_fine, t_out, w_fine, seis, (t_out[0], t_out[-1]))
return dict(grid=grid, h=h, T=T, tau_fine=tau_fine, ai=ai, t_fine=t_fine, t_out=t_out, w_fine=w_fine,
tau_k=tau_k, t_k=t_k, t_true=t_true)
def anchor_samples(d: dict, n: int, seed: int) -> np.ndarray:
return sample_warps(d["grid"], d["h"], d["tau_k"], d["t_k"], n, 1.0, np.random.default_rng(seed))["u"]
def test_tie_posterior_synth_matches_synth_for_warps():
d = tie_toy()
T, U = d["T"], anchor_samples(d, 8, 1)
np.testing.assert_allclose(T.u(T.z(U)), U, atol=1e-8)
Tf = d["grid"].t_of_tau(U[:, 0], U[:, 1:], tau=d["tau_fine"])
for w in (d["w_fine"], fine_wavelet(rotate_phase(ricker(25, length_ms=200.0), 40.0), 8)): # also a longer wavelet
ref = synth_for_warps(d["tau_fine"], d["ai"], Tf, d["t_fine"], d["t_out"], w)
np.testing.assert_allclose(T.with_wavelet(w).synth(U), ref, rtol=1e-9, atol=1e-12)
np.testing.assert_array_equal(T.w_fine, d["w_fine"])
def test_residual_kappa_white_vs_band_limited_noise():
rng = np.random.default_rng(4)
s = synth(20, n=2000)
nb = convolve_same(rng.standard_normal(len(s)), ricker(30))
assert residual_kappa(s, s + 0.5 * s.std() * rng.standard_normal(len(s))) < 1.2
assert residual_kappa(s, s + 0.5 * s.std() * nb / nb.std()) > 1.5
def test_next_gamma_largest_step_with_target_ess():
ll = 30 * np.random.default_rng(5).standard_normal(128)
g = next_gamma(ll, 0.2, 1.0, 0.5)
assert 0.2 < g < 1.0 and ess((g - 0.2) * ll) >= 64 - 1e-6
assert ess((g - 0.2 + 1e-3) * ll) < 64
assert next_gamma(np.zeros(128), 0.2, 0.7) == 0.7
@pytest.mark.parametrize("phase", [-45, 0, 30, 90])
def test_phase_basis_is_exact_rotation(phase):
w0 = ricker(30)
np.testing.assert_allclose(phase_wavelet(phase_basis(w0, 8), phase), fine_wavelet(rotate_phase(w0, phase), 8),
atol=1e-12)
def test_smc_concentrates_on_true_warp():
d = tie_toy(seed=2)
T, U0 = d["T"], anchor_samples(d, 64, 3)
res = smc_tie_posterior(T, T.z(U0), [0.3, 1.0], np.random.default_rng(4))
err = lambda U: warp_errors(d["grid"].t_of_tau(U[:, 0], U[:, 1:], tau=d["tau_fine"]), d["tau_fine"],
d["t_true"], d["t_out"])["warp_rmse_ms"]
assert err(T.u(res["Z"][1.0])) < 0.5 * err(U0)
assert np.all(np.isfinite(T.parts(res["Z"][1.0])[0]))
assert res["stages"][-1]["gamma"] == 1.0 and all(s["ess"] >= 32 - 1e-6 for s in res["stages"])
assert np.isfinite(res["logZ"][0.3]) and np.isfinite(res["logZ"][1.0])
def test_smc_fit_phase_recovers_rotation():
wells = [tie_toy(seed=s, phase=30.0) for s in (5, 6)]
Z0s = [d["T"].z(anchor_samples(d, 32, i)) for i, d in enumerate(wells)]
phi, info = smc_fit_phase([d["T"] for d in wells], Z0s, phase_basis(ricker(30), 8), 0.0, [0])
assert abs(phi - 30.0) < 10.0 and not info["edge"]
def torch_tie(T):
torch = pytest.importorskip("torch")
from ml_porosity.registration.smc_torch import TiePosteriorTorch
return TiePosteriorTorch(T, "cuda:1" if torch.cuda.device_count() > 1 else "cpu")
def test_torch_tie_posterior_matches_cpu():
d = tie_toy()
T = d["T"]
G = torch_tie(T)
Z = T.z(anchor_samples(d, 8, 1))
Z = np.vstack([Z, 40.0 * Z[:2]]) # two particles violate |g| ≤ g_max
for w in (d["w_fine"], fine_wavelet(rotate_phase(ricker(25, length_ms=200.0), 40.0), 8)):
Tw, Gw = T.with_wavelet(w), G.with_wavelet(w)
np.testing.assert_allclose(Gw.synth(T.u(Z)), Tw.synth(T.u(Z)), rtol=1e-9, atol=1e-12)
(bc, lc), (bg, lg) = Tw.parts(Z), Gw.parts(Z)
assert not np.isfinite(bc[-2:]).any()
np.testing.assert_array_equal(np.isfinite(bg), np.isfinite(bc))
np.testing.assert_array_equal(np.isfinite(lg), np.isfinite(lc))
ok = np.isfinite(bc)
np.testing.assert_allclose(bg[ok], bc[ok], rtol=1e-10)
np.testing.assert_allclose(lg[ok], lc[ok], rtol=1e-10)
assert Gw.n_eval == Tw.n_eval
np.testing.assert_allclose(Gw.reference(Z[:8].mean(0), 0.5)[1], Tw.reference(Z[:8].mean(0), 0.5)[1],
rtol=1e-9, atol=1e-12)
def test_torch_ess_moves_match_cpu():
from ml_porosity.registration import smc_torch
d = tie_toy(seed=2)
T = d["T"]
G = torch_tie(T)
Z = T.z(anchor_samples(d, 32, 3))
base, ll = T.parts(Z)
ref = T.reference(Z.mean(0), 0.3)
oc = ess_moves(T, Z, base, ll, 0.3, ref, 3, np.random.default_rng(7))
og = smc_torch.ess_moves(G, *map(G.tensor, (Z, base, ll)), 0.3, tuple(map(G.tensor, ref)), 3,
np.random.default_rng(7))
for a, b in zip(oc[:3], og[:3]):
np.testing.assert_allclose(b.cpu().numpy(), a, rtol=1e-8, atol=1e-10)
assert og[3] == oc[3]
def test_torch_ess_moves_memory_bounded():
"""Each call captures a new CUDA graph; retained memory must not grow with the number of calls."""
torch = pytest.importorskip("torch")
from ml_porosity.registration import smc_torch
d = tie_toy(seed=2)
G = torch_tie(d["T"])
if G.device.type != "cuda":
pytest.skip("requires CUDA")
Z = G.tensor(d["T"].z(anchor_samples(d, 32, 3)))
base, ll = G.parts_t(Z)
ref = G.reference_t(Z.mean(0), 0.3)
run = lambda: smc_torch.ess_moves(G, Z, base, ll, 0.3, ref, 1, np.random.default_rng(0))
run()
r0 = torch.cuda.memory_reserved(G.device)
for _ in range(5):
run()
assert torch.cuda.memory_reserved(G.device) == r0
def test_torch_smc_matches_cpu():
from ml_porosity.registration import smc_torch
d = tie_toy(seed=2)
T, U0 = d["T"], anchor_samples(d, 64, 3)
rc = smc_tie_posterior(T, T.z(U0), [0.3, 1.0], np.random.default_rng(4))
rg = smc_torch.smc_tie_posterior(torch_tie(T), T.z(U0), [0.3, 1.0], np.random.default_rng(4))
np.testing.assert_allclose([s["gamma"] for s in rg["stages"]], [s["gamma"] for s in rc["stages"]], rtol=1e-9)
for g in (0.3, 1.0):
assert rg["logZ"][g] == pytest.approx(rc["logZ"][g], rel=1e-9)
np.testing.assert_allclose(rg["Z"][g], rc["Z"][g], atol=1e-7)

70
tests/test_runlog.py Normal file
View File

@@ -0,0 +1,70 @@
"""ml_porosity.runlog: the log captures child workers, meta/index record the correct status, nested runs, signal forwarding."""
import csv
import json
import os
import signal
import subprocess
import sys
import time
from pathlib import Path
from ml_porosity.paths import REPO_ROOT
CHILD = ("import subprocess, sys; print('out-parent'); print('err-parent', file=sys.stderr); "
"subprocess.run([sys.executable, '-c', 'print(\"out-child\")']); sys.exit(int(sys.argv[1]))")
def launch(tmp: Path, *args: str, env: dict | None = None, **kw) -> subprocess.Popen:
env = {k: v for k, v in os.environ.items() if not k.startswith("RUNLOG_")} | {"ML_POROSITY_LOGS": str(tmp)} | (env or {})
return subprocess.Popen([sys.executable, "-m", "ml_porosity.runlog", *args], cwd=REPO_ROOT, env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kw)
def runs(tmp: Path) -> list[Path]:
return sorted((tmp / "runs").iterdir())
def test_log_meta_index(tmp_path):
p = launch(tmp_path, "-n", "demo", "--", sys.executable, "-c", CHILD, "0")
out, _ = p.communicate(timeout=60)
assert p.returncode == 0 and "out-child" in out # still echoed to the terminal
(d,) = runs(tmp_path)
log = (d / "log.txt").read_text()
assert all(s in log for s in ("out-parent", "err-parent", "out-child")) and "[0:00:00] out-parent" in log
meta = json.loads((d / "meta.json").read_text())
assert meta["status"] == "ok" and meta["exit_code"] == 0 and meta["wall_s"] >= 0 and meta["git"]["code_sha256"]
(row,) = list(csv.DictReader(open(tmp_path / "index.csv")))
assert row["name"] == "demo" and row["status"] == "ok" and row["parent"] == ""
def test_failure_keeps_exit_code(tmp_path):
p = launch(tmp_path, sys.executable, "-c", CHILD, "3")
p.communicate(timeout=60)
assert p.returncode == 3
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
assert meta["status"] == "failed" and meta["exit_code"] == 3
def test_nested_steps_go_into_parent(tmp_path):
inner = f"{sys.executable} -m ml_porosity.runlog -n step -- {sys.executable} -c 'print(1)'"
p = launch(tmp_path, "-n", "parent", "--", "bash", "-c", f"{inner} && {inner}")
p.communicate(timeout=60)
assert p.returncode == 0
(d,) = runs(tmp_path)
assert sorted(x.name for x in d.iterdir() if x.is_dir()) == ["01_step", "02_step"]
rows = list(csv.DictReader(open(tmp_path / "index.csv")))
assert [r["parent"] for r in rows] == [d.name, d.name, ""]
def test_sigterm_marks_interrupted(tmp_path):
p = launch(tmp_path, sys.executable, "-c", "import time; print('started', flush=True); time.sleep(60)")
t0 = time.time()
while not (tmp_path / "runs").exists() or not any((d / "log.txt").exists() and "started" in (d / "log.txt").read_text()
for d in runs(tmp_path)):
assert time.time() - t0 < 30
time.sleep(0.1)
p.send_signal(signal.SIGTERM)
p.communicate(timeout=30)
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
assert meta["status"] == "interrupted" and meta["signals"] == ["SIGTERM"] and p.returncode == 128 + signal.SIGTERM

View File

@@ -8,7 +8,7 @@ from ml_porosity.paths import f3_root, f3_segy
pytestmark = [ pytestmark = [
pytest.mark.data, pytest.mark.data,
pytest.mark.skipif(not f3_segy().exists(), reason="thiếu F3_entire.segy"), pytest.mark.skipif(not f3_segy().exists(), reason="missing F3_entire.segy"),
] ]
@@ -21,7 +21,7 @@ def cube():
def test_axes(cube): def test_axes(cube):
assert (cube.ilines[0], cube.ilines[-1], len(cube.ilines)) == (100, 750, 651) assert (cube.ilines[0], cube.ilines[-1], len(cube.ilines)) == (100, 750, 651)
assert (cube.xlines[0], cube.xlines[-1], len(cube.xlines)) == (300, 1250, 951) assert (cube.xlines[0], cube.xlines[-1], len(cube.xlines)) == (300, 1250, 951)
# DelayRecordingTime = 4 ms: mẫu đầu ở 4 ms, không phải 0 # DelayRecordingTime = 4 ms: the first sample is at 4 ms, not 0
assert cube.times_ms[0] == 4.0 and cube.dt_ms == 4.0 and len(cube.times_ms) == 462 assert cube.times_ms[0] == 4.0 and cube.dt_ms == 4.0 and len(cube.times_ms) == 462
@@ -30,7 +30,7 @@ def test_trace_index_matches_headers(cube, il, xl):
idx = cube._index(il, xl) idx = cube._index(il, xl)
h = cube._f.header[idx] h = cube._f.header[idx]
assert (h[segyio.TraceField.INLINE_3D], h[segyio.TraceField.CROSSLINE_3D]) == (il, xl) assert (h[segyio.TraceField.INLINE_3D], h[segyio.TraceField.CROSSLINE_3D]) == (il, xl)
# Tọa độ trong header (scalar −100) khớp phép biến đổi của .survey # Header coordinates (scalar −100) match the .survey transform
geom = SurveyGeometry.from_survey(f3_root()) geom = SurveyGeometry.from_survey(f3_root())
x, y = geom.bin_to_xy(il, xl) x, y = geom.bin_to_xy(il, xl)
assert h[segyio.TraceField.CDP_X] / 100 == pytest.approx(x, abs=0.5) assert h[segyio.TraceField.CDP_X] / 100 == pytest.approx(x, abs=0.5)

View File

@@ -11,7 +11,7 @@ from ml_porosity.data.tdr import (
) )
from ml_porosity.paths import f3_wells_dir from ml_porosity.paths import f3_wells_dir
# ---------- tổng hợp, không cần dữ liệu ---------- # ---------- synthetic, no data required ----------
def constant_velocity_log(v=2000.0, z0=0.0, z1=1000.0, dz=0.5): def constant_velocity_log(v=2000.0, z0=0.0, z1=1000.0, dz=0.5):
@@ -51,13 +51,13 @@ def test_legacy_starts_at_zero():
def test_calibration_honors_anchors_and_is_monotone(): def test_calibration_honors_anchors_and_is_monotone():
md, dt = constant_velocity_log(v=2000.0, z1=1500.0) md, dt = constant_velocity_log(v=2000.0, z1=1500.0)
base = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0) base = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
# Anchor lệch tới ±40 ms so với sonic, kiểu drift của F06-1. # Anchors offset by up to ±40 ms from the sonic, an F06-1-style drift.
za = np.array([100.0, 400.0, 700.0, 1000.0, 1300.0]) za = np.array([100.0, 400.0, 700.0, 1000.0, 1300.0])
ta = za + np.array([5.0, -20.0, 30.0, -40.0, 10.0]) # ở 2000 m/s, TWT (ms) = MD (m) ta = za + np.array([5.0, -20.0, 30.0, -40.0, 10.0]) # at 2000 m/s, TWT (ms) = MD (m)
cal = calibrate_to_anchors(base, za, ta) cal = calibrate_to_anchors(base, za, ta)
np.testing.assert_allclose(misfit_at_anchors(cal, za, ta), 0.0, atol=1e-9) np.testing.assert_allclose(misfit_at_anchors(cal, za, ta), 0.0, atol=1e-9)
assert np.all(np.diff(cal.twt_ms) > 0) assert np.all(np.diff(cal.twt_ms) > 0)
# ngoài phạm vi anchor: dịch đều theo anchor gần nhất # outside the anchor range: constant shift from the nearest anchor
assert cal.time_at(50.0) == pytest.approx(base.time_at(50.0) + 5.0) assert cal.time_at(50.0) == pytest.approx(base.time_at(50.0) + 5.0)
assert cal.time_at(1400.0) == pytest.approx(base.time_at(1400.0) + 10.0) assert cal.time_at(1400.0) == pytest.approx(base.time_at(1400.0) + 10.0)
@@ -78,7 +78,7 @@ def test_calibration_rejects_crossing_anchors():
def test_log_to_time_antialias(): def test_log_to_time_antialias():
# Log tuyến tính theo thời gian được giữ nguyên; sin 200 Hz (trên Nyquist 125 Hz của 4 ms) bị lọc. # A log linear in time is preserved; a 200 Hz sine (above the 125 Hz Nyquist of 4 ms) is filtered out.
md, dt = constant_velocity_log(v=2000.0, dz=0.15) md, dt = constant_velocity_log(v=2000.0, dz=0.15)
tdr = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0) tdr = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
t_log = tdr.time_at(md) t_log = tdr.time_at(md)
@@ -93,23 +93,23 @@ def test_log_to_time_marks_gaps():
md, dt = constant_velocity_log(v=2000.0, dz=0.15) md, dt = constant_velocity_log(v=2000.0, dz=0.15)
tdr = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0) tdr = sonic_tdr(md, dt, md0=0.0, t0_ms=0.0)
v = np.ones_like(md) v = np.ones_like(md)
v[(md > 400) & (md < 450)] = np.nan # khoảng trống 50 ms v[(md > 400) & (md < 450)] = np.nan # 50 ms gap
out = log_to_time(md, v, tdr, np.arange(300.0, 600.0, 4.0)) out = log_to_time(md, v, tdr, np.arange(300.0, 600.0, 4.0))
t_out = np.arange(300.0, 600.0, 4.0) t_out = np.arange(300.0, 600.0, 4.0)
assert np.all(np.isnan(out[(t_out > 402) & (t_out < 448)])) assert np.all(np.isnan(out[(t_out > 402) & (t_out < 448)]))
assert np.all(np.isfinite(out[(t_out < 398) | (t_out > 452)])) assert np.all(np.isfinite(out[(t_out < 398) | (t_out > 452)]))
# ---------- trên dữ liệu F3 ---------- # ---------- on F3 data ----------
needs_f3 = pytest.mark.skipif(not (f3_wells_dir() / "Lasfiles").exists(), reason="thiếu dữ liệu giếng F3") needs_f3 = pytest.mark.skipif(not (f3_wells_dir() / "Lasfiles").exists(), reason="missing F3 well data")
@needs_f3 @needs_f3
@pytest.mark.data @pytest.mark.data
@pytest.mark.parametrize( @pytest.mark.parametrize(
"name,n_anchors,lo,hi", "name,n_anchors,lo,hi",
[ # plan mục 1.2b và 1.2e: TWT tích phân DT − marker TD trong 600–1100 ms [ # plan §1.2b and §1.2e: integrated-DT TWT − TD marker within 600–1100 ms
("F02-1", 11, -44, 2), ("F02-1", 11, -44, 2),
("F03-2", 9, -14, -3), ("F03-2", 9, -14, -3),
("F03-4", 9, -52, -42), ("F03-4", 9, -52, -42),
@@ -147,7 +147,7 @@ def test_f3_calibrated_tdr(name):
@pytest.mark.data @pytest.mark.data
@pytest.mark.parametrize( @pytest.mark.parametrize(
"name,mean_ms", "name,mean_ms",
[("F02-1", 40.5), ("F03-2", 40.2), ("F03-4", 25.2), ("F06-1", -14.6)], # plan mục 1.2c [("F02-1", 40.5), ("F03-2", 40.2), ("F03-4", 25.2), ("F06-1", -14.6)], # plan §1.2c
) )
def test_f3_dt_model_offset_matches_plan(name, mean_ms): def test_f3_dt_model_offset_matches_plan(name, mean_ms):
from ml_porosity.data.las_io import load_td_source, load_well from ml_porosity.data.las_io import load_td_source, load_well

View File

@@ -13,7 +13,7 @@ PICKS = GI / "Wells/Well_picks_Volve_v1.dat"
CFG = yaml.safe_load((REPO_ROOT / "configs/d3_volve.yaml").read_text()) CFG = yaml.safe_load((REPO_ROOT / "configs/d3_volve.yaml").read_text())
VSP = volve_root() / CFG["well_logs_dir"] VSP = volve_root() / CFG["well_logs_dir"]
CUBE = volve_root() / CFG["cube"] CUBE = volve_root() / CFG["cube"]
pytestmark = pytest.mark.skipif(not GI.exists(), reason="thiếu data/Volve/Geophysical_Interpretations") pytestmark = pytest.mark.skipif(not GI.exists(), reason="missing data/Volve/Geophysical_Interpretations")
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
@@ -53,16 +53,16 @@ def test_well_picks(picks):
assert deep.groupby("well").md.nunique().min() >= 6 assert deep.groupby("well").md.nunique().min() >= 6
@pytest.mark.skipif(not VSP.exists(), reason="thiếu data/Volve/Well_logs_pr_WELL") @pytest.mark.skipif(not VSP.exists(), reason="missing data/Volve/Well_logs_pr_WELL")
def test_checkshot_md_reference(picks): def test_checkshot_md_reference(picks):
"""F-15 A: checkshot ghi MD từ MSL, picks lấy TWT từ chính checkshot này nên khớp 0 ms khi MD đã quy về RKB.""" """F-15 A: the checkshot records MD from MSL and the picks take their TWT from this same checkshot, so they match to 0 ms once MD is referenced to RKB."""
cs = read_checkshot(VSP / "15_9-F-15 A/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC") cs = read_checkshot(VSP / "15_9-F-15 A/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC")
p = picks[(picks.well == "NO 15/9-F-15 A") & picks.twt_ms.notna() & picks.md.between(cs.md.min(), cs.md.max())] p = picks[(picks.well == "NO 15/9-F-15 A") & picks.twt_ms.notna() & picks.md.between(cs.md.min(), cs.md.max())]
assert len(p) >= 5 assert len(p) >= 5
assert np.abs(p.twt_ms - np.interp(p.md, cs.md, cs.twt_ms)).max() < 0.5 assert np.abs(p.twt_ms - np.interp(p.md, cs.md, cs.twt_ms)).max() < 0.5
@pytest.mark.skipif(not VSP.exists(), reason="thiếu data/Volve/Well_logs_pr_WELL") @pytest.mark.skipif(not VSP.exists(), reason="missing data/Volve/Well_logs_pr_WELL")
def test_f11t2_picks_vs_nivsp(picks): def test_f11t2_picks_vs_nivsp(picks):
cs = read_checkshot(VSP / "15_9-F-11 T2/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC") cs = read_checkshot(VSP / "15_9-F-11 T2/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC")
p = picks[(picks.well == "NO 15/9-F-11 T2") & picks.twt_ms.notna() & picks.md.between(cs.md.min(), cs.md.max())] p = picks[(picks.well == "NO 15/9-F-11 T2") & picks.twt_ms.notna() & picks.md.between(cs.md.min(), cs.md.max())]
@@ -70,10 +70,10 @@ def test_f11t2_picks_vs_nivsp(picks):
assert np.abs(p.twt_ms - np.interp(p.md, cs.md, cs.twt_ms)).max() < 7 assert np.abs(p.twt_ms - np.interp(p.md, cs.md, cs.twt_ms)).max() < 7
@pytest.mark.skipif(not CUBE.exists(), reason="thiếu cube ST10010") @pytest.mark.skipif(not CUBE.exists(), reason="missing ST10010 cube")
def test_volve_cube(hugin): def test_volve_cube(hugin):
"""Byte 215 = 3 không phải scalar thời gian hợp lệ; segyio vẫn nhân delrt với nó nên t0 = 12 ms, đúng là 4 ms """Byte 215 = 3 is not a valid time scalar; segyio still multiplies delrt by it, giving t0 = 12 ms instead of the correct
(EBCDIC C11). Cube thiếu 26 trace ở rìa nên phải đọc theo bảng IL/XL từ header.""" 4 ms (EBCDIC C11). The cube lacks 26 edge traces, so it must be read via the IL/XL table from the headers."""
with SeismicCube(CUBE) as c: with SeismicCube(CUBE) as c:
assert (c.times_ms[0], c.times_ms[-1], c.dt_ms) == (4.0, 3400.0, 4.0) assert (c.times_ms[0], c.times_ms[-1], c.dt_ms) == (4.0, 3400.0, 4.0)
assert (c.ilines[0], c.ilines[-1], c.xlines[0], c.xlines[-1]) == (9961, 10361, 1961, 2680) assert (c.ilines[0], c.ilines[-1], c.xlines[0], c.xlines[-1]) == (9961, 10361, 1961, 2680)