4 Commits

Author SHA1 Message Date
0cfe202a8b Complete P4 Volve; pivot the manuscript to theory + benchmark
P4 (Volve field case). Add the deviated-well and Volve well builders
(ml_porosity/data/deviated.py, volve_wells.py), the ml_porosity/volve/
pipeline, scripts 23-25, the run_p4 drivers and tests. The protocol
configs/protocol_volve.yaml was locked at 2026-10-29T01:17:42Z before the
run (.sha256, .lock.json) and is committed here after the run. Gate G-D
failed: M2-Sa beats the selected B3 at 2/6 wells (lowo) and 3/6 (slot),
coverage90 is about 0.47, and no method has blind-well skill (R2 < 0).
A post hoc constant at the training-well mean beats every network, so
G-D had no power. The dropped P4x exploratory run is kept as a record
only (exploratory/, docs/research/p4-exploratory.md).

Applicability and Teapot Dome (exploratory, pre-declared). Scripts 26-29
and docs/research/applicability-*.md: F3 and Volve fail C1 and pass C2;
T3 power needs 5-18 blind wells with an exact reference; Teapot T0 and
pilot P-a failed, so Teapot is stopped. Raw Teapot data stay gitignored.

Manuscript (Pivot 1, level A). Reframe paper/ as a theory and synthetic
benchmark paper: Propositions 3-6, Corollaries 3-4, T4 coverage
(script 30) and the post hoc H2b bound check (script 31), with F3/Volve
moved to Appendix B. Correct two earlier claims: the Berkson and
classical bounds differ by 1.5-4.6x at the f^4-weighted band, and the
bank gain exceeds the registered classical bound (7/8 wide cells at
N = 16) but only 3/8 under the post hoc Berkson bound.

Docs. Sync plan, AGENTS.md, README, report.html, theory and technical
overview. The length pass for the venue is dropped by the user
(plan section 12 item 25); the length risk stays recorded as R9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:18:22 +00:00
7da6b077b6 Record SEG/EAGE literature scan; close abstract-only check of P04/P05/P07/P09
- docs/plan.md §2.4 item 4: SEG/EAGE expanded abstracts 2024-2026 scanned
  on 28/10/2026. DOIs checked against Crossref, abstracts read via OpenAlex.
  No work trains a property predictor on a tie posterior; the closest is
  AWSM (Lim et al., IMAGE 2025). Two details from the initial scan that the
  abstracts do not support are not used. Positioning map (§2.2) and
  reference table (§11) list the ten abstract-only entries. (The
  manuscript changes for the scan were included in 4a5d0b2.)
- P04, P05, P07, P09: full texts confirmed unobtainable; every use in the
  manuscript was checked against the abstracts and the abstract-only
  footnote stays. P03 has full text (refs/xu2024sts.pdf). Bib annotations,
  related-work todo, refs/MISSING.md and the report.html checklist updated.
- Reference paths in plan, bib notes and report.html follow the refs/
  naming convention (PDF named by BibTeX key).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 07:21:39 +00:00
4a5d0b26e6 Add manuscript draft with F3 results; close P3
- paper/: LaTeX draft. Section 6.4 reports the F3 nested leave-one-well-out
  test (gate G-C failed: 1/4 wells improved, macro coverage 0.52/0.61) with
  all-method, sensitivity and ablation tables, posterior width, LOAO and the
  descriptive volume. Discussion, abstract, introduction and conclusion carry
  the F3 outcome; Volve parts remain marked as todo.
- Correct the pre-registration wording for F3: the protocol hash lock
  preceded the run, but the protocol was committed and tagged only after it.
- scripts/22_paper_figures.py: paper figures, including the F3 inline
  section (f3_volume).
- docs/plan.md §12 item 17: close P3 without a rerun, record the lock
  timeline, the post hoc descriptive analyses and the axis label issue in
  the locked plot_sections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 07:13:20 +00:00
9976abc96b Complete P3 F3 evaluation and Windows execution
Implement the frozen F3 protocol, nested LOWO, posterior label banks,
ablations, diagnostics, checkpoint validation and full-volume inference.
Record the negative G-C result: improvement at 1/4 wells, coverage80 52.38%
and coverage90 60.91%, with unchanged thresholds and historical P2 results.

Add native Windows logging, the RTX 3060 environment lock, detached runs,
and an audited dashboard-lock recovery that preserves frozen scientific code.
Update report.html, the plan and agent guidance with completed P3 status.
Archive thesis sources under code_thesis with identical Git blobs and record
the original-output audit without committing large data or model artifacts.

Validation: 129 tests passed, 13 skipped; CUDA end-to-end smoke passed;
completion audit verified 1,320 checkpoint/prediction pairs, 28 registration
bundles and all 649 interior volume inlines. Scripts 04 and 09 were not rerun.

Co-authored-by: Codex <codex@openai.com>
2026-10-28 07:01:08 +07:00
112 changed files with 11528 additions and 891 deletions

8
.gitattributes vendored Normal file
View File

@@ -0,0 +1,8 @@
# Frozen protocols were locked on Linux. Preserve their exact LF bytes on Windows.
configs/protocol*.yaml text eol=lf
configs/d2_synth*.yaml text eol=lf
logs/index.csv text eol=lf
# Keep the historical archive byte-for-byte, including its original line endings.
code_thesis/** -text
# This one archived file was originally stored as LF text in Git.
code_thesis/train_open_patch_v2.py text

7
.gitignore vendored
View File

@@ -3,6 +3,7 @@ __pycache__/
*.pyc *.pyc
.ipynb_checkpoints/ .ipynb_checkpoints/
.venv/ .venv/
.tools/
.claude/ .claude/
# Dữ liệu lớn / artifact huấn luyện (không đẩy lên git) # Dữ liệu lớn / artifact huấn luyện (không đẩy lên git)
@@ -15,9 +16,11 @@ __pycache__/
*.pth *.pth
events.out.tfevents.* events.out.tfevents.*
outputs/ outputs/
outputs_thesis/
# 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 # 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/ logs/runs/
logs/.index.lock
# 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/
@@ -44,3 +47,7 @@ data/Volve/
# NLOG: LAS và TD công khai tải lại được (URL trong docs/research/f3-nlog-inventory.xlsx), hash ở data_manifest/nlog.json # NLOG: LAS và TD công khai tải lại được (URL trong docs/research/f3-nlog-inventory.xlsx), hash ở data_manifest/nlog.json
data/NLOG/ data/NLOG/
# Teapot Dome (RMOTC / U.S. DOE, Texas Data Repository; 1.7 GB): không đẩy lên git. Chỉ dùng cho T0 và pilot P-a
# (plan §12 ý 23); kết quả ở outputs/teapot/.
data/Teapot/

147
AGENTS.md
View File

@@ -1,10 +1,10 @@
# AGENTS.md # AGENTS.md
Seismic-to-porosity learning on F3 when the well tie is uncertain (RML: training on labels drawn from a well-tie posterior). Paper deadline: Sat 31/10/2026. Gate thresholds never change; only dates do. Seismic-to-porosity learning on F3 when the well tie is uncertain (RML: training on labels drawn from a well-tie posterior). Paper deadline: **Sat 14/11/2026** (moved on 29/10/2026 from 31/10; Pivot 1, level B, `docs/plan.md` §12 item 22). Gate thresholds never change; only dates do.
Read first: `docs/plan.md` (plan, gates, decisions; §6 roadmap, §10 forbidden claims, §12 decision log), `README.md` (setup, scripts, logging), `docs/theory.md`. Progress page: `report.html`. These docs are in Vietnamese. Read first: `docs/plan.md` (plan, gates, decisions; §6 roadmap, §10 forbidden claims, §12 decision log), `README.md` (setup, scripts, logging), `docs/theory.md`. Progress page: `report.html`. These docs are in Vietnamese.
## Status (27/10/2026) ## Status (29/10/2026)
- P0, P1 done. P2 closed: gate G-B failed on 26/10 and the P2 verdict stands. - P0, P1 done. P2 closed: gate G-B failed on 26/10 and the P2 verdict stands.
- **P2r** (P2 rerun on new realizations 8–15 under the new pre-registration `configs/protocol_p2r.yaml`) is done and committed (5a6fb2f). Summary in `outputs/p2r/summary/` (`verdict.json`, `summary.md`); details in `docs/plan.md` §12 items 11–14. - **P2r** (P2 rerun on new realizations 8–15 under the new pre-registration `configs/protocol_p2r.yaml`) is done and committed (5a6fb2f). Summary in `outputs/p2r/summary/` (`verdict.json`, `summary.md`); details in `docs/plan.md` §12 items 11–14.
@@ -13,24 +13,157 @@ Read first: `docs/plan.md` (plan, gates, decisions; §6 roadmap, §10 forbidden
- H3 is descriptive only: every ensemble under-covers. No calibration claims. - H3 is descriptive only: every ensemble under-covers. No calibration claims.
- No Pivot 1. P2r is a deviation (designed after P2 failed). The paper's Methods must say so. - No Pivot 1. P2r is a deviation (designed after P2 failed). The paper's Methods must say so.
- No P2r jobs are running. Nothing needs resuming. - No P2r jobs are running. Nothing needs resuming.
- **P3 F3 is complete** (28/10, 06:50 +07:00): 1,320 nested-LOWO trajectories,
diagnostics/ablations, 20 deployment models, and the full 649-interior-inline
volume. **G-C failed both conditions**: improvement at 1/4 wells; macro
coverage80 = 52.38%, coverage90 = 60.91%. Do not claim field superiority or
calibrated uncertainty. The original P2/P2r conclusions are unchanged.
- Frozen protocol: `configs/protocol_f3.yaml` + `.sha256` + `.lock.json`.
The lock includes code, environment and inputs; do not regenerate it after
results. Code changes require an explicitly documented new version.
- The first run stopped at 132/649 volume inlines because Windows locked
`outputs/p3/progress.js`. `operations/resume_f3_volume.py` recovered only
inference with dashboard retries, preserving registered code and completed
rows. Audit: `outputs/p3/volume_recovery.json`, `completion_checks.json`.
- Details: `docs/plan.md` §12 items 15–16 and
`docs/research/p3-code-review.md`. `report.html` contains the completed
status and G-C result even without the local output sidecar.
- **P4 Volve is complete** (29/10, 02:21 UTC) on the Linux server (H200, cuda:1
primary arm, cuda:0 σ_a arms in parallel), not on the Windows workstation.
Protocol `configs/protocol_volve.yaml` locked 01:17:42 UTC (`.lock.json`,
`.sha256`); driver `scripts/run_p4.sh`. **G-D: no consistent improvement, not
calibrated** (M2-Sa beats selected B3 at 2/6 wells lowo, 3/6 slot; coverage90
≈ 0.47). No method has blind-well skill on Volve (R² < 0 everywhere, PCC ≤ 0.24);
σ_a arms change nothing. Details: `docs/plan.md` §12 item 20,
`outputs/p4/summary/`. Do not rerun or redesign P4.
- Post hoc, outside the lock (`scripts/25_p4_posthoc.py` → `outputs/p4/posthoc/`):
a constant at the training-well PHIF mean beats every network (macro RMSE
6.03 lowo, 6.59 slot). Between-well level differences dominate the error, so
G-D had no power: Volve is evidence neither for nor against RML.
- **P4x exploratory is dropped** (decision of 29/10/2026). `exploratory/`
and `outputs/p4x/` stay on disk as a record only: do not summarise, cite,
or extend them (no V3). The last `exploratory/run_p4x.sh` job was stopped
at 670/921 (about 04:05 UTC) and killed to free cuda:0; B3d-Sa and V3
never ran. A partial summary generated at 04:07 UTC, before the
decision was seen, has been deleted (`outputs/p4x/summary/` no longer
exists). Do not restart the job or rerun its summarize stage. History: `docs/plan.md` §12 item 21.
- **Pivot 1 activated (29/10/2026)**: the paper is now a theory + synthetic
benchmark paper. Working title: *Label registration error in sparse-well
seismic property learning: theory, a registration-aware benchmark, and the
limits of field validation*. F3 and Volve are scope-bounding cases only.
Decisions (user fixed 1 and 5; agent fixed 2–4): (1) level B, deadline
14/11/2026; (2) misspecification axis S2 is mandatory, narrow scope, locked
in a new `configs/protocol_bench.yaml` before the first run, otherwise the
paper says "controlled synthetic study", not "benchmark"; (3) the mechanism
study T2 is exploratory on realizations 8–15, pre-declared in
`docs/research/t2-mechanism.md`, never confirmatory; (4) venue *Computers &
Geosciences*, fallback *Geophysical Prospecting*; (5) P4x dropped. Full
analysis and plan: `docs/research/pivot-theory-benchmark.md` (§6 has the
decisions and the day-by-day schedule); public field-dataset survey:
`docs/research/field-dataset-survey.md` (no dataset confirmed adequate; no
new field test in this paper).
- **Applicability conditions and a Teapot Dome attempt (29/10/2026,
exploratory; `docs/plan.md` §12 item 23).** Declared in
`docs/research/applicability-teapot.md` before any computation; results in
`docs/research/applicability-results.md`. Retrospective C1/C2
(`scripts/26_applicability.py`): F3 and Volve fail C1 (no blind-well skill
in the seismic band) and pass C2. T3 power (`scripts/27_t3_power.py`): with
an exact reference a sign test needs 5–18 blind wells in most cells; with
reference errors of 3 ms or more, 40 wells do not suffice. Teapot T0 failed
(at most 2 wells with an independent time–depth reference), and the pilot
P-a requested by the user failed (horizon–top knot error 6.75 ms against a
1.5 ms tolerance). Teapot is stopped; the user chose to return to the
level-B schedule. The raw Teapot data (`data/Teapot/`, 1.7 GB) are
gitignored.
- **Level A writing done early (29/10/2026; `docs/plan.md` §12 item 24).**
`paper/` now follows the Pivot 1 frame (55 pages, compiles cleanly):
Propositions 3–6 (classical/Berkson tie error, calibrated bank with a
fourth-order population gain, coverage, misregistered reference),
Corollaries 3–4, T4 (`scripts/30_t4_coverage.py`) and the post hoc H2b
bound check (`scripts/31_p2r_posthoc.py`) in Sec. 6.3, T3 in Sec. 6.5,
field cases in Sec. 6.6 with F3/Volve details moved to Appendix B. Red
TODOs remain for S1–S8, T2 and the authors' declarations. **Self-correction
(29/10, A6):** two earlier agent claims were wrong. The first was "the two
error structures give nearly the same bound (factor < 1.17)". In fact the
f⁴-weighted distortion sits at 67–72 Hz, where the Berkson integral is
1.5–4.6 times the classical one at σ = 1.5–2.5 ms. The second was "the bank
gain exceeds the population bound". That holds only for the registered
classical bound (7/8 wide cells at N = 16). Under the post hoc Berkson
bound, the natural one for posterior-mean labels, only 3/8 cells exceed it
(all at c = 1), and at most 1/8 at the measured warp error. Script 31 now
computes both bounds and reads the Oracle npz files (about 6 min). The paper
(Sec. 4.3, 6.3 with a 1/B_b column in `tab:h2b`, 6.4, 7, abstract,
introduction, conclusion) and the docs were corrected. **Length risk:**
the main text is about 14,750 words (crude count after A6) against a Computers & Geosciences limit
of about 5,500 (secondary source; not yet checked on the official page).
The user dropped the length pass for the venue on 29/10/2026 (`docs/plan.md`
§12 item 25); the risk stays recorded as R9 with no mitigation.
- Committed and pushed on 29/10/2026 with the tag `protocol-volve` (the Volve
code hash recomputed from that tree matches `configs/protocol_volve.lock.json`):
the P4 code, `configs/protocol_volve.*`, scripts 26–31, the `docs/research/`
additions, the P4x record (`exploratory/`, `docs/research/p4-exploratory.md`),
`.gitignore`, and the 29/10 paper/docs edits. Run logs `logs/*.out` stay
untracked, as before (`docs/plan.md` §12 item 25).
## Next ## Next
1. **P3 F3 field** (gate G-C, end of 28/10): nested LOWO, ensembles, calibration, ablation, leave-one-anchor-out, volume with uncertainty. The "direction of improvement on synthetic" in G-C comes from the P2r main grid. Lock its protocol first as `configs/protocol_f3.yaml` + `.sha256` (P3 has no protocol yet). Schedule: `docs/plan.md` §6.1 (level B, 29/10 → 14/11/2026). Cut-scope order
2. **P4 Volve** (pipeline 28/10, runs 29/10, gate G-D). if late is given there; never cut thresholds.
3. **P5 writing** (29–30/10). If late, cut scope in the order given in `docs/plan.md` §6.
1. **Dataset citations (30–31/10).** Level A writing is done (plan §12 item 24).
Add the F3 and Volve dataset citations to `paper/refs.bib`. The length pass
for the venue was dropped by the user on 29/10/2026 (plan §12 item 25): do
not schedule it. The rest of these two days is buffer.
2. **T2 mechanism study (1/11), exploratory:** declare
`docs/research/t2-mechanism.md` before running. The question is now
whether any bank gain remains beyond the population correction of the
Berkson structure. Five tests, as in the Sec. 6.4 todoblock: (i)
responsibility-weighted warp error vs. mean-warp error; (ii) random GP-noise
bank control; (iii) multimodal-cell split; (iv) Berkson-vs-classical
covariance test for the bulk offset of B3d-Sa and B3c-R, which decides which
bound applies; (v) B3d-Sa retrained at the Oracle's 500 iterations. The
declaration must disclose what was already inspected post hoc on 29/10
(`outputs/p2r/posthoc/`): the Oracle/B3d-Sa and M2-Sa/B3d-Sa ratios and
every bound, (a), (b), b60 and cross-spectral, at σ_post and at the warp
error.
3. **protocol_bench (2–3/11):** add misspecification parameters to
`ml_porosity/data/synth_d2.py` without changing the default path (P2r must
still reproduce); dev on new realizations 902–905 only; lock
`configs/protocol_bench.yaml` + `.sha256` + `.lock.json` before the first
main run. Contents: S1 grid fill (c ∈ {0.5, 1.5}, N ∈ {2, 8}), S2 three
misspec axes (R10, Rm5; c = 1; N ∈ {4, 16}; Oracle, B3c-R, B3d-Sa, M2-Sa),
S3 (B4 under the SMC posterior), S4 (second backbone), S8 (controlled
cycle-skip regime). Realizations 8–15 for all main cells.
4. **Runs (4–7/11)** on both GPUs, detached with `setsid nohup`, via a
`scripts/run_bench.sh` driver with runlog. Report results as they come out.
5. **S7 packaging (8–10/11):** one command to generate, one to score, reference
tables, README, hashes, Zenodo deposit; then rewrite the results sections.
6. **Review and submission (11–14/11):** internal review, figures, proof
appendix, final novelty scan, quartile check, preprint, submit to
*Computers & Geosciences*.
## Conventions ## Conventions
- **Naming:** `protocol_p2r` = the D2 rerun of P2. "P3" in the plan means the F3 field phase (future `protocol_f3`). Do not reuse the name `protocol_p3`. - **Naming:** `protocol_p2r` = the D2 rerun of P2. "P3" in the plan means the F3 field phase (`protocol_f3`). Do not reuse the name `protocol_p3`.
- **Locked protocols:** `configs/protocol*.yaml` are locked by SHA-256 files and git tags. Never edit a locked protocol or relax a threshold. New decisions go in a new protocol with a recorded deviation. Report results as they come out, including failures. - **Locked protocols:** `configs/protocol*.yaml` are locked by SHA-256 files and git tags. Never edit a locked protocol or relax a threshold. New decisions go in a new protocol with a recorded deviation. Report results as they come out, including failures.
- **No test-label leakage:** nothing (shift, checkpoint, hyperparameter) may be chosen using test labels. Design choices come from dev only (realizations 900/901). - **No test-label leakage:** nothing (shift, checkpoint, hyperparameter) may be chosen using test labels. Design choices come from dev only (realizations 900/901).
- **Git:** work on `main`. Do not create branches unless the user explicitly asks. End commit messages with a co-author line for the agent. - **Git:** work on `main`. Do not create branches unless the user explicitly asks. End commit messages with a co-author line for the agent.
- **Language:** code, figures, paper text and commit messages in academic English. Explanations to the user in Vietnamese. - **Language:** code, figures, paper text and commit messages in academic English. Explanations to the user in Vietnamese.
- **Decisions:** decide from evidence and proceed. Do not block on supervisor (GVHD) sign-off. - **Decisions:** decide from evidence and proceed. Do not block on supervisor (GVHD) sign-off.
- **Keep docs in sync (every task):** whenever you change anything (a run starts, finishes, fails or is stopped; a result, decision, deadline, protocol, script or file is added or changed), update in the same turn every file that states it: `report.html` (task status and notes, result cards, FINDS, DECISIONS, LOG), `docs/plan.md` (§0, §6 roadmap, §12 decision log), `AGENTS.md` (Status, Next), and where relevant `README.md` (scripts, run commands), `paper/README.md` (number sources), `docs/technical_overview.md` and `docs/research/*.md`. Before ending the turn, grep these files for older statements about the same item (for example "running", old counts or dates) and correct them, so no two files disagree. After editing `report.html`, check that its data block still parses (balanced brackets and quotes).
- **GPU (shared server):** choose cuda:0 or cuda:1 by free memory and load. Never touch other users' jobs. Set `OMP_NUM_THREADS`, `MKL_NUM_THREADS` and `OPENBLAS_NUM_THREADS` explicitly when running by hand (the machine default is 40). - **GPU (shared server):** choose cuda:0 or cuda:1 by free memory and load. Never touch other users' jobs. Set `OMP_NUM_THREADS`, `MKL_NUM_THREADS` and `OPENBLAS_NUM_THREADS` explicitly when running by hand (the machine default is 40).
- **Long runs:** detach multi-hour runs with `setsid nohup ... &` so they survive the agent session. Wrap runs with `scripts/runlog.sh` or the `run_p*.sh` drivers. Scripts 11/14/15 resume by skipping finished cells. - **Long runs:** detach multi-hour runs with `setsid nohup ... &` so they survive the agent session. Wrap runs with `scripts/runlog.sh` or the `run_p*.sh` drivers. Scripts 11/14/15 resume by skipping finished cells.
- `test 2/` is an archive of the thesis code: do not modify. - `code_thesis/` is the unchanged thesis-code archive (renamed from `test 2/`): do not modify its contents.
- **User constraint:** do not rerun `04_wavelet_tie.py` or
`09_fit_warp_prior_f3.py`, or overwrite their historical artifacts. P3 uses
its own training-fold-local estimates and checks the old artifacts' hashes.
- **This Windows workstation:** RTX 3060 12 GB, driver 577.00, Python 3.12.16,
torch 2.11.0+cu128; versions in `requirements-windows-rtx3060.txt`. Linux's
environment lock is separate. The native driver is `scripts/run_p3.ps1`;
use process-local `-ExecutionPolicy Bypass`, four workers and two CPU threads
per worker. Do not launch another P3 run just because historical logs show a
failure: the volume recovery has already completed and passed its audit.
## Not in git (other machines) ## Not in git (other machines)

View File

@@ -12,6 +12,47 @@ python -m venv .venv
Dữ liệu F3 Demo 2023 đặt ở `data/F3_Demo_2023/F3_Demo_2023/`, dữ liệu Volve ở `data/Volve/`, LAS và TD của NLOG ở `data/NLOG/` (hoặc trỏ `ML_POROSITY_F3_ROOT` tới thư mục chứa `.survey`). Kết quả ghi vào `outputs/` (đổi bằng `ML_POROSITY_OUTPUTS`). Dữ liệu F3 Demo 2023 đặt ở `data/F3_Demo_2023/F3_Demo_2023/`, dữ liệu Volve ở `data/Volve/`, LAS và TD của NLOG ở `data/NLOG/` (hoặc trỏ `ML_POROSITY_F3_ROOT` tới thư mục chứa `.survey`). Kết quả ghi vào `outputs/` (đổi bằng `ML_POROSITY_OUTPUTS`).
Code luận văn được lưu ở [`code_thesis/`](code_thesis/), các output gốc ở [`outputs_thesis/`](outputs_thesis/). SHA-256 của 7 artifact nằm trong [`data_manifest/thesis_outputs.json`](data_manifest/thesis_outputs.json); kết quả kiểm tra ngày 27/10/2026 ở [thesis-output-audit.md](docs/research/thesis-output-audit.md). Pipeline nghiên cứu ghi kết quả mới vào `outputs/`.
## P3 trên Windows / RTX 3060
Môi trường trên máy này: Python 3.12.16, PyTorch 2.11.0+cu128, driver NVIDIA
577.00, RTX 3060 12 GB và RAM 24 GB. Các phiên bản được lưu riêng trong
`requirements-windows-rtx3060.txt`; không thay bản khóa môi trường Linux.
Cài vào venv bằng `uv pip install --python .venv/Scripts/python.exe -r
requirements-windows-rtx3060.txt`, rồi cài project bằng `uv pip install --python
.venv/Scripts/python.exe --no-deps -e .`.
P3 dùng `configs/protocol_f3.yaml`. Bản khóa kèm theo lưu SHA-256 của protocol,
code, dữ liệu đầu vào và phiên bản thư viện. Checkpoint được chọn bằng ba vòng
validation bên trong, giếng ngoài chỉ dùng để chấm điểm. Đọc chi tiết rà soát
và giới hạn khoa học ở [p3-code-review.md](docs/research/p3-code-review.md).
```powershell
# Chỉ dùng khi chưa khóa/chưa chạy P3; không khóa lại sau khi có kết quả.
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/run_p3.ps1 -Stage lock
# Chạy toàn bộ: registration, 1.320 trajectory, diagnostics, LOWO, 20 mô hình volume.
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/run_p3.ps1 -Stage all -Device cuda:0 -Workers 4 -Detach
```
Lệnh `all` có thể chạy lại để resume đúng fingerprint; job hoàn tất được kiểm
tra checksum trước khi tái sử dụng. Không chạy đồng thời hai scheduler trên cùng
thư mục output. Tiến độ cập nhật mỗi 10 giây khi mở [report.html](report.html),
kể cả qua `file://`; dữ liệu gốc ở `outputs/p3/progress.json`, log ở `logs/runs/`.
Process giữ máy thức trong thời gian chạy, không đổi chính sách nguồn toàn hệ
thống. Driver giới hạn mỗi worker ở hai luồng CPU và chạy cửa sổ nền ẩn.
Benchmark thực tế so sánh 1/2/3/4/6 worker: 4 nhanh nhất (khoảng 319 bước/s).
Riêng huấn luyện dự kiến 1,6–3,3 giờ; tổng thời gian có thêm registration,
diagnostics và volume được lưu ở `outputs/p3/progress.json` sau pilot. Đây là
khoảng dự toán thời gian, không phải khoảng tin cậy thống kê.
**Theo yêu cầu phiên làm việc: không chạy script 04 hoặc 09.** P3 chỉ fit
wavelet/prior cục bộ theo đúng giếng train, ghi trong `outputs/p3/`; hai artifact
cũ `outputs/wavelets.npz` và `outputs/p2/warp_prior_f3.json` được bảo vệ bằng hash.
G-C giữ nguyên: cải thiện ít nhất 3/4 giếng và coverage 80/90% trong ±5 điểm %.
Kết quả G-C nằm ở `outputs/p3/summary/gate_gc.json`; fail vẫn được báo cáo.
## Chạy ## Chạy
```bash ```bash
@@ -19,6 +60,9 @@ 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_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) 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)
scripts/run_p2r_main.sh # lưới chính P2r trên realization 8–15
scripts/run_p4.sh # P4 Volve: register, train, summarize nhánh σ_a chính (DEVICE mặc định cuda:1)
ARMS=sensitivity scripts/run_p4.sh register train # nhánh σ_a = 3,5 / 14 ms; sau đó ARMS=all scripts/run_p4.sh summarize
``` ```
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`: 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`:
@@ -37,7 +81,7 @@ Biến môi trường máy đặt sẵn `OMP_NUM_THREADS=40` (cả MKL, OpenBLAS
| 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\|thesis]` | Ghi/kiểm SHA-256 theo `data_manifest/*.json` (F3: 279 file; thesis: 7 artifact trong `outputs_thesis/`) |
| `scripts/01_build_wells.py` | Vị trí giếng từ `.survey`, 4 TDR (legacy, calibrated, anchors, wlt), log sang thời gian có chống alias, trích patch seismic → `outputs/f3_wells.npz` | | `scripts/01_build_wells.py` | Vị trí giếng từ `.survey`, 4 TDR (legacy, calibrated, anchors, wlt), log sang thời gian có chống alias, trích patch seismic → `outputs/f3_wells.npz` |
| `scripts/02_td_qc.py` | Lệch của các nguồn TD so với marker → `outputs/figures/td_drift.png`, `outputs/td_qc.csv` | | `scripts/02_td_qc.py` | Lệch của các nguồn TD so với marker → `outputs/figures/td_drift.png`, `outputs/td_qc.csv` |
| `scripts/03_train.py --config configs/b2_smoke.yaml` | CNN–GRU v2 + loss gốc (B2), split tách rời train/val/test (chạy thử P0) | | `scripts/03_train.py --config configs/b2_smoke.yaml` | CNN–GRU v2 + loss gốc (B2), split tách rời train/val/test (chạy thử P0) |
@@ -55,5 +99,19 @@ Biến môi trường máy đặt sẵn `OMP_NUM_THREADS=40` (cả MKL, OpenBLAS
| `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/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/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` | | `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` |
| `scripts/18_summarize_p2r.py [--root DIR]` | Phán quyết của `protocol_p2r` trên lưới chính (realization 8–15): H2a, H2b, σ_a, H3, H4 → `outputs/p2r/summary/` (`verdict.json`, `summary.md`) |
| `scripts/19_run_f3.py <stage> [--device] [--workers]` | P3 F3: prepare → benchmark → lock → register → train → diagnostics → summarize theo `configs/protocol_f3.yaml` → `outputs/p3/` |
| `scripts/20_summarize_f3.py` | Tổng hợp lượt P3 đã khóa, cổng G-C → `outputs/p3/summary/` |
| `scripts/21_predict_f3.py` | Mô hình triển khai và volume F3 mô tả (649 inline) sau LOWO của P3 → `outputs/p3/volume/` |
| `scripts/22_paper_figures.py [--only …]` | Hình cho bài báo (`paper/figures/*.pdf`), chỉ đọc các summary đã khóa |
| `scripts/23_build_volve_wells.py [--config configs/d3_volve.yaml]` | Dữ liệu 6 giếng nghiêng Volve trên miền thời gian (survey, TDR calibrated và blind, patch 3×3 dọc đường giếng, nhãn PHIF) → `outputs/volve/volve_wells.npz`, `volve_wells_summary.json` |
| `scripts/24_run_volve.py <stage> [--arms primary\|sensitivity\|all] [--device] [--workers]` | P4 Volve: benchmark → lock → register → train → summarize theo `configs/protocol_volve.yaml`, cổng G-D → `outputs/p4/` |
| `scripts/25_p4_posthoc.py` | Post hoc P4, ngoài khóa, không đổi G-D: hằng số bằng trung bình giếng train và tách RMSE thành bias + SD → `outputs/p4/posthoc/` |
| `scripts/26_applicability.py` | Điều kiện áp dụng C1, C2 (khai báo ở `docs/research/applicability-teapot.md`), hồi cứu trên F3 và Volve; chỉ đọc output đã khóa và nhãn giếng train của từng fold, không train → `outputs/applicability/` |
| `scripts/27_t3_power.py` | T3 exploratory: chấm lại dự đoán P2r đã lưu với tham chiếu lệch σ_ref, power của luật k-of-n và sign test theo số giếng blind (beta-binomial) → `outputs/t3/` |
| `python -P scripts/28_teapot_inventory.py --root data/Teapot/raw/rmotc --out outputs/teapot/inventory` | T0 kiểm kê Teapot Dome (chỉ header và độ phủ đường cong; không đọc quan hệ porosity–seismic). Dữ liệu là archive tải về, chạy bằng `python -P` từ gốc repo → `outputs/teapot/inventory/` |
| `python -P scripts/29_teapot_pilot.py` | Pilot P-a Teapot (Deviation 2): hình học, độ phủ horizon, σ̂_knot trên giếng dev (inline ≤ 200), không đọc porosity → `outputs/teapot/pilot_pa/` |
| `scripts/30_t4_coverage.py` | T4 post hoc, mô tả: tỉ số phân tán ξ (cột `kappa`), coverage90 và phần do số vòng lặp của các ensemble 5 seed, từ `outputs/p2r/train/*/cells/*.npz` và dev P2 → `outputs/t4/` |
| `scripts/31_p2r_posthoc.py` | Post hoc H2b, đọc `outputs/p2r/summary/` và dự đoán Oracle trong `outputs/p2r/train/<regime>/cells/*.npz` (khoảng 6 phút): tỉ số Oracle / B3d-Sa / M2-Sa, phần khoảng cách đã đóng; cận 1/B cho cấu trúc (a) classical (đã đăng ký) và (b) Berkson (thêm biến thể giữ hệ số ở 60 Hz và biến thể phổ chéo), tại σ_post và tại sai số warp; cờ vượt mép lưới B → `outputs/p2r/posthoc/{bound.csv, blur_ab.csv, meta.json}` |
`test 2/` là bản lưu trữ code luận văn, không sửa. `code_thesis/` là bản lưu trữ code luận văn. Giữ nguyên nội dung để đối chiếu: các script này còn đường dẫn máy cũ và ghi vào `outputs/`, nên cần một bản sao đã điều chỉnh đường dẫn nếu muốn chạy lại. Kiểm tra bộ artifact hiện có bằng `python scripts/00_data_manifest.py --dataset thesis --check`.

View File

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

View File

@@ -39,3 +39,70 @@ checkshots:
# ROI from the trajectories of the 10 wells above + 500 m (D3 inventory §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]
# P4 (Volve field phase, plan §6): the 6 wells with DT + RHOB + NPHI + PHIF (D3), all deviated.
# Read by ml_porosity/data/volve_wells.py and scripts/23_build_volve_wells.py (-> outputs/volve/volve_wells.npz).
p4:
survey_dir: Well_technical_data/WellWellbore # Compass "ACTUAL" exports: minimum curvature, grid north, MD RKB
log_subdir: 05.PETROPHYSICAL INTERPRETATION # under well_logs_dir/<logs>
las_input: WLC_PETRO_COMPUTED_INPUT_1.LAS # DT, RHOB, NPHI, GR
las_output: WLC_PETRO_COMPUTED_OUTPUT_1.LAS # PHIF, on the INPUT MD grid
wells:
F-1:
picks: NO 15/9-F-1
logs: 15_9-F-1
survey: 15_9-F-1/15_9-F-1/Volve F_F-1_F-1_F-1_ACTUAL
F-1 A:
picks: NO 15/9-F-1 A
logs: 15_9-F-1 A
survey: 15_9-F-1/15_9-F-1 A/Volve F_F-1_F-1 A_F-1 A_ACTUAL
F-1 B:
picks: NO 15/9-F-1 B
logs: 15_9-F-1 B
survey: 15_9-F-1/15_9-F-1 B/Volve F_F-1_F-1 B_F-1 B_ACTUAL
F-11 A:
picks: NO 15/9-F-11 A
logs: 15_9-F-11 A
survey: 15_9-F-11/15_9-F-11 A/Volve F_F-11_159-F-11 A_159-F-11 A_ACTUAL
F-11 T2:
picks: NO 15/9-F-11 T2
logs: 15_9-F-11 T2
survey: 15_9-F-11/15_9-F-11 T2/Volve F_F-11_159-F-11 T2_159-F-11 T2_ACTUAL
# Alternative TDRs from `checkshots` above. RSVSP is left out: a rig-source VSP in a deviated hole is an
# offset VSP, and its vertical times end 35 ms earlier than NIVSP at 4530 m MD.
checkshots: [NIVSP, OPTIMIZED]
F-12:
picks: NO 15/9-F-12
logs: 15_9-F-12
survey: 15_9-F-12/15_9-F-12/Volve F_F-12_F-12_F-12_ACTUAL
# Wellbores sharing a slot, i.e. the hole above the kick-off: F-1 A and F-1 B leave F-1 at 2587 m MD,
# F-11 A leaves F-11 T2 at 2580 m MD. The `slot` blind scheme holds out the whole group.
slot_groups: [[F-1, F-1 A, F-1 B], [F-11 A, F-11 T2], [F-12]]
# Blind schemes for a held-out well (plan §5.2): its input is placed in time by the mean TVDSS–TWT relation of
# the wells it is held out from, never by its own picks or DT. lowo = all other wells, slot = other slots.
blind_schemes: [lowo, slot]
# Volve ROI of plan §12 item 7; 301 samples on the 4 ms grid. Margin only (B1 inversion, synthetics): above
# ~2320 ms the calibrated TDR of 5 wells is an extension beyond DT and anchors (F-11 T2: up to 49 ms off NIVSP).
ext_window_ms: [2000, 3200]
# Input, labels and scoring, 126 samples as in F3. Contains every calibrated label support (2509–2819 ms) and
# starts below the upward extension of every calibrated TDR; below DT the path runs on to TD, then is held there.
main_window_ms: [2400, 2900]
patch_radius: 1 # 3×3 traces along the well path
patch_method: bilinear # bilinear in (IL, XL) between bins; nearest is computed for QC only
label: PHIF
curves: [PHIF, DT, RHOB, NPHI, GR, AI]
dt_valid_us_per_ft: [40, 200] # DT outside this range is set to NaN before any TDR or AI is computed
# P4 also excludes FP (faulted pick): F-1 Skagerrak Fm. Top is the only FP pick with a TWT among the 6 wells.
anchor_exclude_qlf: [NL, NR, FP]
# Picks at most this far below the previous anchor are one marker (F-1: Heather Fm. Top and Heather Fm. Sand
# VOLVE Top are 0.3 m apart); keeps two near-identical anchors out of the stretch and the warp prior.
anchor_min_sep_m: 1.0
edge_m: 30 # logged hole used for the velocity of the TDR extension beyond the DT range
# TDRs per well (ml_porosity/data/deviated.py), all integrating DT over TVD (vertical time):
# calibrated marker-calibrated vertical sonic: scoring reference (plan §5.2) and training-well path
# sonic vertical sonic through the first anchor in the DT range, uncalibrated: the τ axis of RML
# anchors linear in TVD between the anchors, without DT
tdrs: [calibrated, sonic, anchors]
resample:
fine_dt_ms: 0.25
cutoff_frac: 0.8

View File

@@ -0,0 +1,60 @@
{
"protocol_sha256": "0c756d2825d9b6aa1520be6484f501a538f2ec14e5c8fe98a323cf3b6e1bc50c",
"code_sha256": "b5c82d2dfd53dcab726499905d33c8337659907b824737f0c4d12b9035f1ae78",
"environment": {
"python": "3.12.16",
"platform": "Windows",
"packages": {
"torch": "2.11.0+cu128",
"numpy": "2.5.4",
"scipy": "1.18.1",
"pandas": "3.1.0",
"matplotlib": "3.11.2",
"segyio": "1.9.14",
"lasio": "0.32",
"pylops": "2.8.0",
"numba": "0.68.0",
"scikit-learn": "1.9.1",
"PyYAML": "6.0.3",
"tabulate": "0.10.0",
"psutil": "7.2.2"
}
},
"protected_artifacts": {
"outputs\\wavelets.npz": "b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64",
"outputs\\p2\\warp_prior_f3.json": "55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27"
},
"inputs": {
"outputs\\f3_wells.npz": "ffe213dbfa2473e1de0065c7a1a6ac2719536b930bd9b045f673c44cc21e3a52",
"configs\\d1_f3.yaml": "c944a4ab954d15a0f984c5ef314f693166833012656158ea874291388df8be4d",
"configs\\protocol.yaml": "c1c771950538ed89fbb1e6c26fed31506b44999610dc0e79d027fa6e205aa962",
"data\\F3_Demo_2023\\F3_Demo_2023\\.survey": "24e9d3993eca55b4be1ad665268501082c55a3aaa5a1f3257b4180d0ef6810d3",
"data\\F3_Demo_2023\\F3_Demo_2023\\WellInfo\\F02-1.wlt": "43f75d43398866e5fc48f2e692b4ee6a4108b5f409bd11c5bc2670826ae98da4",
"data\\F3_Demo_2023\\F3_Demo_2023\\WellInfo\\F03-2.wlt": "2f992847d64503f1daa9ec33bfbd25b2d01a95ee74afd2750008c76b6f4d96f4",
"data\\F3_Demo_2023\\F3_Demo_2023\\WellInfo\\F03-4.wlt": "748ec6dc6f787d8ab21045bbaa286084eb2acb5cc32b121a4a5a3b8f4a716bce",
"data\\F3_Demo_2023\\F3_Demo_2023\\WellInfo\\F06-1.wlt": "69bc31eb73b12abd1e854123337f42fa6faffceede2d513a0e5b69a6373d1e3b",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Lasfiles\\F02-1_logs.las": "c5bf446bd791ef481e8dd66cd030b7a24a207236e19b3e7e6b620447bda160d6",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Lasfiles\\F03-2_logs.las": "8df10a1f43b295bf68bcb04c19bf95dcb6c0e92bc199cf2a442367c0c0ef5d3b",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Lasfiles\\F03-4_logs.las": "612cd767766bb3de02b13f03330b5f9904a681d4f70a08ee10e4de78ec1c266e",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Lasfiles\\F06-1_logs.las": "d064e8e1b5e4b90eb43cf7ad58d3ced085fd76e93b974c14f3b626888ba6a01b",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\F02-01_logs.las": "3a89796a41a88007c1d7f6e96fe57d928d9e54b34dcd70e2491784e75585cc1b",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Checkshot\\F02-1_TD.txt": "eaf6e351111edc1906d1be4b89e0f4d7e8b5f257be5f0984f5b6d0eb704a258f",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Checkshot\\F03-2_TD.txt": "22c9ab38581623ad152e23b359e9258017bac3bc0ab80058c3f8316e2d0a8a51",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Checkshot\\F03-4_TD.txt": "40de3f3f3b15d4a30d31fa8ef5ee34e3c320336373133d358ba068eea6354377",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\Checkshot\\F06-1_TD.txt": "a913d0a5166ef5360f4e4e6fdfa746aba9553f6ddd467f1a816f3fc4f145c1b1",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\DT_model\\F02-1_TD.txt": "62ffe2cbd8aecbf751f237327bf37e0586f623f28b6595ec98f49680f07f7aa6",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\DT_model\\F03-2_TD.txt": "3315f9e8603cf8d5c083b60f10e421958884dbe56dd39f85a81fa3e8bcf1392b",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\DT_model\\F03-4_TD.txt": "dc1d99c7e73baa6e7f2dd9432b7066dfad8cb107ce91b66f1106016626a541c3",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\All_wells_RawData\\All_wells_RawData\\DT_model\\F06-1_TD.txt": "57743e547306704ecdaacb25d8d55c4f73eb9ff8222a551c0d4d61e86141a1e5",
"data\\F3_Demo_2023\\F3_Demo_2023\\Rawdata\\Well_data\\F02-01_TD.txt": "eaf6e351111edc1906d1be4b89e0f4d7e8b5f257be5f0984f5b6d0eb704a258f"
},
"locked_utc": "2026-10-27T17:14:50.929575+00:00",
"segy_sha256": "b36494f4e9bed7216228124f43ff8901168bff8bebd4e4c4dabb80a68d568dab",
"canonical_text": "UTF-8, CRLF normalized to LF for code and protocol; binary inputs exact",
"wells": [
"F02-1",
"F03-2",
"F03-4",
"F06-1"
]
}

View File

@@ -0,0 +1 @@
0c756d2825d9b6aa1520be6484f501a538f2ec14e5c8fe98a323cf3b6e1bc50c configs/protocol_f3.yaml

97
configs/protocol_f3.yaml Normal file
View File

@@ -0,0 +1,97 @@
# P3 F3: designed after P1 and P2r; no P3 held-out results used for these choices.
# Lock using scripts/19_run_f3.py lock before registration/training. Never overwrite a lock after results exist.
version: 1
date: '2026-10-27'
prior_observation: 'F3 is a descriptive follow-up after the already observed P1 results on these same four wells; functional outer-fold separation does not make this a new untouched field dataset.'
data:
wells: [F02-1, F03-2, F03-4, F06-1]
labels: [PHIE_DT, PHIE]
primary_label: PHIE_DT
window_ms: [600, 1100]
ext_window_ms: [400, 1300]
dataset: outputs/f3_wells.npz
references: [calibrated, wlt]
posterior_reference_samples: 64
note: 'PHIE_DT is sonic-derived porosity. TD markers are interpreted picks, not independent checkshots.'
missing_labels: 'Do not extrapolate missing porosity labels. Require each retained warp to cover measured support of both labels over the full main window; invalid anchor samples receive zero mass. Record retained particle counts and fail explicitly if too few survive. Constant AI extension outside the logged interval means zero reflectivity and is used only by the forward model.'
split:
outer: leave_one_well_out
inner: leave_one_well_out_on_the_three_outer_training_wells
seeds: [0, 1, 2, 3, 4]
selection: 'Per outer fold, label, method and seed: lowest mean original-scale total validation MSE over the three inner wells; ties choose the earliest budget.'
final: 'Ensemble the three inner models at the selected common budget; then ensemble the five seeds. No refit on the outer test well.'
cache: 'Reuse a trajectory for an identical training pair, method, label and seed. The other wells supply seismic only to prediction; their labels never enter that trajectory.'
registration:
kernel: matern32
sigma_a_ms: 7.0
sigma_b_ms: 50.0
hyperprior: {sigma_g: [0.05, 1.0], ell_ms: [150.0, 1.0]}
hyper_starts: 4
S: 64
particles: 1024
g_max: 1.0
wavelet_ms: 128
ess_min_frac: 0.25
shift_K: 8
tau_range_ms: [200, 1500]
fine_dt_ms: 0.5
warp_dtau_ms: 4.0
smc_seed: 0
phase_step: 15.0
phase_half_width: 3
phase_max_extra: 6
smc_moves: 8
sigma_a_sensitivity_ms: [3.5, 14.0]
sensitivity_methods: [B3c-R, B3d-Sa, M2-Sa]
sensitivity_labels: [PHIE_DT]
sigma_a_note: '7 ms is inherited from P2r, not estimated as truth on F3. Both misspecification arms must be reported, never used to choose the best test result.'
training:
d_channels: 64
p_dropout: 0.05
lr: 0.005
grad_clip: 5.0
budgets: [125, 250, 500, 1000, 2000]
window_samples: 64
window_step: 2
softdtw: {gamma: 0.1, band: 8}
dilate: {alpha: 0.5, gamma: 0.1, band: 8}
methods:
main: [B2, B3a, B3b, B3c, B3c-R, B3d, B3d-Sa, B4a, B4b, B4c, B4d, M1, M2-Sa]
classical: [B0a, B0b, B1]
ablations: [M2-anchor-only, M2-no-anchors, M2-bulk, M2-lambda1, M2-S1, M2-S8, M2-S256, M2-fixed-sigma, M2-legacy-loss, M2-TCN, B3d-Sa-TCN, M2-LFM]
ablation_labels: [PHIE_DT]
posterior_mean_definition: 'B3d-Sa averages the forward maps t(tau) over retained particles and then inverts that mean, matching P2r. This is not the mean of inverse maps or the mean of porosity labels.'
no_anchor_note: 'Remove anchor conditioning AND anchor-based hyperparameter fitting; use the predeclared hyperprior medians. The sonic datum remains defined as in every method. This is an information-removal diagnostic, not a fresh proof of absolute-time identifiability.'
lfm_note: 'Append the 6 Hz low-pass mean calibrated label of the training wells as a time-only LFM input, shared at every target; no target logs or markers. Descriptive ablation, not horizon-guided inversion.'
fixed_sigma: 1.0
metrics:
f_c_hz: 6.0
sensitivity_f_c_hz: [5.0, 8.0]
levels: [50, 80, 90, 95]
units: 'porosity units (fraction multiplied by 100)'
reporting: 'Per-well first, then unweighted mean over wells; seed and combined ensembles separate. No p-values on correlated time samples.'
gate:
candidate: M2-Sa
point_competitors: [B3b, B3c, B3c-R]
competitor_selection: 'Per outer fold, lowest inner-validation total MSE averaged over seeds; never select by outer-test metrics.'
direction: 'Lower band RMSE than the selected point competitor in at least 3 of the 4 outer wells, primary label, calibrated reference, 15-member combined ensemble.'
coverage: 'Macro coverage80 within [0.75, 0.85] AND macro coverage90 within [0.85, 0.95] for that same ensemble. Report every well too.'
pass: 'direction AND coverage; never relax thresholds or replace failed calibration by better accuracy.'
same_posterior: 'M2-Sa versus B3d-Sa is reported separately; a success here does not replace either G-C condition.'
diagnostics:
loao: 'All four wells: linearized GP predictive z-scores, including pick noise, with hyperparameters fitted only on the other three wells. Explicitly an anchor-only Gaussian approximation, not SMC calibration.'
evaluation_posterior: 'Anchor-only nonlinear GP samples of the scoring well, prior fitted only on the other three wells; scoring sensitivity only, never fed back into training or checkpoint selection.'
volume:
method: M2-Sa
label: PHIE_DT
training: 'Four inner models each trained on three wells, five seeds (20 members). Budget is the nearest registered budget to the median of outer selected budgets for this method and seed, ties earliest.'
extent: full
batch_size: 256
edge: 'One-trace border is NaN because a complete 3x3 patch is unavailable; never silently clamp patches.'
fallback: 'Only if explicitly requested by --sections: one inline and one crossline through each well; recorded as reduced scope.'
interpretation: 'Descriptive prediction maps of sonic-derived porosity. No independent ground truth or geological-validity claim.'
runtime:
device: cuda:0
workers: 4
cpu_threads_per_worker: 2
resume: 'A completed job is reused only if protocol, code, data, training wells, method, label and seed fingerprints match.'

View File

@@ -0,0 +1,65 @@
{
"protocol_sha256": "7fdff4a1a4417da4322500548b7999657759fe5120c8a459b3d96ecb84a6b7b1",
"code_sha256": "c0befaa4442c50bcfe45352ba4b9c5a49ff2a4d1c2688cb85357ee828adbad95",
"environment": {
"python": "3.13.15",
"platform": "Linux",
"packages": {
"torch": "2.14.0+cu130",
"numpy": "2.5.4",
"scipy": "1.18.1",
"pandas": "3.0.6",
"matplotlib": "3.11.2",
"segyio": "1.9.14",
"lasio": "0.32",
"pylops": "2.5.0",
"numba": "0.67.0",
"scikit-learn": "1.9.1",
"PyYAML": "6.0.3",
"tabulate": "0.10.0",
"psutil": "7.2.2"
}
},
"protected_artifacts": {
"outputs:wavelets.npz": "b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64",
"outputs:p2/warp_prior_f3.json": "55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27"
},
"inputs": {
"repo:configs/d3_volve.yaml": "0d8613ab459292d3fcc3b60c43697bbbef222340daa00fde201b9d2cba5d1fd5",
"outputs:volve/volve_wells.npz": "ea496fac79c67a09543e5bc52dad200043bcb56eef7c371b948d0f04cc5a2c1d",
"outputs:volve/volve_wells_summary.json": "64e1278ad6a02cfac9f5b14df49bd6564e738fcaf0830f164652146b97e1fa4a",
"volve:Geophysical_Interpretations/Wells/Well_picks_Volve_v1.dat": "1c132bba09555915b62e23dc4475f790a304856d369d9d26cc76466cf7b77d3a",
"volve:Geophysical_Interpretations/Horizons/Horizons_TWT/Official_Horizons/Hugin_Fm_Top+ST10010ZC11_Near_190314+STAT+TIME.dat": "44e12e9c80fa59de95f6c6ea8ad76e3c7ebbefd6f6a8142966509f979666355d",
"volve:Well_technical_data/WellWellbore/15_9-F-1/15_9-F-1/Volve F_F-1_F-1_F-1_ACTUAL": "62ee61e501f4838e5eae6e4e012b75a8e8f74763594f5237ce3a65c8433c6d78",
"volve:Well_logs_pr_WELL/15_9-F-1/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_INPUT_1.LAS": "b7adf7938ff7c43d23d504370871ddb55304797ccfb6e6c886bf923118b2c789",
"volve:Well_logs_pr_WELL/15_9-F-1/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_OUTPUT_1.LAS": "53b060678accbae3afb3b40a8abe0881456fafbe4571cafeff80b1b2630c38c4",
"volve:Well_technical_data/WellWellbore/15_9-F-1/15_9-F-1 A/Volve F_F-1_F-1 A_F-1 A_ACTUAL": "7152f2dceb59c72a2d9ed05b71d8708ffde0de36145da75ec0af1f049528772f",
"volve:Well_logs_pr_WELL/15_9-F-1 A/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_INPUT_1.LAS": "494513a2f4448df524e6b0229697e26d2453640c37f8be2e45d3e7219a600602",
"volve:Well_logs_pr_WELL/15_9-F-1 A/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_OUTPUT_1.LAS": "4216236e9618ce348c80a1c2aef1cedde1bba9fa8c32dca0a6438a400439d845",
"volve:Well_technical_data/WellWellbore/15_9-F-1/15_9-F-1 B/Volve F_F-1_F-1 B_F-1 B_ACTUAL": "43d4739828f60a1e5e2fdbcb36601f082d3f375e4d087cfb8d093ee18765a3ed",
"volve:Well_logs_pr_WELL/15_9-F-1 B/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_INPUT_1.LAS": "ad9af11d31c9e116d686294ecb2c3aff7cd96ae7a03e633c70dcbcd7e0748468",
"volve:Well_logs_pr_WELL/15_9-F-1 B/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_OUTPUT_1.LAS": "6576989d3a8935f9f497ce05831b5dac396e653fbe7f7e4738de18bccf535645",
"volve:Well_technical_data/WellWellbore/15_9-F-11/15_9-F-11 A/Volve F_F-11_159-F-11 A_159-F-11 A_ACTUAL": "74bda9f018ef1714371de422c86c7ad3c63480d41c30f6cf3baa5b0588e59882",
"volve:Well_logs_pr_WELL/15_9-F-11 A/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_INPUT_1.LAS": "84ee266e0635a123ad51c96006835539b200fbc9fa6694d2b20a9067f1352870",
"volve:Well_logs_pr_WELL/15_9-F-11 A/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_OUTPUT_1.LAS": "680fe7522c635f23e034b9cc1a5b06593fc62f7c1c1d86e2565730ea785f94bf",
"volve:Well_technical_data/WellWellbore/15_9-F-11/15_9-F-11 T2/Volve F_F-11_159-F-11 T2_159-F-11 T2_ACTUAL": "2018eafc01148baf018e586109321c685f8676d94a902e2bef494e29622a1e04",
"volve:Well_logs_pr_WELL/15_9-F-11 T2/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_INPUT_1.LAS": "6ef9631e99d7da34b3d95356fa58dd6ecac230413723c320c30340dd7ed7979c",
"volve:Well_logs_pr_WELL/15_9-F-11 T2/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_OUTPUT_1.LAS": "d4c214e11d18a2aaa325dc8811d8d42ea77396f21f7d0bd9d022dfa08554a611",
"volve:Well_logs_pr_WELL/15_9-F-11 T2/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_1.ASC": "a58018419164ca3c9dbd9161cac40e590a8f89840b2a2da1be1622c76d9b673e",
"volve:Well_logs_pr_WELL/15_9-F-11 T2/08.VSP_VELOCITY/TZV_TIME_CHECKSHOT_3.ASC": "41c9dd5c5e0d8c7753bdc88f1ee50870a1a7dc67ecba73a16925f33ea1751ed1",
"volve:Well_technical_data/WellWellbore/15_9-F-12/15_9-F-12/Volve F_F-12_F-12_F-12_ACTUAL": "1e1e80a7656455b09b47aea0205f5f441aacb252c9fe09de2b48ba1279201afc",
"volve:Well_logs_pr_WELL/15_9-F-12/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_INPUT_1.LAS": "c38ffd606d7065e5c8904e126fd36ef736a4ce1149918ea88216bb3fe73db84e",
"volve:Well_logs_pr_WELL/15_9-F-12/05.PETROPHYSICAL INTERPRETATION/WLC_PETRO_COMPUTED_OUTPUT_1.LAS": "3633fd2e7797d80b7dc0b272276bc34124e06d275a129926f0afc57ce596a3dc"
},
"locked_utc": "2026-10-29T01:17:42.222240+00:00",
"segy_sha256": "f902e2bdaa277caf93a32e5f35eae653eb8b923138db0efc1e91918ef6757b2e",
"canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and source configuration; binary inputs exact",
"wells": [
"F-1",
"F-1 A",
"F-1 B",
"F-11 A",
"F-11 T2",
"F-12"
]
}

View File

@@ -0,0 +1 @@
7fdff4a1a4417da4322500548b7999657759fe5120c8a459b3d96ecb84a6b7b1 configs/protocol_volve.yaml

185
configs/protocol_volve.yaml Normal file
View File

@@ -0,0 +1,185 @@
# P4 Volve (plan D3, gate G-D): designed 28/10/2026 after P3 (G-C failed) and before any Volve PHIF metric,
# prediction or training run. DRAFT until `scripts/24_run_volve.py lock` on the run machine; after the lock this file
# is never edited (a change needs protocol_volve v2 with a recorded deviation).
version: 1
date: '2026-10-28'
prior_observation: >-
Before this file, Volve had only descriptive QC of DT, RHOB, picks, checkshots and seismic (plan §12 item 18).
The main window was chosen once from the label positions of all six wells, not their values. The design follows
protocol_f3 after its G-C failure was known: a post-P3 design for a second field, not a pre-registration made
before any field result.
data:
wells: [F-1, F-1 A, F-1 B, F-11 A, F-11 T2, F-12]
label: PHIF
dataset: outputs/volve/volve_wells.npz
source_config: configs/d3_volve.yaml
window_ms: [2400, 2900]
ext_window_ms: [2000, 3200]
min_label_samples: 8
references: [calibrated, anchors, NIVSP, OPTIMIZED]
primary_reference: calibrated
note: >-
PHIF is the CPI effective porosity, density-driven and not a function of DT (plan D3). It is used only where DT
is valid (16–37 samples of 4 ms per well). DT enters the time placement: vertical sonic integrated over TVD,
calibrated to the markers. NIVSP and OPTIMIZED exist only at F-11 T2.
missing_labels: >-
Never extrapolate labels. Each bank member keeps the samples where its own tie places the label run (member
support); a member with fewer than min_label_samples samples in a training well is an error. A scoring
reference with fewer than min_label_samples samples is listed, not scored.
split:
schemes: [lowo, slot]
outer: >-
lowo: every other well trains. slot: every well outside the slot group of the test well trains
(d3_volve.yaml p4.slot_groups: {F-1, F-1 A, F-1 B}, {F-11 A, F-11 T2}, {F-12}).
inner: >-
Leave one outer training well out, under both schemes. Under slot an inner validation well can share a slot
with inner training wells (deviation inner_lowo_under_slot).
inputs: >-
Training wells: calibrated reference path. Validation well v: blind key T_in. Outer test well u: blind key
T_out. A blind key K places the well path in time by the mean TVDSS–TWT relation of the wells K only; a
held-out well never supplies its picks, DT or logs to its own input.
seeds: [0, 1, 2, 3, 4]
selection: >-
Per scheme, outer fold, σ_a arm, method and seed: lowest mean original-scale validation MSE over the inner
wells, on their labelled samples of the primary reference; ties choose the earliest budget.
final: >-
Ensemble the inner models at the selected budget on the outer test input, then the five seeds (moment-matched
Gaussian mixture). No refit on the outer test well.
cache: >-
One trajectory per distinct inner training set, method, seed and σ_a arm (22 sets: 15 of four wells, 4 of
three, 3 of two). It predicts every input a fold can ask of it and is reused by every fold that trains on that
set; the other wells supply seismic only.
registration:
kernel: matern32
sigma_a_ms: 7.0
sigma_b_ms: 50.0
hyperprior: {sigma_g: [0.05, 1.0], ell_ms: [150.0, 1.0]}
hyper_starts: 4
S: 64
particles: 1024
g_max: 1.0
wavelet_ms: 128
tau_range_ms: [1800, 3400]
fine_dt_ms: 0.5
log_fine_dt_ms: 0.25
log_cutoff_frac: 0.8
warp_dtau_ms: 4.0
smc_seed: 0
phase_step: 15.0
phase_half_width: 3
phase_max_extra: 6
smc_moves: 8
sigma_a_sensitivity_ms: [3.5, 14.0]
sensitivity_methods: [B3c-R, B3d-Sa, M2-Sa]
sigma_a_note: >-
7 ms is inherited from P2r and protocol_f3, not estimated on Volve. Both misspecification arms are reported
if run, never used to choose a test result.
training_only: >-
Hyperparameters, statistical wavelet, phase and SMC posterior of a set use its training wells only. τ is the
vertical-sonic time through the first anchor in the DT range; anchors are markers in the DT range inside the
ext window.
training:
d_channels: 64
p_dropout: 0.05
lr: 0.005
grad_clip: 5.0
budgets: [125, 250, 500, 1000, 2000]
window_samples: 126
window_step: 2
loss: >-
ml_porosity.volve.losses.masked_bank_loss with one window, the whole main window (126 samples), and the label
support of each member; member log-likelihoods are compared at the mean member count, normalised by it, then
averaged over wells. Equal to the F3 bank loss with a 126-sample window when every sample is labelled.
λ = 1/τ_c from the pooled ACF of the high-passed B3b label runs of the training set.
methods:
main: [B3b, B3c, B3c-R, B3d-Sa, M2-Sa]
definitions: >-
B3b: sonic TDR stretched through the anchors. B3c: B3b plus smoothed local NCC shifts with the phase fitted on
anchor-prior samples. B3c-R: the same with the SMC-refined phase. B3d-Sa: posterior-mean tie. M2-Sa: RML on
S = 64 posterior label draws.
posterior_mean_definition: >-
B3d-Sa averages the forward maps t(τ) over retained particles and then inverts that mean, as in protocol_f3.
metrics:
primary: rmse
f_c_hz: 6.0
desc_band_min_samples: 16
best_shift_max_samples: 16
levels: [50, 80, 90, 95]
units: 'porosity units (fraction multiplied by 100)'
reporting: >-
Per well first, then the unweighted mean over wells, per scheme; seed and combined ensembles separate. Every
available reference is reported; the primary reference is never replaced by a better-scoring one. No p-values
on correlated time samples. Best-shift is a separate diagnostic table.
gate:
name: G-D
candidate: M2-Sa
point_competitors: [B3b, B3c, B3c-R]
same_posterior_method: B3d-Sa
competitor_selection: >-
Per scheme and outer fold: lowest inner-validation MSE averaged over seeds, primary σ_a arm; never outer-test
metrics.
report: >-
Per scheme, primary reference and σ_a arm, combined ensemble: the wells where M2-Sa RMSE is below the selected
competitor, macro RMSE of both, M2-Sa versus B3d-Sa, macro coverage80 and coverage90 of M2-Sa, and every well.
claim_rules:
min_improved_wells: 5
coverage_80: [0.75, 0.85]
coverage_90: [0.85, 0.95]
wording: >-
"Consistent improvement" only if at least 5 of 6 wells improve under both schemes (G-C's 3 of 4, scaled
and rounded up); "calibrated" only if both macro coverages lie in their bands under both schemes. Otherwise
the result is reported as it is (mixed, no improvement, under- or over-coverage). Neither wording overrides
the G-C failure on F3.
note: >-
G-D is descriptive: report results in either direction and scope claims by them (plan §6). No threshold here
changes the plan.
out_of_scope: >-
B0–B2, B3a, B3d, B4, B5, M1 and the F3 ablations (plan §6 scope cut 5), LOAO, the posterior-GP scoring reference,
the calibration-assisted setting and volume prediction.
deviations:
likelihood_window: >-
AI exists only over the logged interval, so the tie likelihood of a well (phase grid, SMC, γ) uses the ext
samples from its first to its last calibrated AI sample; F3 used the whole ext window. B3c and B3c-R keep the
full-window local shifts (windows without synthetic energy are dropped).
particle_validity: >-
A particle must invert over the main window only; F3 also required label support over the full window, which
16–37-sample labels cannot meet.
member_support: >-
Each member trains on its own label support. The first draft intersected the supports of all members and
methods; the CPU smoke (16 particles, S = 8, training wells only, no PHIF metric) cut F-11 A from 15–17 to 7
samples, below min_label_samples, and the intersection shrinks further with S = 64 draws and wider σ_a. The
intersection length is kept as a diagnostic (registration.csv, common_samples).
masked_loss: >-
Masked bank loss with a single 126-sample window instead of the F3 64-sample windows at step 2 (training.loss).
Label runs (16–37 samples) are shorter than an F3 window, so sliding windows would only cut a run at
arbitrary offsets and pick the RML member per offset; one window compares members over the whole run.
segment_lambda: >-
λ from label runs of any length (pooled lagged products) instead of the F3 full-window ACF; identical for runs
longer than the maximum lag.
primary_metric: >-
RMSE on labelled samples replaces the F3 band RMSE: label runs are shorter than one period at f_c = 6 Hz, so
the F3 band split is undefined; band_* (runs of at least 16 samples) is descriptive.
inner_lowo_under_slot: >-
Inner validation under slot is leave-one-well-out, not slot-blind (three slots leave too few groups); inner
validation can be optimistic there.
tau_range: '[1800, 3400] ms: the F3 margins of 200 ms around the ext window.'
main_window: 'Chosen from the label positions of all six wells (not values), once, before any training.'
lateral_path: >-
The 3×3 patch follows the deviated path placed in time by each TDR, so the blind TDR also moves the path
laterally (up to 76 m, F-1 A under slot). Recorded, not corrected.
scope: 'See out_of_scope; plan §6 scope cut 5 (Volve: best B3, B3d-S and M2 only).'
runtime:
device: cuda:1
workers: 8
cpu_threads_per_worker: 2
machine: >-
Linux GPU server (shared; cuda:1 chosen by free memory) via scripts/run_p4.sh, decided 29/10/2026 after the
benchmark stage (training wells only, no PHIF metric) instead of the Windows RTX 3060 workstation planned on
28/10; scripts/run_p4.ps1 stays the Windows driver. The lock binds code, inputs and environment. Worker count
and scheduling do not change results: every job seeds from its own settings.
order: >-
lock; register, train and summarize the primary arm; then register and train --arms sensitivity and
summarize --arms all. An arm not finished before writing is reported as not run.
resume: >-
A completed job is reused only if protocol, code, inputs, training wells, method, seed and σ_a fingerprints
and the artifact checksums match.

View File

@@ -1,25 +1,38 @@
{ {
"source": "outputs/ của luận văn, tải từ iCloud ngày 26/10/2026", "dataset": "Thesis outputs archived in outputs_thesis; source code in code_thesis",
"source": "Bộ output luận văn do người dùng bổ sung vào workspace ngày 27/10/2026",
"root": "outputs_thesis",
"verified_date": "2026-10-27",
"n_files": 7,
"total_bytes": 280112393,
"files": { "files": {
"f3_wells_dataset.npz": { "f3_wells_dataset.npz": {
"size_bytes": 439189, "size_bytes": 439189,
"sha256": "b768e09fa2fcbde6c9d991e8dea20ec02c01e910ccc5a105de038d0768324779", "sha256": "b768e09fa2fcbde6c9d991e8dea20ec02c01e910ccc5a105de038d0768324779"
"note": "prepare_data.py: 3 giếng, patch 3x3 tại IL/XL sai của luận văn, TWT tích phân DT không hiệu chỉnh"
}, },
"open_loop_patch_best.pt": { "open_loop_patch_best_v2.pt": {
"size_bytes": 380709, "size_bytes": 680434,
"sha256": "e1f27c1f1208114f03cef73429b2b582d0011a3e143d99fd552184ae857970e5", "sha256": "e039c941567f6966dc416a11285e236cd0f45bf11e41b7d5e081b28e5f75b4bb"
"note": "checkpoint bản v1 (GRU 1 tầng, không head_skip/bias), không nạp được vào CNNGRU v2"
}, },
"open_loop_patch_preds_F06-1.npz": { "open_loop_patch_preds_F06-1_v2.npz": {
"size_bytes": 2921, "size_bytes": 5316,
"sha256": "99bcba28e098ed689a407b1ed97dd555cbc86a89eccd92cca7be2887beea934a", "sha256": "7f99f3ca43f91267bba6eeb891ce59ff3644b25901a276505531da046a838146"
"note": "dự đoán F06-1 của checkpoint trên (tái tạo được, sai số 2e-7); nhãn min-max, test dịch lag -2" },
"plots/F06-1_overlay.png": {
"size_bytes": 94437,
"sha256": "7a2ccab9f2c40e1f8ba919d364ff084435dadad82a582a027fda8e7bd3b1d70f"
},
"plots/F06-1_overlay_scatter.png": {
"size_bytes": 48344,
"sha256": "a2febe82027e365ec82b01bbbb873823266fca8494516fada33d0f5ed3e175e5"
},
"porosity_comparison_F06-1.png": {
"size_bytes": 87965,
"sha256": "69bbfb83effdb684fb76fd77867b4d2625e8e8bc9a00c836640cc31623719599"
}, },
"porosity_volume_600_1100ms.npz": { "porosity_volume_600_1100ms.npz": {
"size_bytes": 0, "size_bytes": 278756708,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "sha256": "846b762d545933cd769e982e409422d38f28347802c24ca1df81e6438de9a36d"
"note": "RỖNG (0 byte): tải từ iCloud chưa xong"
} }
} }
} }

View File

@@ -3,7 +3,7 @@
Ngày lập: **25/10/2026**. Mục tiêu: phát triển luận văn CNN–GRU trên F3 thành một **bài phương pháp đạt chuẩn tạp chí Q2** (hoặc hội nghị CORE B). Bài phải đánh vào một research gap mà các công trình hiện có chưa chạm tới. Ngày lập: **25/10/2026**. Mục tiêu: phát triển luận văn CNN–GRU trên F3 thành một **bài phương pháp đạt chuẩn tạp chí Q2** (hoặc hội nghị CORE B). Bài phải đánh vào một research gap mà các công trình hiện có chưa chạm tới.
Đầu vào của kế hoạch: Đầu vào của kế hoạch:
- toàn bộ 8 script trong [`test 2/`](<test 2/>); - toàn bộ 8 script trong [`code_thesis/`](<../code_thesis/>);
- báo cáo [LeVietHoangLam_22BI13235.pdf](docs/LeVietHoangLam_22BI13235.pdf) (47 trang); - báo cáo [LeVietHoangLam_22BI13235.pdf](docs/LeVietHoangLam_22BI13235.pdf) (47 trang);
- survey [porosity-research-gap-survey.md](docs/research/porosity-research-gap-survey.md) (mã P01–P15 dưới đây là mã trong survey); - survey [porosity-research-gap-survey.md](docs/research/porosity-research-gap-survey.md) (mã P01–P15 dưới đây là mã trong survey);
- **kiểm tra trực tiếp dữ liệu F3** trong `F3_Demo_2023/`: LAS, marker TD, các mô hình TD của OpendTect và `.survey`; - **kiểm tra trực tiếp dữ liệu F3** trong `F3_Demo_2023/`: LAS, marker TD, các mô hình TD của OpendTect và `.survey`;
@@ -21,13 +21,13 @@ Quy ước nhãn:
| Mục | Quyết định | | Mục | Quyết định |
| --- | --- | | --- | --- |
| **Gap nhắm tới** | Trong học có giám sát seismic → porosity với ít giếng, *vị trí thời gian của nhãn* là một ước lượng (well tie). Sai số của nó có thể đạt cỡ nửa chu kỳ wavelet trở lên. Các công trình hiện có thuộc ba nhóm, không nhóm nào lấp gap: (i) giải tie như bước tiền xử lý và chỉ giữ một nghiệm điểm; (ii) mô hình hóa bất định của porosity nhưng giả định nhãn đã đăng ký đúng; (iii) dùng loss chịu dịch thời gian mà không có ràng buộc độc lập. **Chưa thấy công trình nào coi sai số đăng ký là biến ẩn, ràng buộc nó bằng anchor độc lập và vật lý, marginalize nó khi huấn luyện, rồi truyền nó sang bất định dự đoán và vào cách đánh giá.** | | **Gap nhắm tới** | Trong học có giám sát seismic → porosity với ít giếng, *vị trí thời gian của nhãn* là một ước lượng (well tie). Sai số của nó có thể đạt cỡ nửa chu kỳ wavelet trở lên. Các công trình hiện có thuộc ba nhóm, không nhóm nào lấp gap: (i) giải tie như bước tiền xử lý và chỉ giữ một nghiệm điểm; (ii) mô hình hóa bất định của porosity nhưng giả định nhãn đã đăng ký đúng; (iii) dùng loss chịu dịch thời gian mà không có ràng buộc độc lập. **Chưa thấy công trình nào coi sai số đăng ký là biến ẩn, ràng buộc nó bằng anchor độc lập và vật lý, marginalize nó khi huấn luyện, rồi truyền nó sang bất định dự đoán và vào cách đánh giá.** |
| **Tên làm việc** | *Registration-marginalized learning for sparse-well seismic porosity prediction*. Phương án khác: *When the well tie is uncertain: anchor-constrained registration marginalization for seismic porosity prediction*. | | **Tên làm việc** | **Từ 29/10/2026 (Pivot 1, mục 12 ý 22):** *Label registration error in sparse-well seismic property learning: theory, a registration-aware benchmark, and the limits of field validation*. Tên cũ (trước pivot): *Registration-marginalized learning for sparse-well seismic porosity prediction*; phương án khác: *When the well tie is uncertain: anchor-constrained registration marginalization for seismic porosity prediction*. |
| **Phương pháp (tên làm việc)** | **RML** (Registration-Marginalized Learning). Prior Gaussian process (GP) đặt trên hiệu chỉnh log-slowness, có điều kiện theo marker anchors. Thêm likelihood well tie vật lý. Huấn luyện bằng marginal likelihood (tempered). Phương pháp không phụ thuộc backbone. | | **Phương pháp (tên làm việc)** | **RML** (Registration-Marginalized Learning). Prior Gaussian process (GP) đặt trên hiệu chỉnh log-slowness, có điều kiện theo marker anchors. Thêm likelihood well tie vật lý. Huấn luyện bằng marginal likelihood (tempered). Phương pháp không phụ thuộc backbone. |
| **Đó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). **Pivot 1 (29/10/2026):** đóng góp viết lại thành C1′–C4′ theo `docs/research/pivot-theory-benchmark.md` mục 3.2; bản nháp đã viết theo khung này (mục 12 ý 24): C1′ lý thuyết (Mệnh đề 1 blur, 2 nhận dạng, 3 hai cấu trúc sai số classical/Berkson, 4 bank hiệu chỉnh với lợi ích quần thể bậc bốn, 5 coverage, 6 tham chiếu lệch, Hệ quả 4 tolerance); C2′ benchmark có warp thật, pre-register, kèm trục misspec S2 (chưa chạy); C3′ RML_λ làm họ baseline (Bổ đề 1–5), không phải phương pháp thắng; C4′ khả năng phát hiện ở giếng blind (T3) và phạm vi của field test (F3, Volve, Teapot). |
| **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** | **Chốt 29/10/2026:** *Computers & Geosciences*; dự phòng *Geophysical Prospecting* (mục 12 ý 22). Trước pivot: *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** | **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ỏ. | | **Thời gian** | **Chốt 29/10/2026: dời hạn sang thứ 7, 14/11/2026** (mức B của Pivot 1, mục 12 ý 22; lịch theo ngày ở mục 6.1). Ngưỡng và luật của mọi gate không đổi. Lịch nén trước đó (chốt 27/10/2026, hạn 31/10) đã chạy xong 4 cổng: G-A và G-B ngày 26/10, G-C cuối 28/10, G-D cuối 29/10; G-C và G-D không đạt tiêu chí claim (mục 12, ý 16 và 20). Lịch gốc 24 tuần (→ 02/05/2027) đã bỏ. |
| **Việc tuần này** | Mục 6 (lịch theo ngày) và mục 12. | | **Việc tuần này** | Mục 6.1 (lịch mức B theo ngày) và mục 12 ý 22. |
--- ---
@@ -37,22 +37,24 @@ Quy ước nhãn:
| # | Vấn đề | Vị trí | Hệ quả | | # | Vấn đề | Vị trí | Hệ quả |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| 1 | **Tọa độ giếng sai 5–11 km** [KT] | [prepare_data.py:17–21](<test 2/prepare_data.py>) | Mọi kết quả train/test đều lấy từ trace *không nằm tại giếng*; chi tiết ở mục 1.2a. | | 1 | **Tọa độ giếng sai 5–11 km** [KT] | [prepare_data.py:17–21](<../code_thesis/prepare_data.py>) | Mọi kết quả train/test đều lấy từ trace *không nằm tại giếng*; chi tiết ở mục 1.2a. |
| 2 | TWT tích phân từ DT với t = 0 tại mẫu LAS đầu tiên, không hiệu chỉnh drift [KT] | [prepare_data.py:110](<test 2/prepare_data.py>) | Lệch so với marker TD trong cửa sổ tới 14–66 ms tùy giếng, và biến thiên theo độ sâu (mục 1.2b). | | 2 | TWT tích phân từ DT với t = 0 tại mẫu LAS đầu tiên, không hiệu chỉnh drift [KT] | [prepare_data.py:110](<../code_thesis/prepare_data.py>) | Lệch so với marker TD trong cửa sổ tới 14–66 ms tùy giếng, và biến thiên theo độ sâu (mục 1.2b). |
| 3 | Lag ước lượng bằng tương quan giữa seismic amplitude và PHIE, cho phép đảo cực, trong ±64 ms | [train_open_patch_v2.py:74–108, 294–299](<test 2/train_open_patch_v2.py>) | Seismic tỷ lệ với reflectivity, không với porosity, nên lag chọn được có thể chỉ là tương quan ngẫu nhiên. | | 3 | Lag ước lượng bằng tương quan giữa seismic amplitude và PHIE, cho phép đảo cực, trong ±64 ms | [train_open_patch_v2.py:74–108, 294–299](<../code_thesis/train_open_patch_v2.py>) | Seismic tỷ lệ với reflectivity, không với porosity, nên lag chọn được có thể chỉ là tương quan ngẫu nhiên. |
| 4 | Giếng validation (F02-1) cũng là giếng train | [train_open_patch_v2.py:306–309](<test 2/train_open_patch_v2.py>) | Checkpoint "best" thực chất được chọn trên dữ liệu train. | | 4 | Giếng validation (F02-1) cũng là giếng train | [train_open_patch_v2.py:306–309](<../code_thesis/train_open_patch_v2.py>) | Checkpoint "best" thực chất được chọn trên dữ liệu train. |
| 5 | Chỉ có **2 chuỗi huấn luyện** (`X_train` có shape (2, 9, 126)); PDF mục 3.2.3 ghi "252 samples" | như trên; PDF tr. 23 | Mô tả trong bài không đúng; số "mẫu" độc lập thực tế là 2. | | 5 | Chỉ có **2 chuỗi huấn luyện** (`X_train` có shape (2, 9, 126)); PDF mục 3.2.3 ghi "252 samples" | như trên; PDF tr. 23 | Mô tả trong bài không đúng; số "mẫu" độc lập thực tế là 2. |
| 6 | Volume được giải chuẩn theo min–max [0, 1] trong khi train dùng Z-score | [predict_porosity_volume.py:75–89, 139](<test 2/predict_porosity_volume.py>), [plot_pred.py:33](<test 2/plot_pred.py>), [plot_porosity_maps.py:13](<test 2/plot_porosity_maps.py>) | Bản đồ porosity trong luận văn sai thang đo. | | 6 | Volume được giải chuẩn theo min–max [0, 1] trong khi train dùng Z-score | [predict_porosity_volume.py:75–89, 139](<../code_thesis/predict_porosity_volume.py>), [plot_pred.py:33](<../code_thesis/plot_pred.py>), [plot_porosity_maps.py:13](<../code_thesis/plot_porosity_maps.py>) | Bản đồ porosity trong luận văn sai thang đo. |
| 7 | L_shape ≈ 2·L_PCC − 2/L | [train_open_patch_v2.py:200–217](<test 2/train_open_patch_v2.py>) | Gọi là "6 loss" nhưng chỉ có 5 ràng buộc độc lập (survey mục 4.2). | | 7 | L_shape ≈ 2·L_PCC − 2/L | [train_open_patch_v2.py:200–217](<../code_thesis/train_open_patch_v2.py>) | Gọi là "6 loss" nhưng chỉ có 5 ràng buộc độc lập (survey mục 4.2). |
| 8 | Log bước 0.15 m bị lấy mẫu xuống 4 ms bằng nội suy điểm, không lọc chống alias | [prepare_data.py:203–204, 318](<test 2/prepare_data.py>) | Nhãn bị alias. | | 8 | Log bước 0.15 m bị lấy mẫu xuống 4 ms bằng nội suy điểm, không lọc chống alias | [prepare_data.py:203–204, 318](<../code_thesis/prepare_data.py>) | Nhãn bị alias. |
| 9 | Clip [0, 0.4] che đi dữ liệu bất thường của F02-1 (PHIE lên tới 0.709) | [train_open_patch_v2.py:278–280](<test 2/train_open_patch_v2.py>) | Che một vấn đề định nghĩa nhãn (mục 1.2d). | | 9 | Clip [0, 0.4] che đi dữ liệu bất thường của F02-1 (PHIE lên tới 0.709) | [train_open_patch_v2.py:278–280](<../code_thesis/train_open_patch_v2.py>) | Che một vấn đề định nghĩa nhãn (mục 1.2d). |
| 10 | **MSE = 0.015 (thang thật) tương ứng R² ≈ −9.8 trên F06-1** [KT] | PDF tr. 30, 35 | Nhãn dựng theo đúng cách của code có var(PHIE) trong cửa sổ = 0.00139 (std 0.037), nên MSE 0.015 *tệ hơn dự đoán bằng hằng số khoảng 10 lần*. Phát biểu "low MSE" là sai. | | 10 | **MSE = 0.015 (thang thật) tương ứng R² ≈ −9.8 trên F06-1** [KT] | PDF tr. 30, 35 | Nhãn dựng theo đúng cách của code có var(PHIE) trong cửa sổ = 0.00139 (std 0.037), nên MSE 0.015 *tệ hơn dự đoán bằng hằng số khoảng 10 lần*. Phát biểu "low MSE" là sai. |
| 11 | So sánh với Prabowo dùng MSE 0.020 trong khi bảng gốc ghi 1.020 | PDF tr. 3, 35 | Survey mục 4.1. | | 11 | So sánh với Prabowo dùng MSE 0.020 trong khi bảng gốc ghi 1.020 | PDF tr. 3, 35 | Survey mục 4.1. |
| 12 | Trục thời gian của hình bị ngược (`origin="lower"`); `read_npz_output.py` đọc key `times_ms` không tồn tại; gọi `plt.show()` trước `savefig` | [plot_pred.py:75–76](<test 2/plot_pred.py>), [read_npz_output.py:16, 34–36](<test 2/read_npz_output.py>) | Hình trong luận văn cần vẽ lại. | | 12 | Trục thời gian của hình bị ngược (`origin="lower"`); `read_npz_output.py` đọc key `times_ms` không tồn tại; gọi `plt.show()` trước `savefig` | [plot_pred.py:75–76](<../code_thesis/plot_pred.py>), [read_npz_output.py:16, 34–36](<../code_thesis/read_npz_output.py>) | Hình trong luận văn cần vẽ lại. |
| 13 | Đường dẫn Windows tuyệt đối, chỉ 1 seed, không có git; checkpoint `outputs/open_loop_patch_best.pt` không khớp tên `_v2.pt` mà script suy luận đọc | toàn bộ | Không tái lập được. | | 13 | Đường dẫn Windows tuyệt đối, chỉ 1 seed; bộ `outputs_thesis/` hiện đã có checkpoint `_v2.pt` (27/10/2026) | toàn bộ; [audit output](research/thesis-output-audit.md) | Cần điều chỉnh đường dẫn để chạy lại; chưa kiểm chứng checkpoint bằng suy luận. |
**Kết luận:** PCC 0.34 và MSE 0.015 *không phải* mốc so sánh hợp lệ. Phải dựng lại baseline (pha P1). **Kết luận:** PCC 0.34 và MSE 0.015 *không phải* mốc so sánh hợp lệ. Phải dựng lại baseline (pha P1).
**Cập nhật output ngày 27/10/2026 [KT]:** `outputs_thesis/` có 7 artifact, gồm checkpoint và dự đoán v2 cùng volume `(651, 951, 126)` đọc được (278756708 byte). Metric tính trực tiếp trên 126 cặp dự đoán F06-1, không dịch thời gian: MSE = 0.0018714971, PCC = 0.02947452, R² = −0.3460; best-shift +16 mẫu chỉ cho PCC = 0.1068. Bộ này thay thế nhận định trước về thiếu v2 và volume rỗng. Dataset giữ nguyên SHA-256 nên audit geometry/TWT vẫn áp dụng. Chưa chạy lại checkpoint do môi trường hiện chưa có Python/PyTorch. Chi tiết: [audit output](research/thesis-output-audit.md), [manifest](../data_manifest/thesis_outputs.json).
### 1.2 Năm sự thật về dữ liệu định hình bài báo ### 1.2 Năm sự thật về dữ liệu định hình bài báo
**(a) Geometry [KT].** Vị trí thật tính từ phép biến đổi bin → XY trong `.survey`. Phép biến đổi đã được kiểm lại khớp với Set Point.1 (99/104 → 600938.13, 6073394.5). Tọa độ XY lấy từ header LAS và file track. Cả bốn giếng đều thẳng đứng. **(a) Geometry [KT].** Vị trí thật tính từ phép biến đổi bin → XY trong `.survey`. Phép biến đổi đã được kiểm lại khớp với Set Point.1 (99/104 → 600938.13, 6073394.5). Tọa độ XY lấy từ header LAS và file track. Cả bốn giếng đều thẳng đứng.
@@ -126,7 +128,7 @@ Hệ quả:
**Tài nguyên khác [KT]:** **Tài nguyên khác [KT]:**
- 7 horizon (Shallow, FS8, FS7, Truncation, Top-Foresets, FS6, MFS4) và FaultA. Đã tải đủ bản dataset đầy đủ ngày 26/10/2026, không còn placeholder. - 7 horizon (Shallow, FS8, FS7, Truncation, Top-Foresets, FS6, MFS4) và FaultA. Đã tải đủ bản dataset đầy đủ ngày 26/10/2026, không còn placeholder.
- Log GR, AI, AI_rel ở cả 4 giếng. - Log GR, AI, AI_rel ở cả 4 giếng.
- `F3_entire.segy` (1.29 GB) đã có trên đĩa (tải lại toàn bộ F3 Demo 2023, 9.43 GB, ngày 26/10/2026 [KT]: IL 100–750, XL 300–1250, 462 mẫu 4 ms, float32 IEEE). Thư mục `outputs/` vẫn chưa có. - `F3_entire.segy` (1.29 GB) đã có trên đĩa (tải lại toàn bộ F3 Demo 2023, 9.43 GB, ngày 26/10/2026 [KT]: IL 100–750, XL 300–1250, 462 mẫu 4 ms, float32 IEEE). Bộ output luận văn đã có trong `outputs_thesis/` (kiểm tra ngày 27/10/2026); `outputs/` dành cho kết quả pipeline nghiên cứu.
### 1.3 Ba hệ quả cho bài báo ### 1.3 Ba hệ quả cho bài báo
@@ -152,7 +154,7 @@ Ba nhóm literature đang tách rời nhau:
### 2.2 Bản đồ định vị ### 2.2 Bản đồ định vị
Bảng dựa trên mức đọc F/A của survey. Toàn văn đã có trong `refs/` cho P01–P03, P06, P08, P10–P15, Tschannen, Buland & Omre, Wu & Caumon, AI Review 2024 và các bài phương pháp ở mục 11. **P04, P05, P07, P09 chỉ có abstract** (không tải được toàn văn, quyết định bỏ qua), nên các ô của chúng là suy ra từ abstract và phải đọc lại trước khi nộp [XM]. Bảng dựa trên mức đọc F/A của survey. Toàn văn đã có trong `refs/` cho P01–P03, P06, P08, P10–P15, Tschannen, Buland & Omre, Wu & Caumon, AI Review 2024 và các bài phương pháp ở mục 11. **P04, P05, P07, P09 chỉ có abstract** (không tải được toàn văn, quyết định bỏ qua), nên các ô của chúng là suy ra từ abstract. **Ngày 28/10/2026:** xác nhận lần cuối là không lấy được toàn văn; mọi chỗ trích bốn bài này trong bản thảo đã được đối chiếu với abstract và đều khớp (P05: bất định nằm trên trọng số mạng, không có tie, nên ô "bất định tie → huấn luyện" = – là công bằng; P07: không có bất định tie; P09 đối chiếu theo ghi chép survey 23/10 vì OpenAlex, Crossref và Semantic Scholar không còn abstract). Giữ chú thích "assessed from the abstract only"; mục [XM] này đóng. P03 (Xu et al. 2024) **có** toàn văn (`refs/xu2024sts.pdf`, 16 trang) nên vẫn được tính là đã đọc toàn văn.
| Công trình | DL dự đoán thuộc tính | Tie tự động | Bất định tie | Bất định tie → huấn luyện | UQ có kiểm chứng calibration | Đánh giá có xét registration | | Công trình | DL dự đoán thuộc tính | Tie tự động | Bất định tie | Bất định tie → huấn luyện | UQ có kiểm chứng calibration | Đánh giá có xét registration |
| --- | :-: | :-: | :-: | :-: | :-: | :-: | | --- | :-: | :-: | :-: | :-: | :-: | :-: |
@@ -166,6 +168,8 @@ Bảng dựa trên mức đọc F/A của survey. Toàn văn đã có trong `ref
| Tschannen et al. 2022 | – | ✓ | một phần (pha wavelet; shift chỉ trong biên) | – | – | – | | Tschannen et al. 2022 | – | ✓ | một phần (pha wavelet; shift chỉ trong biên) | – | – | – |
| Wu & Caumon 2017 | – | ✓ (nhiều giếng) | – | – | – | – | | Wu & Caumon 2017 | – | ✓ (nhiều giếng) | – | – | – | – |
| Buland & Omre 2003 | – (Bayes cổ điển) | ✓ (wavelet + mistie marker) | ✓ (posterior shift từng marker) | – (không có mô hình học) | – | – | | Buland & Omre 2003 | – (Bayes cổ điển) | ✓ (wavelet + mistie marker) | ✓ (posterior shift từng marker) | – (không có mô hình học) | – | – |
| AWSM, Lim et al. IMAGE 2025 (abstract) | – | ✓ (PT-MCMC time–depth + wavelet) | ✓ | – (wavelet sang AVA inversion) | – | – |
| Guillon et al. 2020 (abstract) | segmentation fault/horizon | – | – | – | – | dung sai không gian trong metric |
| Soft-DTW / DILATE | (chuỗi chung) | căn chỉnh mềm | – | không anchor/vật lý | – | – | | Soft-DTW / DILATE | (chuỗi chung) | căn chỉnh mềm | – | không anchor/vật lý | – | – |
| Luận văn v2 | ✓ | lag PCC thô | – | hard-min, không prior | – | best-shift chọn trên test | | Luận văn v2 | ✓ | lag PCC thô | – | hard-min, không prior | – | best-shift chọn trên test |
| **Bài đề xuất** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | **Bài đề xuất** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
@@ -210,9 +214,9 @@ Với sai số tới 14–66 ms (tùy giếng) đo được ở mục 1.2, phầ
**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):** **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/gunning2006waveletextractor.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.
4. Quét SEG/EAGE expanded abstracts 2024–2026 với các từ khóa "well tie uncertainty", "misalignment", "label noise", "porosity", "impedance". 4. ~~Quét SEG/EAGE expanded abstracts 2024–2026 với các từ khóa "well tie uncertainty", "misalignment", "label noise", "porosity", "impedance".~~ **Đã quét ngày 28/10/2026.** DOI kiểm bằng Crossref; abstract đọc qua OpenAlex vì EarthDoc và SEG Library chặn truy cập tự động; không có toàn văn bài nào. Đã thêm 10 mục vào `paper/refs.bib` và §2 của bản thảo (xem mục 11). Kết luận: **không bài nào đưa posterior của tie vào huấn luyện mô hình dự đoán thuộc tính**, nên câu "to our knowledge, in the reviewed literature…" vẫn giữ. Bài gần nhất là AWSM (Lim, Van Wagoner & Cardona, IMAGE 2025): PT-MCMC đồng thời cho tham số time–depth và wavelet, có bất định; wavelet được đưa sang AVO/AVA inversion, còn bất định time–depth thì abstract không cho thấy được dùng tiếp. Hai chi tiết trong kết quả quét ban đầu không kiểm chứng được trong abstract nên **không đưa vào bài**: "44 giếng" của AWSM, và câu nói rằng Rizzuti et al. 2025 coi việc tích hợp well log và wavelet vào UQ là việc còn lại. Còn mở: abstract IMAGE 2026 của Palavicini Gurria et al. (well tie và seismic inversion làm QC định lượng; có trong chương trình chính thức nhưng chưa lấy được nội dung); DOI và trang của Quesada et al. 2024. Bỏ qua: Raeisdana & MacBeth (EAGE 2026, time shift 4D, khác bài toán) và Lim (IMAGE 2026, AVA Zoeppritz + bootstrap, đã có BootNet đại diện).
5. Đặt Google Scholar alert cho các cụm trên. 5. Đặt Google Scholar alert cho các cụm trên.
**Quy tắc viết:** không dùng "first". Dùng "to our knowledge, in the reviewed literature…". **Quy tắc viết:** không dùng "first". Dùng "to our knowledge, in the reviewed literature…".
@@ -333,7 +337,7 @@ Bảng này biến ablation thành một con đường đi từ v2 tới RML.
| --- | --- | --- | --- | | --- | --- | --- | --- |
| **D1** | F3, 4 giếng, LOWO 4 fold | Field chính | Cửa sổ chính 600–1100 ms, thêm cửa sổ mở rộng để kiểm tra robustness. **Quyết định D-1** (mục 12): nhãn chính là PHIE_DT hài hòa (−0.2018 + 0.0011·DT cho cả 4 giếng), nhãn gốc là phụ. Kiểm kê [NLOG](https://www.nlog.nl) ngày 26/10/2026 [KT, `docs/research/f3-nlog-inventory.xlsx`]: 38 borehole/sidetrack trong footprint, 7 hồ sơ có TD số. Hai giếng ngoài bộ demo có DT + RHOB đo + TD số phủ cửa sổ: **F03-03** (DT/RHOB 500–3920 m MD, TWT 0–3165 ms) và **F03-06** (DT/RHOB 501–3701 m MD, TWT 0–3044 ms). F03-05-S1 không dùng được vì TD số bắt đầu ở 1295 ms. NLOG có RHOB đo cho F03-4 (473–3155 m), có thể làm nhãn thay thế. Điểm cần làm tiếp: NLOG không có PHIE, nhãn phải tự tính từ RHOB đo; DT của NLOG tính bằng µs/ft; chưa QC washout; file TZ có thể là TD đã xử lý chứ không phải checkshot độc lập. **D-1 chốt ngày 26/10/2026** (mục 1.2d hệ quả 6). Nhãn chính là PHIE_DT, báo cáo rõ là porosity dẫn xuất từ sonic. PHIE gốc là nhãn phụ, chỉ để so với luận văn. φ_D từ RHOB đo chỉ dùng để đánh giá độ nhạy ở F02-1 và F03-4, không dùng để train. Giữ 4 giếng; hoãn mở rộng lên 6 giếng vì F03-03 và F03-06 chưa có marker để làm anchor TD, file TZ có thể là TD đã xử lý, và F03-06 có DRHO cao. Phần kiểm tra độc lập với sonic giao cho D3 (PHIF của Volve). Protocol v2 đã khoá không đổi, vì nó đã dùng PHIE_DT chính và PHIE phụ. | | **D1** | F3, 4 giếng, LOWO 4 fold | Field chính | Cửa sổ chính 600–1100 ms, thêm cửa sổ mở rộng để kiểm tra robustness. **Quyết định D-1** (mục 12): nhãn chính là PHIE_DT hài hòa (−0.2018 + 0.0011·DT cho cả 4 giếng), nhãn gốc là phụ. Kiểm kê [NLOG](https://www.nlog.nl) ngày 26/10/2026 [KT, `docs/research/f3-nlog-inventory.xlsx`]: 38 borehole/sidetrack trong footprint, 7 hồ sơ có TD số. Hai giếng ngoài bộ demo có DT + RHOB đo + TD số phủ cửa sổ: **F03-03** (DT/RHOB 500–3920 m MD, TWT 0–3165 ms) và **F03-06** (DT/RHOB 501–3701 m MD, TWT 0–3044 ms). F03-05-S1 không dùng được vì TD số bắt đầu ở 1295 ms. NLOG có RHOB đo cho F03-4 (473–3155 m), có thể làm nhãn thay thế. Điểm cần làm tiếp: NLOG không có PHIE, nhãn phải tự tính từ RHOB đo; DT của NLOG tính bằng µs/ft; chưa QC washout; file TZ có thể là TD đã xử lý chứ không phải checkshot độc lập. **D-1 chốt ngày 26/10/2026** (mục 1.2d hệ quả 6). Nhãn chính là PHIE_DT, báo cáo rõ là porosity dẫn xuất từ sonic. PHIE gốc là nhãn phụ, chỉ để so với luận văn. φ_D từ RHOB đo chỉ dùng để đánh giá độ nhạy ở F02-1 và F03-4, không dùng để train. Giữ 4 giếng; hoãn mở rộng lên 6 giếng vì F03-03 và F03-06 chưa có marker để làm anchor TD, file TZ có thể là TD đã xử lý, và F03-06 có DRHO cao. Phần kiểm tra độc lập với sonic giao cho D3 (PHIF của Volve). Protocol v2 đã khoá không đổi, vì nó đã dùng PHIE_DT chính và PHIE phụ. |
| **D2** | Synthetic hiệu chỉnh theo F3 | Biết ground truth registration; tạo phase diagram | Earth model dựng từ 7 horizon + FaultA. Thuộc tính theo lớp lấy từ thống kê log cộng Gaussian random field. Chuỗi rock physics F3 chính xác. Wavelet ước lượng từ F3, noise SNR {∞, 20, 10, 5} dB. Drift g lấy từ GP fit trên anchor F3, nhân hệ số ×{0, 0.5, 1, 2}, cộng các họ drift sai mô hình (bước nhảy tại Truncation, jitter tần số cao). Anchor đặt tại giao horizon–giếng và có pick noise. Giả lập 2/4/8/16 pseudo-well. Split theo realization và theo khối không gian. | | **D2** | Synthetic hiệu chỉnh theo F3 | Biết ground truth registration; tạo phase diagram | Earth model dựng từ 7 horizon + FaultA. Thuộc tính theo lớp lấy từ thống kê log cộng Gaussian random field. Chuỗi rock physics F3 chính xác. Wavelet ước lượng từ F3, noise SNR {∞, 20, 10, 5} dB. Drift g lấy từ GP fit trên anchor F3, nhân hệ số ×{0, 0.5, 1, 2}, cộng các họ drift sai mô hình (bước nhảy tại Truncation, jitter tần số cao). Anchor đặt tại giao horizon–giếng và có pick noise. Giả lập 2/4/8/16 pseudo-well. Split theo realization và theo khối không gian. |
| **D3** | Field thứ hai: [Volve, Equinor](https://www.equinor.com/energy/volve-data-sharing) | Kiểm tra transfer; porosity tính độc lập với sonic (density–neutron, CPI) phá vỡ cấu trúc PHIE = f(DT) của F3 | Kiểm kê bản Volve cục bộ ngày 26/10/2026 [KT]: giấy phép CC BY-NC-SA 4.0 (không thương mại, phải ghi nguồn, chia sẻ lại cùng giấy phép). 9 giếng có PHIF đã tính (F-1, 1A, 1B, 1C, 11A, 11B, 11T2, 12, 15D), chỉ ở đoạn reservoir khoảng 3100–4750 m MD. Chỉ **6 giếng** có đủ DT + RHOB + NPHI + PHIF (F-1, 1A, 1B, 11A, 11T2, 12); F-1C, 11B, 15D không có DT. Checkshot/VSP chỉ có ở **F-11 T2 và F-15 A**. **Không có cube post-stack** trong bản này (các SEGY là VSP), phải tải riêng. Tọa độ giếng chưa lấy (LAS để trống; cần EDM/Compass). PHIF của Volve phụ thuộc density, không phụ thuộc sonic: corr(PHIF, RHOB) từ −0.92 đến −0.99, R² theo RHOB + NPHI từ 0.84 đến 0.98, thêm DT chỉ nâng thêm tối đa 0.009. Giả thuyết phá vỡ cấu trúc PHIE = f(DT) được xác nhận. Điểm vướng: điều kiện "≥ 6 giếng" cần thêm time-depth cho 4 giếng chưa có checkshot, và cần cube seismic. *Cập nhật 26/10/2026: cả hai đã gỡ (well picks cho marker TWT ở cả 10 giếng; cube ST10010 đã tải và kiểm tra, xem mục 12 ý 7).* Chỉ lấy ROI quanh ≥ 6 giếng. Dự phòng: Penobscot (2 giếng, yếu) hoặc NLOG. | | **D3** | Field thứ hai: [Volve, Equinor](https://www.equinor.com/energy/volve-data-sharing) | Kiểm tra transfer; porosity tính độc lập với sonic (density–neutron, CPI) phá vỡ cấu trúc PHIE = f(DT) của F3 | Kiểm kê bản Volve cục bộ ngày 26/10/2026 [KT]: giấy phép CC BY-NC-SA 4.0 (không thương mại, phải ghi nguồn, chia sẻ lại cùng giấy phép). 9 giếng có PHIF đã tính (F-1, 1A, 1B, 1C, 11A, 11B, 11T2, 12, 15D), chỉ ở đoạn reservoir khoảng 3100–4750 m MD. Chỉ **6 giếng** có đủ DT + RHOB + NPHI + PHIF (F-1, 1A, 1B, 11A, 11T2, 12); F-1C, 11B, 15D không có DT. Checkshot/VSP chỉ có ở **F-11 T2 và F-15 A**. **Không có cube post-stack** trong bản này (các SEGY là VSP), phải tải riêng. Tọa độ giếng chưa lấy (LAS để trống; cần EDM/Compass). *Cập nhật 28/10/2026: trajectory lấy từ survey Compass, xem mục 12 ý 18.* PHIF của Volve phụ thuộc density, không phụ thuộc sonic: corr(PHIF, RHOB) từ −0.92 đến −0.99, R² theo RHOB + NPHI từ 0.84 đến 0.98, thêm DT chỉ nâng thêm tối đa 0.009. Giả thuyết phá vỡ cấu trúc PHIE = f(DT) được xác nhận. Điểm vướng: điều kiện "≥ 6 giếng" cần thêm time-depth cho 4 giếng chưa có checkshot, và cần cube seismic. *Cập nhật 26/10/2026: cả hai đã gỡ (well picks cho marker TWT ở cả 10 giếng; cube ST10010 đã tải và kiểm tra, xem mục 12 ý 7).* Chỉ lấy ROI quanh ≥ 6 giếng. Dự phòng: Penobscot (2 giếng, yếu) hoặc NLOG. |
### 5.2 Giao thức blind well và tham chiếu đánh giá ### 5.2 Giao thức blind well và tham chiếu đánh giá
@@ -399,7 +403,7 @@ Lưới thí nghiệm:
--- ---
## 6. Lộ trình với cổng go/no-go (lịch nén: xong trước T7 31/10/2026) ## 6. Lộ trình với cổng go/no-go (hạn hiện tại: T7 14/11/2026; lịch nén 31/10 trước đó)
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. 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.
@@ -408,17 +412,36 @@ Chốt ngày 27/10/2026: toàn bộ bài, gồm cả review nội bộ và bản
| **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 | — | | **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** | 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. | | **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** | 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). | | **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** | 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 | | **P3 F3 field** | T4 28/10 | Nested LOWO đầy đủ; ensemble; calibration; ablation; leave-one-anchor-out; volume kèm bất định. M3 hoãn, không đưa vào bài | Bảng và hình F3 | **G-C (cuối 28/10):** chiều cải thiện nhất quán với synthetic ở ≥ 3/4 giếng; coverage 80/90% nằm trong ±5% so với mức danh nghĩa. Kết quả: không đạt (1/4 giếng; coverage 52,38/60,91%; mục 12, ý 16) |
| **P4 Field 2** | T4 28/10 dựng pipeline (song song P3); T5 29/10 chạy | 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ả | | **P4 Field 2** | T4 28/10 dựng pipeline (song song P3); T5 29/10 chạy (xong 02:21 UTC trên server Linux) | ROI Volve, tie, pipeline; chạy tập con B1, B3 tốt nhất, B4, B5, M2. Đã áp dụng mục cắt phạm vi 5: B3b, B3c, B3c-R (ứng viên B3), B3d-Sa, M2-Sa | Bảng field 2 (`outputs/p4/summary/`; paper mục 6.5) | **G-D (cuối 29/10):** báo cáo kết quả bất kể chiều nào; giới hạn phạm vi claim theo kết quả. Kết quả: M2-Sa tốt hơn B3 chọn ở 2/6 (lowo) và 3/6 (slot) giếng; coverage90 0,48/0,47; không phương pháp nào có kỹ năng ở giếng blind. Không claim cải thiện, hiệu chuẩn hay transfer (mục 12, ý 20–21) |
| **P5 Viết** | Khung bài và mục audit, lý thuyết, D2 viết dần từ 27/10; viết chính T5 29/10 – T6 30/10 | 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ộ | | **P5 Viết** | Khung bài và mục audit, lý thuyết, D2 viết dần từ 27/10; viết chính T5 29/10 – T6 30/10; từ 29/10 theo lịch mức B (mục 6.1) | Bản nháp, hình, phụ lục chứng minh, gói tái lập (code + config + dữ liệu dẫn xuất theo CC BY-SA 3.0) | Draft v1 (cuối 29/10), v2 (cuối 30/10). Ngày 29/10: đã viết các mục Volve; trục bài đặt vào lý thuyết và benchmark synthetic, hai field là kiểm tra giới hạn phạm vi (mục 12, ý 21). **Mức A viết xong sớm ngày 29/10** (mục 6.1, mục 12 ý 24): bản nháp theo khung Pivot 1, 55 trang, biên dịch sạch; còn TODO đỏ cho S1–S8, T2, khai báo của tác giả. Rủi ro độ dài: thân bài khoảng 14.750 từ so với giới hạn khoảng 5.500 từ của C&G (chưa kiểm trên trang chính thức); người dùng bỏ lượt rút gọn (mục 12 ý 25) | Review nội bộ |
| **P6 Review + nộp** | T7 31/10 | GVHD và một người làm địa vật lý đọc; kiểm tra novelty lần cuối (quét SEG/EAGE, tra quartile); preprint (EarthArXiv/ESSOAr) nếu venue cho phép; nộp | Bản nộp | — | | **P6 Review + nộp** | T7 31/10 → dời sang T4 11/11 – T7 14/11 (mục 6.1) | GVHD và một người làm địa vật lý đọc; kiểm tra novelty lần cuối (quét SEG/EAGE, tra quartile); preprint (EarthArXiv/ESSOAr) nếu venue cho phép; nộp | Bản nộp | — |
**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): ### 6.1 Lịch mức B sau Pivot 1 (chốt 29/10/2026; hạn T7 14/11/2026)
Pivot 1 kích hoạt ngày 29/10/2026 (mục 12 ý 22): bài chuyển thành lý thuyết + benchmark synthetic, hai field case là phạm vi. Thiết kế đầy đủ ở `docs/research/pivot-theory-benchmark.md` (mục 4.2 và 6). Mọi thí nghiệm mới chạy dưới `configs/protocol_bench.yaml` khóa trước lần chạy đầu; không đụng `protocol_p2r`, `protocol_f3`, `protocol_volve` và kết quả của chúng.
| Ngày | Việc | Đầu ra |
| --- | --- | --- |
| T5 29/10 | Chốt 5 quyết định; cập nhật plan, AGENTS, report; khảo sát dataset field public (`docs/research/field-dataset-survey.md`) | Quyết định ghi ở mục 12 ý 22 |
| T6 30/10 – T7 31/10 | Mức A: viết lại abstract, intro, contributions, discussion, conclusion; T1, T4, T8 thành mệnh đề; T4 từ `outputs/p2r/train/*/cells/*.npz`; T3 (giải tích + mô phỏng trên dự đoán P2r); T10 related work. **Xong sớm ngày T5 29/10** (mục 12 ý 24). Việc còn lại của hai ngày này: trích dẫn dataset F3 và Volve; còn lại là dự phòng. Lượt rút gọn độ dài cho venue đã bỏ theo quyết định của người dùng ngày 29/10 (mục 12 ý 25) | Draft khung mới (xong) |
| CN 1/11 | T2 exploratory (khai báo trước ở `docs/research/t2-mechanism.md`): responsibility-weighted warp error; bank nhiễu đối chứng; tách ô đa mode; kiểm Berkson hay classical (hiệp phương sai offset); B3d-Sa ở số vòng lặp của Oracle | Phân tích cơ chế: còn lợi ích nào vượt hiệu chỉnh Berkson không |
| T2 2/11 – T3 3/11 | Sửa generator cho S2 (misspec rock physics, wavelet, σ_b/drift); dev trên realization 902–905; viết và khóa `protocol_bench.yaml` (S1, S2, S3, S4, S8) kèm `.sha256`, `.lock.json` | Protocol khóa |
| T4 4/11 – T5 5/11 | S1 lấp lưới c ∈ {0.5, 1.5}, N ∈ {2, 8}; S3 B4 dưới SMC; S4 backbone thứ hai (hai GPU) | Lưới đầy |
| T6 6/11 – T7 7/11 | S2 ba trục ở R10, Rm5, c = 1, N ∈ {4, 16}; S8/T8 cycle-skip | Bảng misspec |
| CN 8/11 – T3 10/11 | S7 đóng gói benchmark (một lệnh sinh, một lệnh chấm, bảng tham chiếu, README, hash, Zenodo); viết lại §4–5 | Gói benchmark; draft v2 |
| T4 11/11 – T5 12/11 | Review nội bộ; hình; phụ lục chứng minh; gói tái lập | Draft v3 |
| T6 13/11 | Kiểm tra novelty lần cuối; tra quartile; preprint | — |
| **T7 14/11** | **Nộp** *Computers & Geosciences* | Bản nộp |
**Thứ tự cắt phạm vi nếu trễ (lịch mức B; không cắt ngưỡng):** (1) S4 backbone thứ hai; (2) S8/T8; (3) S2 rút còn một trục rock physics, khi đó bài gọi là "controlled synthetic study", không gọi là benchmark; (4) S1 rút còn c ∈ {0.5, 1.5} với N = 4/16; (5) T2 chỉ giữ thí nghiệm responsibility-weighted warp error.
**Thứ tự cắt phạm vi nếu trễ (lịch cũ đến 31/10; mục 1 và 5 đã áp dụng)** (cắt từ trên xuống, không cắt các cổng hay ngưỡng):
1. M3 (RML-EM): đã hoãn. 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. 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. 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. 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). 5. Volve: chỉ B3 tốt nhất, B3d-S và M2 (bỏ B1, B4, B5). Đã áp dụng trong `protocol_volve`.
6. Lưới stress ở P2: chỉ trục SNR và mật độ anchor. 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. **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.
@@ -440,7 +463,7 @@ scripts/ 01_build_wells.py, 02_tie.py, 03_train.py, 04_eval.py, 05_predi
tests/ test_geometry.py (Set Point), test_tdr.py (monotone, honor anchors), test_losses.py (special cases ở 4.5) tests/ test_geometry.py (Set Point), test_tdr.py (monotone, honor anchors), test_losses.py (special cases ở 4.5)
``` ```
Giữ nguyên `test 2/` làm bản lưu trữ của luận văn; không sửa tại chỗ. Giữ nguyên [`code_thesis/`](../code_thesis/) làm bản lưu trữ của luận văn (đã đổi tên từ thư mục cũ ngày 27/10/2026); không sửa tại chỗ. Lưu output gốc trong [`outputs_thesis/`](../outputs_thesis/), theo dõi SHA-256 bằng `data_manifest/thesis_outputs.json`; `outputs/` dành cho pipeline nghiên cứu. Code lưu trữ vẫn chứa đường dẫn máy cũ, nên cần bản sao đã điều chỉnh đường dẫn nếu muốn chạy lại.
--- ---
@@ -473,6 +496,8 @@ Giữ nguyên `test 2/` làm bản lưu trữ của luận văn; không sửa t
- T4: ablation. - T4: ablation.
- T5: field 2. - T5: field 2.
**Chốt 29/10/2026 (Pivot 1, mục 12 ý 22):** venue chính *Computers & Geosciences*; dự phòng *Geophysical Prospecting*. Dàn ý mới (8 mục, theory + benchmark + detectability) ở `docs/research/pivot-theory-benchmark.md` mục 3.3; dàn ý, hình và bảng dưới đây là bản trước pivot. Bản nháp ngày 29/10 đã theo dàn ý mới (mục 12 ý 24). Độ dài: thân bài khoảng 14.750 từ, trong khi giới hạn Research Article của C&G là khoảng 5.500 từ theo nguồn thứ cấp (chưa kiểm trên trang chính thức); xem R9 ở mục 9. Người dùng bỏ lượt rút gọn độ dài ngày 29/10 (mục 12 ý 25).
**Venue** (kiểm tra quartile SJR mới nhất khi nộp [XM]): **Venue** (kiểm tra quartile SJR mới nhất khi nộp [XM]):
| Venue | Lý do phù hợp | Lưu ý | | Venue | Lý do phù hợp | Lưu ý |
@@ -498,9 +523,10 @@ Giữ nguyên `test 2/` làm bản lưu trữ của luận văn; không sửa t
| 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 độ (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. | | 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. |
| R9 (thêm 29/10/2026): bản thảo dài gấp khoảng 2,7 lần giới hạn số từ của venue (C&G khoảng 5.500 từ, chưa kiểm trên trang chính thức) | Cao | Người dùng bỏ lượt rút gọn độ dài ngày 29/10 (mục 12 ý 25); rủi ro vẫn mở, chưa có biện pháp. Nếu sau này có rút gọn thì không bỏ kết quả âm hay deviation đã ghi. |
**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*. **Kích hoạt ngày 29/10/2026** (mục 12 ý 22; thiết kế ở `docs/research/pivot-theory-benchmark.md`; venue chốt *Computers & Geosciences*).
- **Pivot 2:** chuyển sang G2 (nhận dạng theo băng thông), tái sử dụng hạ tầng D2. - **Pivot 2:** chuyển sang G2 (nhận dạng theo băng thông), tái sử dụng hạ tầng D2.
- **Pivot 3:** viết ghi chú audit benchmark F3 cho porosity; venue thấp hơn. - **Pivot 3:** viết ghi chú audit benchmark F3 cho porosity; venue thấp hơn.
@@ -526,10 +552,10 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
| --- | :-: | --- | | --- | :-: | --- |
| Buland & Omre (2003), Bayesian wavelet estimation from seismic and well data, *Geophysics* 68(6) | Có | 10.1190/1.1635053. Mistie của marker là biến ẩn có prior (mục 2.1) | | Buland & Omre (2003), Bayesian wavelet estimation from seismic and well data, *Geophysics* 68(6) | Có | 10.1190/1.1635053. Mistie của marker là biến ẩn có prior (mục 2.1) |
| Gunning & Glinsky (2006), Wavelet extractor: a Bayesian well-tie and wavelet extraction program, *C&G* 32, 681–695 | Có | 10.1016/j.cageo.2005.10.001. Thời gian checkshot/marker là tham số có prior; sai số định vị giếng; posterior Laplace (mục 2.1) | | Gunning & Glinsky (2006), Wavelet extractor: a Bayesian well-tie and wavelet extraction program, *C&G* 32, 681–695 | Có | 10.1016/j.cageo.2005.10.001. Thời gian checkshot/marker là tham số có prior; sai số định vị giếng; posterior Laplace (mục 2.1) |
| Wu & Caumon (2017), simultaneous multiple well-seismic ties using flattened synthetic and real seismograms, *Geophysics* 82(1) IM13–IM20 | Có | 10.1190/GEO2016-0295.1. File `geo2016-0295.pdf` là bản HAL | | Wu & Caumon (2017), simultaneous multiple well-seismic ties using flattened synthetic and real seismograms, *Geophysics* 82(1) IM13–IM20 | Có | 10.1190/GEO2016-0295.1. File `wu2017multiwelltie.pdf` là bản HAL |
| Tschannen, Ghanim & Ettrich (2022), partial automation of the seismic to well tie with deep learning and Bayesian optimization, *C&G* 164 | Có | 10.1016/j.cageo.2022.105120 | | Tschannen, Ghanim & Ettrich (2022), partial automation of the seismic to well tie with deep learning and Bayesian optimization, *C&G* 164 | Có | 10.1016/j.cageo.2022.105120 |
| Ali et al. (2024), AI Review 58:31, synthetic pseudo-wells + CNN + transfer learning, target P-impedance | Có | 10.1007/s10462-024-11030-8 | | Ali et al. (2024), AI Review 58:31, synthetic pseudo-wells + CNN + transfer learning, target P-impedance | Có | 10.1007/s10462-024-11030-8 |
| Herrera & van der Baan, tie bán tự động bằng DTW | Chỉ preprint arXiv 2012 (`Herrera2012_...`) | Bản *Geophysics* 2014 (79(3) V47–V54, 10.1190/GEO2013-0248.1) chưa có. Trích bản nào thì ghi đúng bản đó | | Herrera & van der Baan, tie bán tự động bằng DTW | Chỉ preprint arXiv 2012 (`herrera2012automatedtie.pdf`) | Bản *Geophysics* 2014 (79(3) V47–V54, 10.1190/GEO2013-0248.1) chưa có. Trích bản nào thì ghi đúng bản đó |
| Cuturi & Blondel (2017), Soft-DTW, ICML | Có | arXiv 1703.01541 | | Cuturi & Blondel (2017), Soft-DTW, ICML | Có | arXiv 1703.01541 |
| Le Guen & Thome (2019), DILATE, NeurIPS | Có | arXiv 1909.09020 | | Le Guen & Thome (2019), DILATE, NeurIPS | Có | arXiv 1909.09020 |
| Lakshminarayanan et al. (2017), deep ensembles; Kendall & Gal (2017), heteroscedastic uncertainty | Có | arXiv 1612.01474; arXiv 1703.04977 | | Lakshminarayanan et al. (2017), deep ensembles; Kendall & Gal (2017), heteroscedastic uncertainty | Có | arXiv 1612.01474; arXiv 1703.04977 |
@@ -538,8 +564,17 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
| Ravasi & Vasconcelos, PyLops | Có (bản arXiv) | *SoftwareX* 11 (2020) 100361, 10.1016/j.softx.2019.100361 (online từ cuối 2019). Năm 2020 trong plan cũ là đúng | | Ravasi & Vasconcelos, PyLops | Có (bản arXiv) | *SoftwareX* 11 (2020) 100361, 10.1016/j.softx.2019.100361 (online từ cuối 2019). Năm 2020 trong plan cũ là đúng |
| Alfarraj & AlRegib (2019), semi-supervised learning for acoustic impedance inversion, SEG | Có | arXiv 1905.13412 | | Alfarraj & AlRegib (2019), semi-supervised learning for acoustic impedance inversion, SEG | Có | arXiv 1905.13412 |
| Các bài P01–P03, P06, P08, P10–P15 của survey | Có | Mã và DOI trong [porosity-references.bib](docs/research/porosity-references.bib). P14 và P15 là bản arXiv | | Các bài P01–P03, P06, P08, P10–P15 của survey | Có | Mã và DOI trong [porosity-references.bib](docs/research/porosity-references.bib). P14 và P15 là bản arXiv |
| Lim, Van Wagoner & Cardona (IMAGE 2025), AWSM: PT-MCMC cho time–depth + wavelet | Không (abstract) | 10.1190/image2025-4304877.1. Thuộc L1, là tie UQ gần nhất; không có bước học (mục 2.4) |
| Lim & Cardona (IMAGE 2025), BootNet | Không (abstract) | 10.1190/image2025-4304887.1. Ensemble bootstrap cho AVA; UQ của mạng, không có tie |
| Quesada, Prabhushankar & AlRegib (IMAGE 2024), nhãn fault F3 từ 38 người gán | Không (abstract trên trang lab) | Chưa tìm thấy DOI. Bất định nhãn kiểu diễn giải, không phải thời điểm |
| Mirza et al. (EAGE 2025), chất lượng seismic và nhãn salt | Không (abstract) | 10.3997/2214-4609.2025101452 |
| Guillon et al. (2020), *TLE* 39(10) 734–741, metric có dung sai cho fault/horizon | Không (abstract) | 10.1190/tle39100734.1. Tìm thấy khi tra Crossref ngày 28/10, ngoài danh sách quét; là tiền lệ gần nhất cho cột "đánh giá có xét registration" |
| Cordoba, Goyes & Castro (EAGE 2025), seismic → porosity bằng NN | Không (abstract) | 10.3997/2214-4609.2025101450. Abstract không nhắc tie hay nhãn lệch |
| Thiebaud, Aker & Kjønsberg (EAGE 2024), porosity từ inversion litho-facies xác suất | Không (abstract) | 10.3997/2214-4609.202410490 |
| Rizzuti & Vasconcelos (EAGE 2024); Rizzuti, Telling & Vasconcelos (EAGE 2025), UQ inversion post-stack bằng normalizing flow | Không (abstract) | 10.3997/2214-4609.202410525; 10.3997/2214-4609.202510205 |
| Huff et al. (EAGE 2024), CNN căn chỉnh angle stack | Không (abstract) | 10.3997/2214-4609.202410580. Lệch nằm ở input, không phải nhãn |
**Bỏ qua, không có toàn văn (quyết định ngày 26/10/2026):** P04, P05, P07, P09; White & Simm (2003). Chỉ được trích dựa trên abstract hoặc trích gián tiếp, và không dùng làm căn cứ cho claim nào ở mục 10 trở đi mà chưa đọc. **Bỏ qua, không có toàn văn (quyết định ngày 26/10/2026; với P04, P05, P07, P09 xác nhận lại ngày 28/10/2026, xem mục 2.2):** P04, P05, P07, P09; White & Simm (2003). Chỉ được trích dựa trên abstract hoặc trích gián tiếp, và không dùng làm căn cứ cho claim nào ở mục 10 trở đi mà chưa đọc.
**Bỏ qua, không tìm thấy bài (quyết định ngày 26/10/2026), không đưa vào bib và không trích:** Muñoz & Hale (2015) (chỉ thấy luận văn thạc sĩ Mines 2014 cùng tên), RING 2025 (Boucard, Caumon & Baville). **Bỏ qua, không tìm thấy bài (quyết định ngày 26/10/2026), không đưa vào bib và không trích:** Muñoz & Hale (2015) (chỉ thấy luận văn thạc sĩ Mines 2014 cùng tên), RING 2025 (Boucard, Caumon & Baville).
@@ -547,10 +582,10 @@ 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 (26/10–31/10/2026) ## 12. Việc làm ngay (26/10–14/11/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). Ngày 27/10/2026 đã bổ sung `outputs_thesis/`: 7 artifact, có checkpoint/dự đoán v2 và volume hợp lệ; xem [audit](research/thesis-output-audit.md).
3. Viết `geometry.py` và test bằng Set Point; tạo lại bảng IL/XL ở mục 1.2a từ code. 3. Viết `geometry.py` và test bằng Set Point; tạo lại bảng IL/XL ở mục 1.2a từ code.
4. Viết `tdr.py` (marker-calibrated sonic) và vẽ hình drift 4 giếng (bản nháp F2). 4. Viết `tdr.py` (marker-calibrated sonic) và vẽ hình drift 4 giếng (bản nháp F2).
5. ~~Đo phổ seismic quanh 4 giếng.~~ **Đã xong ngày 26/10/2026** (mục 2.3): tần số trội khoảng 50–60 Hz, băng 4–83 Hz, f_c đề xuất 6 Hz. 5. ~~Đo phổ seismic quanh 4 giếng.~~ **Đã xong ngày 26/10/2026** (mục 2.3): tần số trội khoảng 50–60 Hz, băng 4–83 Hz, f_c đề xuất 6 Hz.
@@ -601,6 +636,91 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
- **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. - **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. - **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. - **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. - **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) đã đăng ký, nên không quy hết cho khử nhoè (*sửa 29/10: cận đã đăng ký là cận classical; với cận Berkson post hoc chỉ 3/8 ô rộng vượt, hai ô sát cận, và tối đa 1/8 tại sai số warp; xem ý 24*). 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. - **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. - **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.
15. **Triển khai P3 trên máy Windows / RTX 3060 (đêm 27–28/10/2026, trước kết quả P3):**
- Đã pull Gitea `main` từ `5a6fb2f` lên `a22f9d9`, đọc `AGENTS.md` và rà code theo bốn skill: scientific-critical-thinking, scikit-learn, statistical-analysis, scientific-visualization. Chi tiết lỗi, cách sửa và giới hạn ở [p3-code-review.md](research/p3-code-review.md). Bộ test: 129 đạt, 13 bỏ qua do nền tảng/dữ liệu tùy chọn; không coi test phần mềm là bằng chứng đạt G-C.
- Protocol F3 dùng tên `configs/protocol_f3.yaml`; khóa trước registration/train bằng script 19. Khóa gồm code, môi trường và dữ liệu; giữ nguyên ngưỡng G-C. F3 đã được xem trong P1 nên đây là follow-up mô tả trên cùng bốn giếng, không phải tập field hoàn toàn chưa quan sát.
- Nested LOWO 4 vòng ngoài × 3 vòng trong, 5 seed; dùng lại trajectory có cùng hai giếng train. Vòng trong chọn một budget chung theo MSE validation trung bình, hòa chọn sớm nhất; ensemble 3 mô hình vòng trong × 5 seed khi chấm giếng ngoài. Không refit trên nhãn giếng ngoài. Đối thủ point tie cho G-C cũng chọn bằng validation, không chọn theo test.
- Lưới gồm 1.320 trajectory tối đa 2.000 bước, hai nhãn PHIE_DT/PHIE, 12 ablation trên nhãn chính và hai nhánh σ_a = 3.5/14 ms. σ_a chính 7 ms kế thừa P2r, không được xem là giá trị đúng trên F3. Leave-one-anchor-out dùng xấp xỉ GP tuyến tính chỉ có anchor và phải ghi rõ không kiểm định calibration của SMC.
- Volume đầy đủ dùng ensemble triển khai 20 mô hình (4 tập ba giếng × 5 seed), chỉ có tính mô tả. Viền thiếu patch 3×3 để NaN. Chỉ giảm phạm vi sang section khi có yêu cầu rõ ràng, không tự hạ yêu cầu vì chậm.
- Môi trường Windows: Python 3.12.16, torch 2.11.0+cu128, driver 577.00; giữ riêng `requirements-windows-rtx3060.txt`, không thay lock Linux. Cube và bảy horizon phục hồi từ bản Thesis khớp SHA-256 gốc. Chỉ script 01 được chạy để dựng dữ liệu; **không chạy lại script 04 và 09** theo yêu cầu người dùng, hai artifact cũ được kiểm tra hash trong khóa P3.
- Benchmark so sánh 1/2/3/4/6 tiến trình: 4 nhanh nhất (khoảng 319 bước/s), riêng train 1,6–3,3 giờ. Pilot registration chỉ dùng cặp giếng train, không chọn thiết kế bằng điểm test; tổng dự toán sau pilot ở `outputs/p3/progress.json`. Khoảng thời gian là ngoại suy vận hành, không phải khoảng tin cậy.
- Người dùng đã cho phép chủ động chạy full qua đêm. Driver `scripts/run_p3.ps1 -Stage all -Device cuda:0 -Workers 4 -Detach` chạy nền ẩn, giữ máy thức khi process còn sống, lưu log và resume có checksum. [report.html](../report.html) đọc sidecar cập nhật mỗi 10 giây; trạng thái chuẩn và kết quả G-C nằm trong `outputs/p3/`. Không thay đổi kết luận P2/P2r.
- **Đã khóa và khởi chạy:** SHA-256 protocol `0c756d2825d9b6aa1520be6484f501a538f2ec14e5c8fe98a323cf3b6e1bc50c`, khóa 00:14 ngày 28/10. Smoke CUDA toàn tuyến (6 registration, 18 train job, diagnostics và summary) hoàn tất, G-C cố ý không chấm. Full P3 chạy nền từ 00:15:47 ngày 28/10, dự kiến 2,57–6,35 giờ (khoảng 02:49–06:37 giờ máy). Trạng thái thực tế tiếp tục ghi tự động; giờ dự kiến không phải cam kết kết quả khoa học.
16. **Kết quả P3 F3 và sự cố vận hành (28/10/2026):**
- Đã hoàn tất 1.320 trajectory LOWO, 12 ablation, hai nhánh σ_a, diagnostics/LOAO, summary và 20 mô hình triển khai volume. Kết quả ở `outputs/p3/summary/`.
- **G-C KHÔNG ĐẠT cả hai điều kiện.** M2-Sa chỉ cải thiện band RMSE tại F03-4 (1/4 giếng), cần ≥ 3/4. Đối thủ được vòng validation chọn là B3c-R ở cả bốn giếng. Tỷ số M2-Sa/B3c-R lần lượt F02-1: 1,00769; F03-2: 1,00023; F03-4: 0,98105; F06-1: 1,07028. Không thay đối thủ sau khi xem test.
- Coverage macro 80% là 52,38% (cần 75–85%); coverage 90% là 60,91% (cần 85–95%). Band RMSE macro M2-Sa 1,27229 p.u., B3c-R 1,25591 p.u. Không claim calibration, không mở rộng khoảng sau khi xem test. Kết quả F3 không ủng hộ ưu thế field của M2-Sa theo protocol này; không thay kết luận P2/P2r.
- Lượt chạy nền đầu dừng lúc 03:57:33 sau 3 giờ 41 phút 46 giây: Windows từ chối thay file `progress.js` khi volume đã ghi 132/649 inline. Log lỗi giữ nguyên ở `logs/runs/20261028-001548_p3_all/`. Đây là lỗi cập nhật dashboard, không phải huấn luyện hoặc gate.
- Phục hồi bằng `operations/resume_f3_volume.py`: chỉ thêm retry cho hai file dashboard khi bị khóa, gọi nguyên hàm suy luận đã khóa, không chạy lại registration/train hoặc script 04/09. Mã khoa học, protocol, checkpoint và G-C không đổi; kiểm tra SHA-256 khóa và byte của 132 inline cũ trước/sau. Lưu provenance ở `outputs/p3/volume_recovery.json`; trạng thái hoàn tất volume thực tế đọc trong [report.html](../report.html).
- **P3 hoàn tất lúc 06:50:44 ngày 28/10.** Volume đủ 649 inline trong, shape 651×951×126 gồm viền NaN, mean và sigma, kèm 8 hình section. Adapter gặp lại đúng lỗi khóa dashboard một lần và retry thành công. Không đổi byte của 132 inline cũ; khóa code/dữ liệu/môi trường và G-C vẫn khớp. Kiểm tra artifact cuối ở `outputs/p3/completion_checks.json`; nhiệm vụ P3 hoàn thành, cổng khoa học G-C trượt.
17. **Đóng P3 và ghi chú cho paper (28/10/2026):**
- **Quyết định:** đóng P3, không chạy P3r. Mọi thay đổi thiết kế lúc này đều là lựa chọn sau khi đã thấy nhãn test. Chuyển sang P4 Volve.
- **Thứ tự thời gian của việc khóa (giờ máy Windows, +07):** pilot registration 00:07 và preflight baseline cổ điển 00:12, cả hai không tính metric trên giếng test; khóa SHA-256 lúc 00:14:50; smoke 00:15:05; main run 00:15:47. `protocol_f3.yaml` vào git lần đầu ở commit 9976abc (07:01, cùng với kết quả), và tag `protocol-f3` được gắn sau đó. Vì vậy bằng chứng khóa trước khi chạy là timestamp tự ghi trong `configs/protocol_f3.lock.json`, không phải lịch sử git. Paper (§6 và §6.4) ghi đúng như vậy.
- **Tái lập P3 dùng tag `protocol-f3`, không dùng HEAD (kiểm tra 28/10).** `source_hash()` (`ml_porosity/f3/protocol.py`) băm mọi `ml_porosity/**/*.py`, `scripts/*.py`, `scripts/run_p3.ps1` và `pyproject.toml` có trong cây làm việc, kể cả file chưa track; CRLF chuẩn hoá về LF. Bản export sạch của tag (9976abc, 70 file) cho đúng hash code trong khóa (`b5c82d2dfd53dcab…`). HEAD 7da6b07 (71 file) cho `542590c4ee6e1ec8…` vì commit 4a5d0b2 thêm `scripts/22_paper_figures.py` sau khi khóa; code P4 trong `ml_porosity/` và `scripts/` cũng đổi hash này. Khóa còn ghi môi trường Windows (Python 3.12.16, torch 2.11.0+cu128) và đường dẫn input dạng `outputs\f3_wells.npz`, nên `freeze()` chỉ qua trên máy Windows ở tag này; trên Linux chỉ tái tạo được hash code. Đây là đúng thiết kế khóa, không phải lỗi; không tạo lại khóa.
- **Phân tích làm sau khi chạy (post hoc), chỉ mô tả, không đổi G-C:** (a) Mốc "không có nội dung băng" là RMS thành phần > 6 Hz của reference PHIE_DT calibrated, macro 1,224 p.u. Chỉ B4b (1,211) thấp hơn mốc này. (b) Trong cửa sổ 600–1100 ms, PHIE và PHIE_DT chênh RMS 3,2 p.u. ở F02-1 và < 0,02 p.u. ở ba giếng còn lại. (c) σ_post, pha và logZ tổng hợp từ `outputs/p3/registration/*.json`; thống kê volume từ `mean.npy`/`sigma.npy`. Nguồn từng con số ở `paper/README.md`.
- **Lỗi nhãn trong code khóa:** `plot_sections` đặt nhãn trục x của PNG section inline là "inline", thực ra là crossline. Không sửa code khóa. Hình trong paper (`paper/figures/f3_volume.pdf`) được tạo lại bằng `scripts/22_paper_figures.py --only f3_volume`.
18. **P4 Volve: lớp dữ liệu giếng nghiêng (28/10/2026; chỉ CPU; chưa khóa, chưa tính metric PHIF nào):**
- **Code:** `ml_porosity/data/deviated.py` (trajectory minimum curvature từ survey Compass "ACTUAL", TDR thời gian thẳng đứng, đường giếng theo thời gian, mô hình TVDSS→TWT, patch 3×3 dọc đường giếng), `ml_porosity/data/volve_wells.py` (log, anchor, tập giếng train khi blind), `scripts/23_build_volve_wells.py` → `outputs/volve/volve_wells.npz` và `volve_wells_summary.json` (khoảng 1 phút CPU), test `tests/test_deviated.py`. Tham số ở mục `p4` của `configs/d3_volve.yaml`.
- **Survey:** cả 6 giếng đều nghiêng: inclination lớn nhất 30–82°, trên đoạn nhãn 4–54°. Tính lại minimum curvature khớp TVD của file trong 0,007 m và XY trong 0,44 m; MD/TVD đáy khớp header. Pick nằm trên survey trong 0,39 m TVD và 1,01 m XY, nhỏ so với bin 12,5 m.
- **Thời gian:** TWT tích phân DT theo TVD (giả định đẳng hướng), rồi hiệu chỉnh theo marker: stretch giữa các anchor, shift ngoài. Ở F-11 A, F-11 T2 và F-12, hệ số stretch là 0,92–1,37 khi tích phân theo TVD và 0,24–1,05 khi tích phân theo MD. Tại F-11 T2, TDR calibrated lệch NIVSP −2,4 đến −0,8 ms trên đoạn nhãn. RSVSP lệch +35 ms (offset VSP trong giếng nghiêng) nên không dùng.
- **Anchor:** pick có TWT, bỏ các surface nông và cờ NL, NR, FP (FP chỉ có ở F-1 Skagerrak). Pick cùng MD hoặc cách ≤ 1 m gộp làm một. Vận tốc khoảng Draupne→Heather Sand ở F-1 A là 2100 m/s, bất thường so với 3195–3490 m/s hai bên. Vận tốc khoảng liên tiếp ở F-1 B (2670/2674/2683 m/s) và F-11 A (2774/2764/2764 m/s) gần như trùng nhau, nên TWT pick có thể lấy từ mô hình vận tốc. Hai điểm này chỉ ghi nhận, không sửa.
- **Nhãn:** PHIF trong khoảng có DT hợp lệ, 16–37 mẫu 4 ms mỗi giếng (tổng 150), TWT 2509–2819 ms. Nhãn nằm dưới anchor cuối 25–179 m nên phụ thuộc drift sonic. Cửa sổ chính 2400–2900 ms (126 mẫu) chứa mọi nhãn và nằm dưới phần ngoại suy lên trên của mọi TDR calibrated (đỉnh có ràng buộc ≤ 2319 ms); 2000–3200 ms chỉ là lề. Cửa sổ chọn một lần theo vị trí nhãn của cả 6 giếng, trước mọi lần train. Nhãn ngắn hơn `window_samples` = 64 của F3, nên pipeline P4 cần loss có mask.
- **Đầu vào blind (chính, mục 5.2):** đường giếng test đặt theo thời gian bằng mô hình TVDSS→TWT trung bình của các giếng train, không dùng pick hay DT của giếng test. Seismic vẫn lấy ở cùng thời gian; TDR blind chỉ dời vị trí XY của đường giếng. Lưu đủ 31 tập con của 5 giếng còn lại cho hai scheme `lowo` và `slot`; `slot` bỏ cả nhóm chung lỗ khoan ({F-1, F-1 A, F-1 B}, {F-11 A, F-11 T2}, {F-12}). TDR blind lệch TDR calibrated tới 45 ms (F-1 A, slot), làm đường giếng dời tới 76 m. Đường calibrated của giếng test chỉ dùng cho thiết lập phụ "calibration-assisted".
- **Seismic:** patch 3×3 nội suy bilinear dọc đường giếng; nearest chỉ để QC (lệch RMS tương đối 0,05–0,09). Dưới TD, đường giếng giữ ở trạm cuối. Trên đoạn nhãn, trace thẳng đứng tại một bin lệch composite 0,19–0,61 (RMS tương đối), nên không dùng trace thẳng đứng.
- Các số trên là QC mô tả từ DT, RHOB, pick, checkshot và seismic; không chọn gì theo các số này. Việc tiếp theo: pipeline P4 (loss có mask, fold LOWO/slot), nháp `configs/protocol_volve.yaml`, smoke CPU, rồi khóa và chạy trên RTX 3060.
19. **P4 Volve: pipeline và protocol nháp (28/10/2026; chỉ CPU; chưa khóa, chưa tính metric PHIF nào):**
- **Code:** `ml_porosity/volve/` gồm `data.py` (view public/private), `folds.py` (fold lồng LOWO/slot), `losses.py` (bank loss có mask), `registration.py`, `training.py`, `runner.py` (job resume được, có checksum) và `evaluation.py` (chọn budget và đối thủ B3 bằng inner validation, G-D mô tả); `protocol.py` khóa code, input và môi trường. Script là `scripts/24_run_volve.py` và `scripts/run_p4.ps1`; test ở `tests/test_volve_pipeline.py`. Không sửa gì trong `ml_porosity/f3/`.
- **Chống rò nhãn:** view của tập train chỉ giữ của giếng ngoài tập thời gian, mask cửa sổ, KB, survey và các blind key K ⊇ tập train (giếng đó ∉ K). Đọc nhãn, đường reference hay quan sát registration của giếng đó sẽ báo lỗi. Việc chọn budget và đối thủ B3 đọc nhãn validation qua view của T_out, nên không thấy giếng test ngoài. Có test kiểm tra: đổi PHIF của giếng test thì selection và dự đoán của fold đó không đổi.
- **Fold:** 22 tập train khác nhau (15 tập 4 giếng, 4 tập 3, 3 tập 2) cho 52 fold lồng (30 LOWO, 22 slot). Mỗi trajectory dự đoán 8, 15 hoặc 34 đầu vào; cache dùng chung giữa các fold. Nhánh chính có 22 registration và 550 job train; hai nhánh σ_a có 44 registration và 660 job.
- **Deviation phát hiện ở smoke (trước khóa):** bản nháp đầu lấy giao support nhãn của mọi member và mọi method. Ở F-11 A (15–17 mẫu theo từng tie) giao này chỉ còn 7 mẫu, dưới ngưỡng `min_label_samples` = 8. Đo lại với cấu hình đầy đủ (1024 particle, S = 64) cũng ra 7. Sửa: mỗi member dùng support của chính nó; log-likelihood các member được so ở số mẫu trung bình; một cửa sổ duy nhất phủ cả cửa sổ chính (126 mẫu) thay cho cửa sổ 64 mẫu bước 2 của F3. Với mask chung, loss mới bằng đúng loss cũ. Sau khi sửa, smoke cho support nhỏ nhất mỗi member là 13 mẫu (F-11 A). Giao vẫn được ghi trong `registration.csv` (`common_samples`) để mô tả. Đã ghi trong `deviations.member_support` và `masked_loss` của `configs/protocol_volve.yaml`.
- **Smoke CPU** (`outputs/p4/smoke`, 16 particle, S = 8, 1 seed, budget 2/4): 22/22 registration và 110/110 job train, mọi output hữu hạn, không lỗi. Chưa chạy summarize vì bước này cần khóa. Một registration đầy đủ (tập 4 giếng) mất 847 s trên 4 luồng CPU; thời gian trên RTX 3060 sẽ đo bằng stage `benchmark`.
- **Việc tiếp theo trên máy Windows:** đồng bộ `outputs/volve/volve_wells.npz`, chạy `run_p4.ps1 -Stage benchmark`, rồi `-Stage lock` (khóa tạo trên máy chạy), rồi `-Stage all` và các nhánh σ_a. `run_p4.ps1` chưa được chạy thử vì Linux không có pwsh.
20. **P4 Volve: chạy xong, G-D (29/10/2026, server Linux, giờ UTC):**
- **Máy chạy (quyết định trước khóa):** chạy trên server Linux (H200), không chạy trên máy Windows RTX 3060 như ý 19. Stage `benchmark` (chỉ giếng train, không tính metric PHIF) lúc 01:16 cho registration tập 4 giếng 17 s trên GPU (847 s CPU). Trước khóa đã sửa mục `runtime` của `protocol_volve.yaml` (cuda:1, 8 worker, lý do) và thêm driver `scripts/run_p4.sh` vào hash code. 49/49 test pass. Khóa lúc 01:17:42 UTC (`protocol_sha256` 7fdff4a1…, `code_sha256` c0befaa4…, Python 3.13.15, torch 2.14.0+cu130, cube khớp manifest).
- **Deviation sau khóa (chỉ về lịch chạy):** `runtime.order` ghi chạy nhánh chính rồi mới tới nhánh σ_a, và `device` là cuda:1. Thực tế nhánh σ_a chạy song song trên cuda:0 từ 01:22 để tận dụng GPU trống. Device không nằm trong fingerprint, mỗi job tự seed, file hai nhánh tách riêng, nên chỉ có thể khác ở sai số dấu phẩy động giữa hai H200. Summarize `--arms all` cho G-D của nhánh chính trùng hệt lần summarize đầu.
- **Thời gian:** nhánh chính 22 registration (2 phút 47 giây) + 550 job train (46 phút 46 giây); nhánh σ_a 44 registration (5 phút 28 giây) + 660 job (52 phút 39 giây); không job nào lỗi. Server dùng chung (vLLM, job người khác): load CPU 30–69/40, cuda:1 có lúc còn 4 GB trống nhưng không OOM.
- **G-D (mô tả; tham chiếu calibrated, σ_a = 7 ms, ensemble gộp; `outputs/p4/summary/`):** lowo: M2-Sa tốt hơn B3 được chọn ở **2/6** giếng, RMSE macro 6,50 so với 6,36 (B3b) và 6,52 (B3d-Sa), coverage80/90 = 0,39/0,48. slot: **3/6** giếng, 7,13 so với 7,32 (B3 chọn) và 7,26 (B3d-Sa), coverage 0,35/0,47. **Không "consistent improvement", không "calibrated".** Ensemble under-cover nặng hơn F3.
- **Không có kỹ năng dự đoán ở giếng blind:** R² âm với mọi phương pháp và scheme (−0,84 đến −1,71, tham chiếu calibrated), PCC 0,12–0,24. Với tham chiếu anchors (4 giếng) PCC từ −0,11 đến +0,02; NIVSP/OPTIMIZED (chỉ F-11 T2) PCC âm. Các dự đoán M2-Sa, B3b, B3d-Sa gần trùng nhau; mô hình bỏ lỡ đoạn PHIF cao ở F-12 (~22 p.u.) và F-11 A. Khác biệt giữa các phương pháp tie (0,1–0,2 p.u.) nhỏ hơn rất nhiều so với sai số tổng (6–7 p.u.).
- **Nhánh σ_a (3,5 / 14 ms):** RMSE macro M2-Sa 6,49/6,55 (lowo) và 7,13/7,09 (slot), gần như không đổi so với 7 ms; coverage90 0,43–0,52. Trên Volve kết quả không nhạy với σ_a, vì không có tín hiệu nào để σ_a làm thay đổi (khác P2r, nơi H2a phụ thuộc σ_a).
- **Hệ quả cho paper:** Volve không ủng hộ transfer. Báo cáo như một kết quả âm thứ hai: với 16–37 mẫu nhãn mỗi giếng, giếng nghiêng và PHIF dẫn xuất từ density, seismic post-stack trong cửa sổ 2400–2900 ms không dự đoán được PHIF ở giếng blind bằng bất kỳ phương pháp tie nào; câu hỏi "RML có giúp không" không trả lời được trên Volve. Không claim cải thiện, không claim hiệu chuẩn, không claim transfer (mục 10). Không chạy lại hay đổi thiết kế (mọi thay đổi lúc này đều sau khi thấy nhãn test).
21. **P4 sau G-D: post hoc, đổi trục bài, exploratory P4x (29/10/2026; commit cùng ngày, ý 25):**
- **Post hoc, ngoài khóa, không đổi G-D** (`scripts/25_p4_posthoc.py` → `outputs/p4/posthoc/wells.csv`, `macro.csv`; tham chiếu calibrated, σ_a = 7 ms, ensemble gộp). Hằng số bằng trung bình PHIF gộp của các giếng train ngoài (không dùng seismic) có RMSE macro **6,03 (lowo) và 6,59 (slot)**, R² −0,70 và −1,14. Con số này thấp hơn mọi phương pháp (6,36–6,61 và 7,13–7,32). Trung bình PHIF từng giếng 8,5–17,0 p.u., SD trong giếng 3,3–6,0 p.u.; hằng số lệch trung bình giếng test tới 6,4 p.u. Độ lệch trung bình của M2-Sa bám độ lệch của hằng số: F-1 +3,9 so với +4,9, F-11 A −5,4 so với −4,3, F-12 −6,8 so với −6,0 p.u. Sau khi bỏ độ lệch trung bình từng giếng, SD sai số của M2-Sa (trung bình theo giếng) là 5,2/5,1 p.u., lớn hơn SD nhãn trong giếng (trung bình 4,8); SD dự đoán trong giếng 1,1–4,1. Sai số do mức trung bình giữa giếng chi phối, nên so sánh G-D không có lực phân biệt.
- **Đọc thêm từ output khóa (chỉ mô tả):** `best_shift_DIAGNOSTIC_ONLY.csv` cho M2-Sa PCC 0,40–0,82 sau khi dời, nhưng shift tối ưu 56–64 ms, sát biên tìm kiếm ±64 ms, ở 3 giếng (lowo) và 4 giếng (slot). Với 16–37 mẫu, tìm trên 33 shift nên PCC cực đại bị thổi phồng; không đọc đây là bằng chứng về lệch thời gian. `registration.csv`: σ_post 1,9–9,3 ms (trung vị 4,3; 3,0 trên mẫu có nhãn), F-11 T2 1,9–2,6, F-12 4,3–9,3; trung vị 3,8/4,3/4,1 ms ở σ_a 3,5/7/14 ms, tức gần như không theo σ_a. Pha wavelet của 22 tập train nằm trong cung 43° (F3: 214°). Khác biệt giữa các tie ≤ 0,25 p.u. RMSE macro.
- **Đổi trục bài (P5):** bằng chứng cho RML là lý thuyết (Mệnh đề 1 khớp trong 1%) và benchmark synthetic P2r. F3 là kết quả âm có thông tin. Volve là hiệu ứng sàn: không có kỹ năng ở giếng blind, nên không phải bằng chứng ủng hộ hay chống RML. Đã viết `paper/sections/03_data.tex` (mục Volve), `06_experiments.tex` (mục 6.5, bảng `tab:volvegd`, `tab:volveall`, `tab:volvesens`), `07_discussion.tex`, `00_abstract.tex`, `01_introduction.tex` và `08_conclusion.tex`. Bài build sạch, 42 trang. Tên bài chưa đổi. Còn thiếu: citation dữ liệu Volve và hình Volve (tùy chọn).
- **Exploratory P4x (post hoc, không claim):** khai báo trước ở `docs/research/p4-exploratory.md` (02:40 UTC, trước mọi lần train P4x). Code ở `exploratory/`, output ở `outputs/p4x/`, không đụng `ml_porosity/`, `scripts/` hay `outputs/p4/`. V0 tái lập `outputs/p4/summary/metrics.csv` trong 1,8e-15 (60 dòng); trajectory train lại trùng bitwise. Đang chạy V1a (trend vận tốc PSDM + residual), V1b, V2a (CNN-GRU 8 kênh) và V2b (Conv1d tuyến tính, 83 tham số), tổng 921 job. Mọi biến thể được chọn sau khi thấy nhãn test của P4, nên chỉ báo cáo như quan sát mô tả, không đổi G-D hay kết luận của bài (mục 10).
- **Commit cùng ngày (ý 25):** code P4 (`ml_porosity/volve/`, `ml_porosity/data/deviated.py`, `volve_wells.py`, scripts 23–25, `run_p4.sh`, test), `configs/protocol_volve.*` (khóa), các chỉnh sửa paper và docs.
22. **Pivot 1 kích hoạt: bài lý thuyết + benchmark; dời hạn sang 14/11/2026 (29/10/2026; commit cùng ngày, ý 25):**
- **Căn cứ.** Sau G-C và G-D, phần bằng chứng đứng được là lý thuyết (Mệnh đề 1 khớp trong 1%; Mệnh đề 2 và H4) và benchmark synthetic P2r (H2a, H2b, nhánh σ_a). Hai field test không có lực phân biệt: trên F3 chênh giữa phương pháp 0,016 p.u. so với 0,13 p.u. giữa seed; trên Volve hằng số thắng mọi mạng. Phân tích đầy đủ, vấn đề tồn đọng (T1–T10, S1–S10) và kế hoạch ở `docs/research/pivot-theory-benchmark.md`. Khảo sát dataset field public ở `docs/research/field-dataset-survey.md`: chưa có dataset nào xác nhận đủ 7 tiêu chí (điểm nghẽn là checkshot ở giếng test); Teapot Dome và Groningen là ứng viên cần kiểm kê, không làm trong bài này.
- **Quyết định** (người dùng chốt ý 1 và 5; agent chốt ý 2–4 theo bằng chứng): (1) mức B, hạn mới **thứ 7, 14/11/2026**; ngưỡng và luật của mọi gate không đổi. (2) S2 misspec **bắt buộc**, phạm vi hẹp: ba trục (rock physics sai hệ số; wavelet sai pha và băng thông; σ_b / prior drift sai) × regime R10, Rm5 × c = 1 × N ∈ {4, 16}, realization 8–15, dev trên 902–905, tập phương pháp Oracle, B3c-R, B3d-Sa, M2-Sa; khóa trong `configs/protocol_bench.yaml` trước lần chạy đầu; nếu đến 10/11 chưa xong thì bài gọi là "controlled synthetic study". (3) T2 là **exploratory**, chạy trên realization 8–15 với bank P2r đã có, khai báo trước ở `docs/research/t2-mechanism.md`; trong bài là mechanism analysis kèm Mệnh đề 3 (*ghi chú 29/10: đánh số lúc lập kế hoạch; trong bài, giả thuyết tái đăng ký ngầm là Nhận xét 1, còn Mệnh đề 3 của bài là hai cấu trúc sai số của tie*), không confirmatory; không sinh realization 16–23 cho T2. (4) Venue chính *Computers & Geosciences*, dự phòng *Geophysical Prospecting*. (5) **Bỏ hẳn P4x.**
- **P4x.** Job `exploratory/run_p4x.sh` (cuda:0, 8 worker) ở 560/921 lúc 03:43 UTC khi chốt. Theo yêu cầu người dùng, job được dừng ở 670/921 (khoảng 04:05 UTC) rồi kill để trả cuda:0; còn dở V2a (195/220) và V2b (1/220), nhánh B3d-Sa và V3 chưa chạy. Một bản tổng hợp dở (`outputs/p4x/summary/`, 04:07 UTC) đã được tạo trước khi thấy quyết định này và đã bị xóa theo yêu cầu người dùng (bỏ hẳn P4x); không khởi động lại job, không chạy lại bước summarize. Kết quả không tổng hợp, không vào bài, không chạy V3. `exploratory/` và `outputs/p4x/` giữ làm hồ sơ, không xóa. Ý 21 giữ nguyên làm lịch sử.
- **Tên bài mới (làm việc):** *Label registration error in sparse-well seismic property learning: theory, a registration-aware benchmark, and the limits of field validation.* Đóng góp C1′–C4′ và dàn ý 8 mục ở tài liệu pivot mục 3.2–3.3. Claim cấm ở mục 10 giữ nguyên và thêm: không gọi là "benchmark" nếu thiếu S2; T2 và T3 không được trình bày như confirmatory.
- **Lịch mức B** ở mục 6.1. Mọi thí nghiệm mới chạy dưới `protocol_bench` khóa trước, ghi rõ là thiết kế sau khi đã thấy P2r. Không đụng `protocol_p2r`, `protocol_f3`, `protocol_volve` và kết quả của chúng; không chạy lại P3/P4.
23. **Điều kiện áp dụng C1–C4 và thử Teapot Dome (29/10/2026; exploratory; commit cùng ngày, ý 25):**
- Khai báo trước ở `docs/research/applicability-teapot.md` (băm 04:06 UTC, trước mọi phép tính; Deviation 1 = mở rộng lưới σ_ref của T3). Kết quả ở `docs/research/applicability-results.md`.
- **C1/C2 hồi cứu** (`scripts/26_applicability.py`): F3 và Volve đều trượt C1 (kỹ năng ở giếng blind trong inner fold dưới ngưỡng D2: band PCC 0,04–0,15 so với τ = 0,47), cả hai đạt C2 (σ_post trung vị 2,8 và 4,3 ms). Đúng dự đoán đã khai báo. Không đổi G-C, G-D.
- **T3 power** (`scripts/27_t3_power.py`): lợi thế M2-Sa ở D2 (band RMSE thấp hơn 8–20%) mất hẳn khi reference chấm điểm lệch khoảng 4 ms. Với sign test α = 0,05, power 0,8 cần 5–18 giếng test nếu σ_ref = 0; với σ_ref ≥ 1,5 ms thì không còn ô Rm5 nào đạt khi n ≤ 40. Luật k-of-n không phải phép kiểm, không dùng.
- **T0 Teapot: trượt.** Chỉ có 4 bảng TD, trong đó 2 suy từ synthetic, 1 nguồn mập mờ, 1 VSP nông (≤ 2335 ft). Như vậy có tối đa 2 giếng TD độc lập, trong khi cần ≥ 3 cho C3 cộng 11–18 cho C4. Dừng Teapot theo cây §4; **bài giữ Pivot 1** (lý thuyết + benchmark). T3 và C1–C4 vào bài dưới dạng phân tích exploratory về điều kiện cần cho một field test có lực phân biệt (pivot T3), không phải claim.
- **Pilot P-a Teapot (Deviation 2, theo yêu cầu người dùng "lấy 1 tập nhỏ triển khai thử rồi mới chốt"): trượt.** Thay checkshot bằng knot horizon–top (Carlile ↔ CRLL, KF2 ↔ F2WC) ở 37 giếng dev (inline ≤ 200), không mở porosity. Hình học và pick đều tốt, nhưng σ̂_knot = 6,75 ms (CI 90% 4,1–9,4) so với ngưỡng 1,5 ms; riêng phần vi sai cũng đã 2,5–2,8 ms. **Dừng Teapot hẳn; giữ Pivot 1.** Chi tiết ở `docs/research/applicability-results.md`; script `scripts/29_teapot_pilot.py`.
24. **Viết mức A xong sớm (29/10/2026; commit cùng ngày, ý 25):** A1–A5 của tài liệu pivot (mục 4.1) làm trong ngày 29/10 thay vì 30–31/10. Bản nháp `paper/` theo khung Pivot 1 biên dịch sạch (55 trang sau lượt tự sửa A6, không còn tham chiếu hỏng). Không có lần chạy GPU nào; mọi số mới là post hoc trên output đã lưu, không đổi số nào đã đăng ký và không dùng để chọn gì.
- **Lý thuyết (mục 4 của bài; chứng minh ở Phụ lục A).** Thêm Mệnh đề 3 (hai cấu trúc sai số của tie: classical làm mờ predictor và nới phương sai học được; Berkson làm sắc và thu hẹp nó; tie là trung bình posterior có cấu trúc Berkson), Mệnh đề 4 (bank hiệu chỉnh có cực tiểu quần thể của huấn luyện trên nhãn thật; lợi ích quần thể so với nhãn điểm là **bậc bốn** theo sai số tie), Hệ quả 3 (hai mode ±Δ/2: hệ số truyền đổi dấu ở 1/(2Δ) < |f| < 3/(2Δ)), Nhận xét 1 (λ > 0 là tái đăng ký ngầm), công thức ρ* và đoạn "Finite samples" (heuristic: sai số nhãn bậc một, phương sai có điều kiện đổi ở bậc hai, nên với ít giếng hiệu ứng mẫu hữu hạn có thể lấn bias quần thể), Mệnh đề 5 (coverage qua tỉ số phân tán ξ; T4 cũ gọi là "Mệnh đề 4"), Mệnh đề 6 và Hệ quả 4 (chấm điểm với tham chiếu lệch: bias phụ thuộc phương pháp, không giảm khi thêm giếng; dấu của lợi thế đo được chỉ đúng khi σ_ref < σ/√2). Bản tiếng Việt ở `docs/theory.md` mục 6.
- **Sửa cách đọc cận 1/B(σ_post).** Đây là ρ* dưới cấu trúc (a) với sai số Gauss, tính bằng dự đoán của Oracle thay cho m (trong bài gọi là 1/B_a). Khi σ_post vượt mép 6 ms của lưới B, `np.interp` trả 1/B(6 ms) = 0,634, nên cận thật thấp hơn (R10tb c = 2: 0,481 tại σ_post).
- **Tự sửa cùng ngày (A6).** Bản trước của ý trên có hai nhận định. Thứ nhất, hai cấu trúc chỉ khác một hệ số e^{4π²σ²f²} < 1,17 (|f| ≤ 25 Hz), nên cấu trúc gần như không đổi ρ*. Thứ hai, lợi ích của bank vượt cận quần thể (7/8 ô ở σ_post, 6/8 ở sai số warp). Nhận định thứ nhất sai, nhận định thứ hai phụ thuộc cấu trúc. Lý do: méo bậc bốn có trọng số f⁴, nên nó nằm ở 67–72 Hz, dù 71–73% công suất kết hợp với nhãn nằm dưới 25 Hz. Ở đó tích phân (b) bằng 1,5–1,7 lần (a) tại σ = 1,5 ms, 2,1–2,6 lần tại 2 ms và 3,3–4,6 lần tại 2,5 ms.
- `scripts/31_p2r_posthoc.py` được viết lại. Script đọc thêm npz dự đoán Oracle, chạy khoảng 6 phút và tái lập số đã đăng ký với sai lệch tối đa 4e-16. Nó tính cận (b) bằng cách làm sắc dự đoán Oracle tại đúng độ rộng của từng ô. Hai biến thể hạn chế khuếch đại nhiễu: giữ hệ số ở giá trị 60 Hz, và dùng phổ chéo với nhãn thật.
- Kết quả ở N = 16, 8 ô rộng. Cận (a): vượt ở 7/8 ô tại σ_post và 6/8 tại sai số warp; với phổ chéo là 5/8 và 3/8. Cận (b): vượt ở 3/8 tại σ_post với cả ba ước lượng (R0, R0h, R10tb ở c = 1; lề của R0h và R10tb < 0,004, nằm trong CI 95%). Tại sai số warp: 0/8 với plug-in, 1/8 (R0 c = 1) với hai biến thể.
- Vì vậy **không claim lợi ích vượt cận**. Bài thêm cột 1/B_b (post hoc) vào Bảng tab:h2b.
- Oracle tốt hơn B3d-Sa 7–8% ở R0, R0h, Rm5 (c = 1, N = 16). Tỉ số này dưới cận (a) ở mọi ô, dưới cận (b) ở 3–4 ô tại σ_post và 1–2 ô tại sai số warp. Ở c = 0, mọi cận nằm trong 0,4% quanh 1, nhưng Oracle vẫn tốt hơn 1–3% (sai số warp SMC 0,2–0,7 ms). Hai bên khác cả số vòng lặp (500 và 250).
- M2-Sa đóng 27–46% khoảng cách B3d-Sa–Oracle ở c = 1 (39–65% ở c = 2), và **không ô rộng nào ở N = 16 đạt mức Oracle**.
- T2 đổi câu hỏi thành: còn lợi ích nào vượt hiệu chỉnh quần thể của cấu trúc Berkson không. Test (iv), kiểm hiệp phương sai của offset, quyết định cận nào áp dụng.
- **T4** (`scripts/30_t4_coverage.py` → `outputs/t4/`; post hoc, mô tả): mọi ensemble quá hẹp (ξ = 0,19 cho Oracle, tối đa 0,66 cho B5). Thứ tự coverage đi theo **số vòng lặp huấn luyện** ngang với chất lượng nhãn (B3c-R train 500 vòng có cùng ξ với B3d-Sa ở 250; trên dev P2, coverage90 của Oracle giảm 0,47 → 0,23 → 0,10 khi tăng 125 → 500 → 2000 vòng). Ở P2r số vòng lặp và nguồn nhãn trộn lẫn, nên phần (b), (c) của Mệnh đề 5 chưa được kiểm. Không claim calibration.
- **T3 trong bài** (mục 6.5, exploratory): điểm giao của tỉ số trung vị ở N = 16 là 3,6–4,3 ms, cùng thứ tự và cách σ/√2 của Hệ quả 4 (3,0; 4,1; 5,1 ms) không quá 1 ms. N* của sign test: 5–18 giếng với tham chiếu chính xác (5/6 ô); 11–30 giếng ở 1 ms (4 ô); ở 2 ms chỉ R0 còn trong 40 giếng; từ 3 ms không ô nào. Luật k-of-n không phải phép kiểm (đạt với xác suất 0,31 khi n = 4 và 0,11 khi n = 6 nếu không có khác biệt thật).
- **Cấu trúc bài.** Chi tiết F3 và Volve chuyển sang Phụ lục B (`paper/sections/B_field.tex`); thân bài giữ mục phạm vi ngắn (6.6) với bốn điều kiện C1–C4 và Teapot. Related work thêm đoạn label noise / errors-in-variables (Berkson 1950, Fuller 1987, Carroll và cộng sự 2006, Frénay và Verleysen 2014, Song và cộng sự 2023, Mnih và Hinton 2012 (đã đọc toàn văn), Balakrishnan 1962 (chỉ có metadata, trích cho phát biểu chung)) và một dòng Mnih và Hinton trong bảng định vị; câu định vị nói rõ các thành phần không mới. Abstract 292 từ (sau A6), từ khóa, highlights (`paper/highlights.txt`, 5 ý ≤ 85 ký tự), tên bài Pivot 1 kèm TODO đổi "benchmark" thành "controlled synthetic study" nếu S2 không kịp, intro bốn đóng góp C1–C4 mới, kết luận viết lại, các mục khai báo của C&G để TODO (tác giả phải tự viết khai báo dùng AI tạo sinh). Hình `p2r_h2b.pdf` vẽ lại, chỉ đổi nhãn trục thành "population bound".
- **Rủi ro độ dài (mới).** Theo bản tóm tắt tìm kiếm của trang Guide for Authors của C&G (trang chính thức trả 403, chưa kiểm trực tiếp), Research Article tối đa khoảng 5.500 từ (không tính abstract, từ khóa, highlights, tài liệu tham khảo, chú thích hình và bảng), abstract ≤ 300 từ. Thân bài hiện khoảng 14.750 từ (mục 1–8, đếm thô sau A6, không tính công thức, float và hộp TODO; 15.036 nếu tính hộp TODO). Phải kiểm giới hạn trên trang chính thức và làm lượt rút gọn (mục 6.1, ngày 30–31/10: chuyển chứng minh, chi tiết Thí nghiệm 1 và H1, phụ lục field sang Supplementary) hoặc cân nhắc lại venue. Nếu không rút được, *Geophysical Prospecting* (dự phòng) cần kiểm giới hạn riêng. *(Cùng ngày: người dùng bỏ lượt rút gọn, xem ý 25.)*
- **Còn mở.** Bib cho dữ liệu F3 và Volve chưa có; câu "field protocols were committed only after their runs" ở mục 6 chỉ đúng khi `configs/protocol_volve.*` được commit (đã commit cùng ngày, ý 25); T2 phải khai báo ở `docs/research/t2-mechanism.md` trước 1/11. Bản khai báo phải ghi rằng các tỉ số post hoc (Oracle/B3d-Sa, M2-Sa/B3d-Sa) và mọi cận (a), (b), b60, phổ chéo, tại σ_post và tại sai số warp, đã được xem ngày 29/10.
25. **Bỏ lượt rút gọn độ dài; commit và push (29/10/2026).**
- **Quyết định của người dùng:** bỏ lượt rút gọn độ dài cho venue (trước đó dự kiến 30–31/10: kiểm giới hạn trên Guide for Authors của C&G, chuyển chứng minh, chi tiết Thí nghiệm 1, H1 và phụ lục field sang Supplementary). Rủi ro độ dài vẫn ghi ở R9 (thân bài khoảng 14.750 từ, đếm thô, so với khoảng 5.500 từ theo nguồn thứ cấp), chưa có biện pháp. Ngày 30–31/10 còn: trích dẫn dataset F3 và Volve; còn lại là dự phòng.
- **Commit và push lên `main`** (theo yêu cầu người dùng): toàn bộ thay đổi của ý 20–24 (code P4, `configs/protocol_volve.*`, scripts 23–31, `run_p4.sh`/`.ps1`, test, `docs/research/` mới, bản ghi P4x ở `exploratory/` và `docs/research/p4-exploratory.md`, `.gitignore`, bài và tài liệu). Tag `protocol-volve` đặt trên commit này: hash code tính lại từ cây commit khớp `configs/protocol_volve.lock.json` (`c0befaa4…`). Giao thức Volve vì vậy được commit sau lần chạy, đúng như câu ở mục 6 của bài. 190 test pass, 1 skip. `logs/*.out` vẫn không theo dõi, như trước; `data/Teapot/` bị gitignore.

View File

@@ -0,0 +1,65 @@
# Kết quả C1, C2 (hồi cứu) và T3 (power) — 29/10/2026
Khai báo trước: `applicability-teapot.md` (SHA-256 trong `applicability-teapot.sha256`, Deviation 1 = mở rộng lưới σ_ref). Exploratory, không confirmatory.
## C1, C2 (`scripts/26_applicability.py` → `outputs/applicability/verdict.json`)
Ngưỡng từ 19 ô D2 đạt H2a: τ_band_pcc = 0.468, τ_R² = 0.053.
| Dataset | R² in | band PCC in | skill so với hằng số | C1 | σ_post trung vị | C2 |
| --- | --- | --- | --- | --- | --- | --- |
| F3 lowo | 0.039 | 0.146 | 0.108 | trượt | 2.83 ms | đạt |
| Volve lowo | −0.990 | 0.133 | −0.089 | trượt | 4.33 ms | đạt |
| Volve slot | −0.986 | 0.042 | −0.105 | trượt | 4.33 ms | đạt |
Đúng dự đoán đã khai báo: cả hai trượt C1 (kỹ năng mạng), không phải C2 (độ rộng posterior).
## T3 (`scripts/27_t3_power.py` → `outputs/t3/`)
Luật dùng được là sign test một phía α = 0.05; luật k-of-n (k = ⌈0.75n⌉) không phải phép kiểm (ở p = 0.5 vẫn qua 31% với n = 4) và power giảm theo n, nên bỏ.
N* (power ≥ 0.8, sign test, n ≤ 40) theo sai số đăng ký của reference chấm điểm σ_ref:
| Ô | 0 | 0.5 | 1 | 1.5 | 2 | ≥ 3 ms |
| --- | --- | --- | --- | --- | --- | --- |
| R0, N=4 | 5 | 8 | 11 | 13 | 23 | — |
| R0, N=16 | 5 | 8 | 13 | 18 | 37 | — |
| R10, N=4 | — | — | — | — | — | — |
| R10, N=16 | 5 | 5 | 11 | 23 | — | — |
| Rm5, N=4 | 18 | 30 | — | — | — | — |
| Rm5, N=16 | 11 | 16 | 30 | — | — | — |
(— : không đạt 0.8 với n ≤ 40.) Tỉ số band RMSE trung vị M2-Sa / đối thủ: 0.80–0.92 ở σ_ref = 0, về ≈ 1 ở 4 ms, > 1 ở 8 ms.
Hệ quả cho T0 Teapot (C4, giả định mức Rm5 như §4): cần khoảng 11–18 giếng test có reference TD độc lập với sai số ≲ 0.5 ms, cộng ≥ 3 giếng TD ngoài test cho C3. Với σ_ref ≥ 1.5 ms thì không còn ô Rm5 nào khả thi; với σ_ref ≥ 3 ms thì không ô nào khả thi. Sai số bulk shift datum/statics giữa checkshot và seismic cũng tính vào σ_ref.
## T0 Teapot Dome (29/10/2026) — trượt, dừng Teapot
Nguồn: `rmotc.tar` (TDR, doi:10.18738/T8/21WDU8), giải nén ở `data/Teapot/raw/rmotc/` (1,7 GB; 1.210 file LAS, 3D `filt_mig.sgy` 345 × 188 inline/crossline, bin 110 ft, 2 ms, datum 5500 ft, Vc = 9000 ft/s). Kiểm kê chỉ đọc header, độ phủ curve và tài liệu kèm theo; không so nhãn với seismic.
- **Time-depth độc lập.** Nguồn TD duy nhất là `Seismic/CD files/TimeDepthTables.xls` ("Select time/depth tables" theo readme), 4 giếng:
- 25-1-X-14 và 67-1-X-10: "From synthetic log", tức suy ra từ tie synthetic. Không độc lập; cùng loại với marker của F3.
- 48-X-28: "From Synthetic Seismogram", 32 mức (TWT, TVD). Nguồn không rõ là checkshot hay tie synthetic; tính rộng rãi là độc lập.
- 35-1-X-10: VSP thật ("FROM Paper VSP log"), nhưng chỉ tới 2335 ft MD (≈ 492 ms TWT), nông hơn 1st Wall Creek và mọi tầng chứa chính.
- **LAS.** Không file nào có curve thời gian hay checkshot (các dòng khớp `CS` là casing size / cable speed). Tần suất curve: RHOB 515, DPHI 301, NPHI 134, DT 82 file.
- **So với ngưỡng §4.** C3 cần ≥ 3 giếng TD độc lập ngoài tập test; C4 (mức Rm5, `outputs/t3/nstar.csv`) cần 11–18 giếng test có reference TD sai ≲ 0,5 ms. Teapot có tối đa 2 giếng TD độc lập tính rộng rãi, và chỉ 1 nếu tính chặt (VSP nông). Tổng 2 < 3 + 11, nên trượt cả C3 lẫn C4 trước khi phải mở bất kỳ log nào. Ngoài ra, các bảng TD dùng datum KB/ASL còn seismic dùng datum phẳng 5500 ft, nên bản thân việc quy đổi datum đã đưa thêm sai số vào σ_ref.
- **Quyết định (theo cây §4, đã khai báo trước).** Dừng Teapot ở T0. Bài giữ khung lý thuyết + benchmark (Pivot 1). Discussion nêu dữ kiện kiểm kê này như một ví dụ cho thấy dataset field public hiếm khi thỏa C3–C4. Không thử dataset field khác (§0: không "chọn dataset cho đến khi đạt").
Kiểm kê LAS chi tiết: `scripts/28_teapot_inventory.py` → `outputs/teapot/inventory/`.
## Pilot P-a Teapot (29/10/2026, Deviation 2) — trượt, dừng Teapot hẳn
Khai báo: Deviation 2 trong `applicability-teapot.md` (băm v2 07:11:29 UTC, trước mọi phép tính σ_knot; bản sao `outputs/applicability/declaration_v2.md`). Script `scripts/29_teapot_pilot.py` → `outputs/teapot/pilot_pa/`. Chỉ dùng 37 giếng dev (inline chiếu ≤ 200); không đọc giá trị porosity; không tính gì trên 115 giếng test.
- **Hình học đạt.** Phép chiếu affine XY → inline/xline khớp header SEG-Y (sai số tối đa 0,013 bin). Cả hai horizon có pick bilinear ở 37/37 giếng dev (độ phủ 100%). Pick nằm đúng cực trị cùng cực tính của trace: Carlile 37/37 và KF2 36/37 lệch không quá 2 ms.
- **σ̂_knot (M1, quyết định) = 6,75 ms** (CI 90% bootstrap theo giếng: 4,1–9,4; ước lượng robust 1,4826·MAD = 5,0; Carlile 6,0, KF2 7,4). Ngưỡng σ_tol = 1,5 ms. **Trượt.**
- **Cấu trúc sai số (chẩn đoán, không quyết định).** Phần dư của hai horizon tại cùng giếng tương quan 0,85. Thành phần chung (bulk shift theo giếng) có SD 6,6 ms và không tương quan với giếng lân cận (hệ số −0,23 ở khoảng cách khoảng 9 bin ≈ 1.000 ft). Như vậy đây không phải biến thiên vận tốc ngang mượt mà M1 có thể đã quy nhầm thành sai số; nó giống sai số riêng từng giếng (KB/datum, residual statics, pick top). Thành phần vi sai (dạng stretch): 2,8 ms; M2 (sonic, 5 giếng): 2,5 ms.
- **Kết luận độc lập với cách ước lượng.** Mọi ước lượng (M1 6,75; robust 5,0; hệ số hai knot 5,3; chỉ phần vi sai 2,5–2,8) đều vượt 1,5 ms, và vượt cả 2 ms (ngưỡng nếu giả định mức R0 lạc quan hơn). Theo T3, với σ_ref ≥ 3 ms không ô D2 nào có power 0,8 ở n ≤ 115 trừ R0 với N_train = 4.
- **Quyết định (cơ học theo Deviation 2).** Dừng Teapot hẳn, không có P-b. Bài giữ Pivot 1. Dữ kiện dùng được cho phần "limits of field validation" (exploratory): ngay cả ở dataset field public có nhiều kiểm soát nhất mà nhóm biết (hàng trăm giếng có top cùng horizon 3D đã minh giải), sai số TD độc lập khoảng 5–7 ms (bulk) và 2,5–2,8 ms (vi sai), tức gấp 2–5 lần dung sai mà một field test có lực phân biệt cần (≈ 1–1,5 ms).
## Dùng trong bài (29/10/2026)
- **T3** → bài mục 6.5 (*Detectability of a gain at blind wells*, exploratory), bảng `tab:t3`. Hệ quả 4 (bài mục 4.5: dấu của lợi ích đo được đúng với dấu thật chỉ khi σ_r < σ/√2) dự báo điểm cắt σ/√2 = 3,0/4,1/5,1 ms; tỉ số band RMSE trung vị cắt 1 ở 3,6–4,3 ms (ba ô N = 16). Bài ghi rõ phép phân tích được khai báo trước khi chạy nhưng sau khi cả hai field gate trượt, và nêu Deviation 1.
- **C1–C4 và phép kiểm hồi cứu F3, Volve** → bài mục 6.6, đoạn *Neither test could have detected the effect*: ghi là post hoc, với ngưỡng C1, C2 lấy cơ học từ Thí nghiệm 2 (P2r).
- **Teapot T0 và pilot P-a** → bài mục 6.6, đoạn *Limits of field validation*: ghi là post hoc, exploratory; dùng 152 giếng, 4 bảng TD, tối đa 2 giếng có reference độc lập, σ̂_knot 6,75 ms (CI 90% 4,1–9,4) so với 1,5 ms.
- Nguồn số liệu từng câu: `paper/README.md`. Quyết định dừng Teapot: `docs/plan.md` §12 ý 23; `report.html` D-11.

View File

@@ -0,0 +1,106 @@
# Điều kiện áp dụng C1–C4 và nhánh thử Teapot Dome (P6)
Ngày viết: **29/10/2026**. Trạng thái: **khai báo trước** (pre-declaration). Tài liệu này được viết và băm SHA-256 (`applicability-teapot.sha256`) **trước** khi tính bất kỳ điều kiện nào trên F3 hay Volve, và trước khi có bất kỳ file dữ liệu Teapot Dome nào trên máy. Không sửa sau khi băm; thay đổi phải ghi thành mục "Deviation" có ngày ở cuối tài liệu.
Liên quan: `docs/plan.md` §12 ý 22 (Pivot 1), `docs/research/pivot-theory-benchmark.md` (T3), `docs/research/field-dataset-survey.md` (Teapot Dome, tiêu chí Q1–Q7).
---
## 0. Mục đích và giới hạn trung thực
Người dùng đề xuất (29/10): F3 và Volve trượt vì dữ liệu; nếu một field dataset thỏa các điều kiện dữ liệu cho kết quả dương, bài có thể trở lại khung **bài phương pháp có miền áp dụng rõ**. Nếu Teapot Dome không thỏa, bài giữ khung **lý thuyết + benchmark** (Pivot 1, không đổi).
Giới hạn phải ghi nhận:
1. Người viết tài liệu này **đã thấy** kết quả test của F3 và Volve. Để hạn chế việc chọn ngưỡng theo kết quả, mọi ngưỡng của C1 và C2 được **dẫn xuất cơ học từ D2** (benchmark synthetic P2r), không chọn tự do.
2. C3 và C4 trượt ở F3 và Volve **theo cấu trúc** (không có TD độc lập đủ giếng; N = 4 và 6). Vì vậy phép kiểm hồi cứu trên F3 và Volve chỉ có nội dung phân biệt qua **C1 và C2**.
3. Toàn bộ nhánh này **thiết kế sau khi thấy G-C và G-D**. Bài phải ghi là deviation so với kế hoạch gốc, cùng loại với P2r.
4. **Không mua sắm dataset:** Teapot Dome là dataset field duy nhất được thử trong nhánh này. Nếu Teapot trượt ở bất kỳ bước nào, bài này không thử thêm dataset field nào khác.
---
## 1. Định nghĩa C1–C4
Mọi điều kiện tính **không dùng nhãn của giếng test**: chỉ dùng giếng train, inner fold, posterior tie và TD độc lập ngoài tập test.
### C1. Mạng có kỹ năng ở giếng blind, trong miền đã kiểm chứng của D2
- **Đại lượng.** Với mỗi outer fold u, lấy point competitor m*(u) được chọn theo inner-validation MSE (như protocol của dataset đó). Với mỗi inner validation well v ∈ T_out(u), lấy dự đoán tại v của mô hình train trên T_out(u) ∖ {v}, tại budget mà protocol đã chọn cho (u, m*, seed); trung bình 5 seed (mean của μ). So với nhãn reference chính của v (giếng train, nên không phải nhãn test).
- `r2_in`: R² (point_metrics, toàn dải).
- `band_pcc_in`: PCC băng. F3: `band_metrics` với f_c của protocol (6 Hz). Volve: `desc_band` (run ≥ 16 mẫu, như protocol_volve, chỉ mô tả).
- `ss_const`: 1 − RMSE_net / RMSE_const, với RMSE_const của hằng số bằng trung bình nhãn các giếng T_out(u) ∖ {v}.
- Gộp: trung bình không trọng số trên mọi cặp (u, v).
- **Ngưỡng (dẫn xuất từ D2, `outputs/p2r/`).** Tập ô xác nhận = các ô H2a có `cell_pass = True` trong `outputs/p2r/summary/h2a.csv` với c = 1, regime ∈ {R10, R0, Rm5}, N ∈ {4, 16}. Trong mỗi ô, lấy best competitor của ô đó (cột `best`), tính trung bình `band_pcc` và `r2` trên mọi (realization, seed, giếng test) từ `outputs/p2r/train/<regime>/results.csv`.
- τ_pcc = **min** trên tập ô xác nhận của band_pcc trung bình.
- τ_r2 = **min** trên tập ô xác nhận của r2 trung bình.
- **C1 đạt** nếu `band_pcc_in ≥ τ_pcc` **và** `r2_in ≥ τ_r2` **và** `ss_const > 0`.
- Lý do: ngoài khoảng kỹ năng mà D2 đã xác nhận hiệu ứng, benchmark không nói gì; một field test ở đó là ngoại suy. Ghi chú: inner model train trên ít giếng hơn và chấm bằng reference có sai số, nên `*_in` thiên thấp; đây là hướng bảo thủ, chấp nhận.
### C2. Posterior tie đủ rộng (chỉ cho claim RML so với nhãn trung bình posterior)
- **Đại lượng.** σ_post của posterior SMC trên giếng train (định nghĩa `protocol_p2r` notes.sigma_post; không dùng nhãn), trung vị trên giếng train của mọi tập train, tại σ_a chính của dataset.
- **C2 đạt** nếu σ_post ≥ **1.5 ms** (ngưỡng "wide" của `protocol_p2r` H2b).
- C2 chỉ điều kiện hóa claim kiểu H2b (M2-Sa so với B3d-Sa). Claim chính (M2-Sa so với point tie tốt nhất, kiểu H2a/G-C) không cần C2, vì H2a đạt cả ở ô hẹp (c = 0) trên D2.
### C3. σ_a xác định được
- **Đại lượng.** Có TD độc lập (checkshot hoặc VSP, không dùng để dựng tie train) ở **≥ 3 giếng không thuộc tập test**. σ̂_a = SD của (thời gian marker theo tie dùng để train − thời gian theo TD độc lập tại cùng độ sâu marker), gộp theo giếng; khoảng tin cậy 90% bằng bootstrap theo giếng.
- **C3 đạt** nếu đủ ≥ 3 giếng **và** CI 90% nằm trong [σ̂_a / 2, 2 σ̂_a].
- Lý do: nhánh σ_a của P2r cho thấy lợi ích H2a mất khi σ_a sai ×0.5 hoặc ×2.
### C4. Đủ power
- **Đại lượng.** N* = số giếng test nhỏ nhất sao cho xác suất luật G-E đạt ≥ **0.80**, tính bằng T3 (mô phỏng trên dự đoán đã lưu của P2r, mục 3), với: (a) regime D2 có band PCC của competitor gần nhất với `band_pcc_in` của field (nếu thấp hơn mọi regime thì dùng regime thấp nhất); (b) sai số reference σ_ref = 0 nếu mọi giếng test có TD độc lập, ngược lại σ_ref = σ̂_a của C3.
- **C4 đạt** nếu số giếng test khả dụng (có nhãn porosity trong cửa sổ seismic và đạt QC) ≥ N*.
---
## 2. Phép kiểm hồi cứu trên F3 và Volve (bước R)
- Tính C1, C2 trên F3 (`outputs/p3/`) và Volve (`outputs/p4/`, scheme lowo và slot) bằng `scripts/26_applicability.py`. C3, C4 ghi theo dữ kiện đã biết (F3: 0 giếng TD độc lập, N = 4; Volve: 2 giếng có checkshot, N = 6) và theo N* của T3.
- **Dự đoán đăng ký trước:** cả F3 và Volve trượt **C1**.
- Đọc kết quả:
- Cả hai trượt C1: nhất quán với "trượt vì dữ liệu" (không chứng minh được, vì là hồi cứu).
- Một dataset **đạt C1** (và C2 nếu áp dụng): lập luận "trượt vì dữ liệu" **yếu đi** cho dataset đó; bài không được dùng C1–C4 để giải thích kết quả âm của nó. Nhánh Teapot vẫn có thể chạy, nhưng claim sẽ hẹp hơn.
---
## 3. T3 (power) — exploratory, mức B của Pivot 1
- Nguồn: `outputs/p2r/train/<regime>/cells/*.npz` (y_true theo warp thật, μ theo phương pháp và seed, 8 giếng test mỗi realization).
- Reference chấm điểm mô phỏng: y_true lấy tại t + s(t), với s(t) là warp trơn ngẫu nhiên có SD σ_ref ∈ {0, 2, 4, 8} ms (thành phần hằng + tuyến tính).
- Với mỗi ô (regime, c = 1, N), mỗi giếng: chỉ báo "M2-Sa có band RMSE thấp hơn best competitor của ô" theo reference mô phỏng; trung bình seed như ensemble.
- Từ chỉ báo theo giếng và độ tương quan trong realization (ICC), tính P(luật đạt | n) cho n = 4…40 theo beta-binomial cho hai luật ứng viên: (a) k-of-n với k = ⌈0.75 n⌉ (G-C 3/4, G-D 5/6); (b) kiểm định dấu một phía α = 0.05 trên chỉ báo theo giếng.
- Đầu ra: đường cong N*(regime, σ_ref, luật), `outputs/t3/`. Đây là phân tích giải thích, không confirmatory.
---
## 4. Cây quyết định cho Teapot Dome
| Bước | Việc (không nhìn nhãn test so với dự đoán) | Đạt → | Trượt → |
| --- | --- | --- | --- |
| **T0. Kiểm kê** | Tải `rmotc.tar` (TDR, doi:10.18738/T8/21WDU8, CC0). Đếm: giếng trong footprint 3D có density/neutron trong cửa sổ seismic; có sonic; có checkshot/VSP; giếng nghiêng; formation tops/horizon; chất lượng log | C3 khả thi (≥ 3 giếng TD độc lập ngoài test) **và** số giếng test khả dụng ≥ N* (T3, giả định mức Rm5) | **Dừng Teapot.** Bài giữ khung lý thuyết + benchmark; Discussion nêu dữ kiện kiểm kê |
| **T1. Dev** | Chia giếng thành **dev** (thiết kế, C1, C2, C3) và **test** (khóa, không mở nhãn tới G-E) theo luật không gian chốt trước khi mở log. Tính C1, C2, C3 chỉ trên dev | C1 và C3 đạt | **Dừng Teapot.** Báo cáo "Teapot nằm ngoài miền áp dụng của benchmark" như một kết quả; khung lý thuyết + benchmark |
| **T2. Khóa** | Viết `configs/protocol_teapot.yaml` (+ `.sha256`, `.lock.json`): G-E (luật chọn theo power của T3), N, tập phương pháp (tối thiểu B3 point ties, B3d-Sa, M2-Sa), σ_a từ C3, reference chấm điểm, f_c | Đã khóa | — |
| **T3. Chạy** | Nested LOWO trên tập test, như P3/P4 | G-E đạt | G-E trượt (dù C1–C4 đạt) |
| **Bài** | | **Khung phương pháp + lý thuyết + miền áp dụng:** "khi C1–C4 đạt, RML cải thiện; F3 và Volve nằm ngoài miền áp dụng" (claim cỡ 1 dataset) | **Khung lý thuyết + benchmark, mạnh hơn:** kết quả âm đủ power, RML không chuyển sang field ngay cả trong miền áp dụng |
Không đổi trong mọi nhánh: G-C, G-D và kết luận của chúng; H3 bị bác bỏ (không claim calibration); sự phụ thuộc vào σ_a là giới hạn của phương pháp.
**Mốc thời gian (theo hạn 14/11 ở plan §6.1; ngày có thể dời, ngưỡng thì không):** T0 xong trước **2/11**; nếu G-E chưa có kết quả trước **10/11** thì coi như không làm được trong bài này và giữ khung lý thuyết + benchmark.
---
## Deviation
Bản băm gốc (v1) được giữ nguyên byte ở `outputs/applicability/declaration_v1.md` (SHA-256 khớp `applicability-teapot.sha256`). Mọi thay đổi sau v1 chỉ nằm trong mục này.
1. **(29/10/2026, sau lần chạy T3 đầu tiên) Lưới σ_ref mở rộng** từ {0, 2, 4, 8} ms thành {0, 0.5, 1, 1.5, 2, 3, 4, 8} ms. Lý do: lần chạy đầu cho thấy xác suất M2-Sa thắng ở một giếng giảm từ 0.81–0.97 (σ_ref = 0) xuống 0.65–0.82 (2 ms) và về khoảng 0.5 (4 ms), nên ngưỡng dung sai nằm giữa 0 và 2 ms, nơi lưới v1 không có điểm. Kết quả lưới v1 giữ ở `outputs/t3_grid_v1/`. Không đổi luật, ngưỡng hay dữ liệu; chỉ thêm điểm lưới. T3 vẫn là exploratory.
2. **(29/10/2026, sau kiểm kê T0, trước khi mở bất kỳ nhãn porosity nào) Nguồn TD độc lập mở rộng sang knot horizon–top; pilot trên tập dev nhỏ.**
- *Lý do.* T0 cho thấy chỉ có 4 bảng TD (1 VSP nông), nên C3/C4 theo nghĩa checkshot/VSP trượt. Kiểm kê cũng tìm thấy `3DHorizons.xyz` (9 horizon đã minh giải trên khối 3D) và formation tops ở khoảng 1.000 giếng. `FormationCodes.doc` ánh xạ KF2 ↔ F2WC; Carlile ↔ CRLL (trùng tên). Mỗi cặp (thời gian horizon tại giếng, độ sâu top) là một knot TD độc lập với waveform tie. Ngưỡng, luật G-E, luật N* và giả định mức Rm5 **không đổi**; chỉ định nghĩa nguồn TD thay đổi.
- *Tập giếng.* W = giếng có tọa độ header nằm trong footprint 3D (inline/xline chiếu bằng phép affine khớp từ `3DHorizons.xyz`), có top CRLL và F2WC, và có density phủ trọn [CRLL, F2WC] (152 giếng). Cửa sổ nhãn là CRLL → F2WC. **Dev** = các giếng W có inline chiếu ≤ 200 (37 giếng, đầu nam của vòm). **Test** = phần còn lại (115 giếng). Luật này chốt từ số đếm, chưa xem giá trị log nào. Không tính gì trên giếng test (kể cả σ_knot) cho tới G-E.
- *Thiết kế field (nếu đi tiếp).* Knot **chỉ dùng để chấm điểm giếng test và để ước lượng σ_a**. Giếng train được đăng ký bằng waveform tie với prior σ_a như P3/P4; không dùng knot khi đăng ký. Nếu không làm vậy, σ_post ở giếng train co lại theo knot và câu hỏi RML biến mất. Trong bài, phần này gọi là *controlled field experiment* (giữ lại knot ở giếng train), không gọi là quy trình thực hành chuẩn. Reference TD ở giếng test là nội suy tuyến tính theo độ sâu giữa hai knot (vận tốc khoảng không đổi).
- *Pilot P-a (hôm nay, chỉ trên dev, không dùng porosity).* (i) Hình học: đọc được SEG-Y, phép chiếu XY → inline/xline khớp header, horizon khớp với SEG-Y (biên độ tại pick). (ii) Độ phủ horizon: có pick trong bán kính 1 bin tại giếng dev, hoặc nội suy được. (iii) **σ̂_knot (M1, chính)**: với từng horizon, thời gian quan sát được so với 2·z/V̂, trong đó z là độ sâu dưới datum seismic 5500 ft (= TVD − KB + 5500, TVD từ directional survey nếu có, ngược lại TVD = MD) và V̂ là trend bậc hai theo (inline, xline) của vận tốc trung bình, khớp bằng leave-one-out trên dev. σ̂_knot = SD gộp của phần dư. Đây là cận trên, vì nó gồm cả biến thiên vận tốc ngang thật. (iv) Kiểm tra phụ (không quyết định): M2 = phần dư của chênh thời gian giữa hai horizon so với 2∫DT dz ở giếng dev có sonic, chia √2; đối chiếu với bảng TD của 48-X-28 nếu giếng này có trong dev. CI 90% bằng bootstrap theo giếng.
- *Cổng P-a (cơ học).* σ_tol = σ_ref lớn nhất trên lưới T3 sao cho N*(Rm5, N_train = 16, sign test, power 0,8) ≤ số giếng test (115), tức σ_tol = 1,5 ms. Đạt nếu σ̂_knot ≤ σ_tol **và** có knot cho cả hai horizon ở ≥ 80% giếng dev. Lấy σ_ref = σ̂_knot, không nhân hệ số 0,78 của mô hình hai knot (chỉ báo như độ nhạy). **Trượt → dừng Teapot hẳn**; bài giữ Pivot 1.
- *Nếu đạt P-a → pilot P-b (chỉ dev):* dựng pipeline tie/train trên dev, tính C1 (kỹ năng blind trong dev), C2 (σ_post) và C3 (σ̂_a từ knot). Có kết quả P-b rồi mới quyết định chuyển sang T2 (khóa `configs/protocol_teapot.yaml`).

View File

@@ -0,0 +1,2 @@
ba65d9acbc9e16691a8919828345c67967980a9ccd39eac88da41cf1c07e5076 applicability-teapot.md # hashed 2026-10-29T04:06:34Z before any C1-C4 computation
21602f1397a08b6d05a02d284c2d309bfead72b3562511687cb51518bd9d7ec0 applicability-teapot.md # v2 (Deviation 2) hashed 2026-10-29T07:11:29Z before any sigma_knot computation

View File

@@ -0,0 +1,64 @@
# Khảo sát dataset public cho field test (29/10/2026)
Mục đích: tìm xem có dataset công khai nào đủ điều kiện cho một field test **có sức mạnh thống kê**, khác với F3 (4 giếng) và Volve (6 giếng). Nguồn: tra cứu web ngày 29/10/2026. Phần lớn số liệu bên dưới **chưa kiểm trên dữ liệu thật**: [W] = theo nguồn web, chưa kiểm; [KT] = đã kiểm trong repo.
## 1. Tiêu chí (rút từ bài học F3 và Volve)
| Mã | Tiêu chí | Vì sao | Bài học |
|---|---|---|---|
| Q1 | Giấy phép cho phép công bố, tải được | Bắt buộc | |
| Q2 | Seismic 3D post-stack (miền thời gian, hoặc miền sâu kèm mô hình vận tốc) phủ các giếng | Bài toán | |
| Q3 | **Đủ nhiều giếng test.** Mục tiêu sơ bộ ≥ 15–20 giếng đủ chuẩn, tốt hơn ≥ 30. Con số chính xác lấy từ T3 (`pivot-theory-benchmark.md`) | Power | F3: chênh giữa phương pháp 0.016 p.u., chênh giữa seed 0.13 p.u. |
| Q4 | Nhãn porosity **không suy ra từ sonic** (density/neutron/core) trong cửa sổ seismic | Tránh PHIE = f(DT) | F3: 3/4 giếng là hàm của DT [KT] |
| Q5 | **Time–depth độc lập** (checkshot/VSP) ở các giếng test | Tham chiếu chấm điểm không phải point tie; ước lượng σ_a (rủi ro chính của H2a) | F3: marker không phải checkshot; σ_a không nhận dạng được |
| Q6 | **Có khả năng có kỹ năng ở giếng blind**: giếng dày so với độ dài tương quan ngang; chênh mức porosity giữa giếng không trội | Không có kỹ năng thì không có power | Volve: hằng số thắng mọi mạng; PHIF chênh 8.5–17 p.u. giữa giếng [KT] |
| Q7 | Giếng đứng hoặc có trajectory | Trích nhãn đúng vị trí | Volve phải dựng trajectory từ Compass |
## 2. Ứng viên
| Dataset | Q1 giấy phép | Q2 seismic | Q3 giếng | Q4 nhãn | Q5 TD độc lập | Q6 kỹ năng | Đánh giá |
|---|---|---|---|---|---|---|---|
| **Teapot Dome (NPR-3), Wyoming** | Public domain (DOE/RMOTC), phải ghi nguồn; S3 open.source.geoscience [W] | 3D post-stack migrated, 2 ms, ~345 × 188 trace [W] | ~900 giếng có log; ~26 có cả sonic + density; Moon et al. (2016) dùng 64 giếng cho Second Wall Creek, giữ 39 làm validation [W] | Density/neutron, log cũ, cần QC [W] | **Chưa xác nhận**; một nghiên cứu tie nói không có checkshot/VSP [W] | Tốt: giếng rất dày, onshore, mục tiêu nông [W] | **Ứng viên mạnh nhất về Q3, Q6.** Yếu ở Q5 |
| **Groningen (mô hình tĩnh NAM)** | Mở trên YoDa/EPOS-NL, báo EPOS-NL, trích NAM (2020) [W] | PSDM (miền sâu), dưới muối Zechstein [W] | 371 giếng, > 6000 log, top của 12 zone Rotliegend [W] | Nhiều khả năng có density [W] | Checkshot có thể có trên NLOG, chưa kiểm [W] | Trung bình: nhiều giếng lệch theo cụm, ảnh dưới muối | **Mạnh về Q3.** Phải chỉnh bài toán sang miền sâu; định dạng Petrel/RESCUE |
| **NLOG offshore Hà Lan** (khảo sát DEF Z3FUG2012A; dự án Petrel EPOS-NL) | Tải miễn phí; điều khoản chính xác chưa kiểm [W] | DEF 6000–8000 km²; EPOS-NL có 280 cube 3D [W] | EPOS-NL: 6590 giếng, 4752 composite log [W] | Phải tự tính porosity từ RHOB | Một số giếng có TD số [KT ở F3] | Chưa biết | Trong footprint F3: 38 borehole nhưng chỉ thêm được 2 giếng dùng được, vì log bắt đầu dưới cửa sổ nông [KT]. Với DEF phải đổi sang mục tiêu sâu hơn. Cần kiểm kê |
| **Stratton (BEG), Texas** | Mở trên S3, ghi nguồn BEG [W] | 3D land, Frio fluvial, ~7.5 mi² [W] | Có log; số giếng chưa xác nhận [W] | Chưa rõ | **Có VSP** ở giếng hiệu chỉnh [W] | Tốt nếu giếng dày | Ứng viên phụ: có TD độc lập nhưng diện tích nhỏ, N chưa rõ |
| Boonsville (BEG), Texas | **Trả phí** (bản số 145 USD), điều khoản phân phối lại chưa rõ [W] | 3D, 5.5 mi² [W] | 38 giếng [W] | Chưa rõ | Chưa rõ | Tốt | Khó làm benchmark tái lập vì không tải tự do |
| Poseidon, Browse Basin | CC BY (3.0 AU hoặc 4.0, nguồn mâu thuẫn) [W] | 3D ~2900 km² (TGS MDIO trên AWS) [W] | ~8 giếng trong cube; log/VSP qua NOPIMS [W] | Có thể có | NOPIMS có VSP [W] | Kém: giếng thăm dò thưa, sâu | **Lặp lại vấn đề của Volve** (N nhỏ) |
| Taranaki, NZ (NZP&M) | Open-file [W] | Nhiều 3D (Pohokura...) [W] | Chưa xác nhận | Chưa rõ | Chưa rõ | Chưa rõ | Cần kiểm kê; chưa đủ thông tin |
| Volve đầy đủ | CC BY-NC-SA [KT] | ST10010 [KT] | 24 giếng, ~12 có D/S/N [W] (P4 dùng 6) | PHIF theo density [KT] | Chỉ 2 giếng có checkshot [KT] | **Kém** (đã chứng minh) [KT] | Không đề xuất: dữ liệu đã thấy, P4 cấm thiết kế lại, N vẫn nhỏ |
| Penobscot / Kerry | Mở | 3D | 2 / 1 giếng | | | | Loại (Q3) |
| Diskos (Na Uy) / NDR (Anh) | Thành viên đại học miễn phí (Diskos); giấy phép OGA (NDR); **không phân phối lại** [W] | Rất nhiều | Rất nhiều | | | | Không phải "public dataset": người khác không tái lập được |
| Namorado (ANP, Brazil) | Cấp cho đại học [W] | 3D chưa xác nhận | 56 giếng LAS [W] | | | | Truy cập không chắc với đơn vị ngoài Brazil |
Không tìm thấy benchmark chuẩn nào cho seismic → porosity có nhiều giếng blind dùng chung [W].
## 3. Kết luận
1. **Chưa có dataset nào được xác nhận đạt cả 7 tiêu chí.** Điểm nghẽn là Q5: dataset nhiều giếng (Teapot Dome, Groningen) chưa xác nhận có checkshot ở đủ giếng test; dataset có VSP (Stratton, Poseidon, Volve) thì ít giếng hoặc N chưa rõ.
2. **Teapot Dome** là ứng viên tốt nhất cho Q3 và Q6. Đây cũng là chỗ duy nhất có tiền lệ dùng hàng chục giếng validation. Nếu không có checkshot, vẫn có thể chấm bằng point tie, nhưng khi đó T3 phải tính cả sai số của tham chiếu.
3. **Groningen** là ứng viên thứ hai: N lớn, nhưng miền sâu và dưới muối làm bài toán khác hẳn D2/F3.
4. **Không cái nào làm kịp 31/10.** Mỗi dataset cần kiểm kê (1–2 ngày), dựng nhãn và time–depth, một protocol mới khóa trước khi chạy (P6, không đụng P3/P4), rồi mới chạy.
## 4. Đề xuất
- **Trong bài hiện tại:** không thêm field test mới. Mục "Detectability" (T3) nêu cụ thể dataset public nào có thể đạt ngưỡng N (Teapot Dome, Groningen) như một khuyến nghị có căn cứ.
- **Bước tiếp theo, nếu muốn có field test thật:**
1. Chạy T3 trước để có con số N cần thiết, thay cho mức sơ bộ 15–20 ở Q3.
2. Kiểm kê Teapot Dome (1 ngày): đếm giếng có density/neutron trong cửa sổ seismic, giếng có sonic để tie, checkshot/VSP, khoảng cách giếng, và tìm xem có checkshot trong kho RMOTC không.
3. Kiểm kê Groningen song song nếu Teapot Dome trượt Q5.
4. Nếu đạt: pre-register **dự đoán của T3** (power, tỉ lệ cải thiện kỳ vọng) trên dataset mới trước khi chạy. Khi đó field test kiểm chứng lý thuyết power chứ không chỉ kiểm phương pháp, khớp với hướng theory + benchmark.
- **Lựa chọn rẻ hơn cho trục "simulator khác":** dataset tổng hợp độc lập với D2 (SEAM Phase I có log tổng hợp [W]; Stanford VI-E). Có warp thật, nên trả lời giới hạn "cùng simulator" của benchmark (S2). Giấy phép chưa kiểm.
## Nguồn
- Teapot Dome: [ahay.org, Teapot dome dataset](https://www.ahay.org/RSF/book/tccs/welllogs/paper_html/node2.html); [SEG wiki, scavenger hunt](https://wiki.seg.org/wiki/User:Azizuddin/Scavenger_hunt); [Oil IT 2005](https://oilit.com/HTML_Articles/2005_4_22.php); [Moon et al. 2016 (KIOST)](https://sciwatch.kiost.ac.kr/handle/2020.kiost/2160)
- Stratton: [SEG wiki](https://wiki.seg.org/wiki/Stratton_3D_survey); [BEG store](https://store.beg.utexas.edu/cd-rom-sets/2120-sw0003.html)
- Boonsville: [BEG store SW0007](https://store.beg.utexas.edu/seminars-and-workshops/2216-sw0007.html)
- Poseidon: [AWS Registry](https://registry.opendata.aws/tgs-opendata-poseidon); [NOPIMS](https://www.ga.gov.au/nopims/access-and-help2)
- NLOG/EPOS-NL: [NLOG 3D download](https://www.nlog.nl/en/nieuws/new-free-3d-seismic-data-download-map); [DEF survey](https://www.nlog.nl/en/nieuws/additional-north-sea-data-def-survey); [EPOS-NL data](https://www.nlog.nl/en/epos-nl-data)
- Groningen: [YoDa](https://public.yoda.uu.nl/geo/UU01/1QH0MW.html); [GeoExpro](https://geoexpro.com/static-model-giant-groningen-field-publicly-available/)
- Volve: [Frontiers 2020](https://www.frontiersin.org/articles/10.3389/feart.2020.00285/pdf)
- Diskos: [Sodir membership](https://www.sodir.no/en/diskos/About-us/membership/); NDR: [NSTA](https://www.nstauthority.co.uk/data-and-insights/data/themes/seismic/)
- Taranaki: [NZP&M geodata](https://geodata.nzpam.govt.nz/survey/3095909085)
- Namorado: [SBGF 2009](https://sbgf.org.br/mysbgf/eventos/expanded_abstracts/11th_CISBGf/1454_evt_6year_2009.pdf)
- SEAM: [SEG SEAM open data](https://seg.org/seam/open-data/)

View File

@@ -0,0 +1,139 @@
# P3 implementation review before the main experiment
Date: 27 October 2026. Repository pulled from Gitea `main`, fast-forward from
`5a6fb2f` to `a22f9d9`. The incoming commits add `AGENTS.md` and ten agent skills;
they do not change the scientific pipeline. Existing local work was preserved.
This review concerns the new, uncommitted P3 implementation. The original P2
G-B failure and the registered P2r results remain unchanged. No P3 main grid
has been run and no field outcome was used to select the fixes below.
## Findings and changes
| Finding | Consequence | Resolution |
| --- | --- | --- |
| Training workers loaded held-out labels and markers even though the optimizer did not use them. | The software boundary did not enforce the blind-well rule. | Training data views now expose only training logs/markers and seismic-only targets. Access to held-out labels or logs raises an error. A perturbation test verifies that changing the current outer well's labels cannot change its checkpoint or prediction. |
| A completed prediction cache could be accepted without its checkpoint. | A resumed job could later fail at deployment or mix artifacts. | Prediction and checkpoint checksums, fingerprints, atomic checkpoint writes, and matching-pair validation are required. |
| Missing porosity logs were extended by interpolation without a support check. | Warped labels could include values outside the measured interval. | Keep measured-support masks, exclude invalid warp particles, assign zero mass to invalid anchor samples, record retained counts, and fail if too few particles remain. AI's constant edge extension is a separate forward-model assumption. |
| The SMC class required anchors, so the new no-anchor ablation could not run. | The ablation failed before sampling. | Add an explicit opt-in prior-only initialization with empty anchor operators; the existing P2 default still requires anchors. Exercise both paths on synthetic wells. |
| P3 depended on scripts and P1 settings outside its initial code fingerprint. | Editing a classical-baseline dependency could escape resume validation. | The P3 lock covers all project Python modules/scripts, the Windows driver, baseline settings, prepared data, raw well inputs, and package versions. |
| The original run logger imported POSIX-only modules. | Logging and detached execution failed on native Windows. | Add Windows process groups and CSV locking; retain POSIX behavior. Unavailable resource/VRAM measurements remain null. Test nested child logging on both platforms; POSIX signal semantics are explicitly skipped on Windows. |
| The `all` command stopped before volume fitting/prediction. | A command named `all` did not complete the P3 deliverables. | Connect deployment fitting and streamed volume prediction; reduced scope requires explicit flags. |
| Volume uncertainty used subtraction of large second moments. | Rounding could erase a small predictive variance. | Use a stable online variance calculation and test a small variance around a large mean. |
| A resume state could outlive a missing volume file. | Completed rows could be skipped even though their predictions were gone. | Refuse that inconsistent resume state. |
| Smoke and intermediate stages could mark full ablation/protocol tasks complete. | `report.html` could overstate progress. | Separate smoke, protocol, training, diagnostics and volume states; mark the combined ablation task complete only after its required outputs exist. |
| Plot lines relied on color, and intervals lacked a precise definition. | Visual comparisons and uncertainty could be misread. | Add distinct line styles, shared scales, PNG/PDF outputs and a source/interval manifest. Intervals are nominal, moment-matched Gaussian predictive intervals, with calibration evaluated separately. |
## Scientific boundaries retained
- The sampling unit is the well: four outer folds, each with three inner
validation folds. Network seeds and 126 time samples do not increase the
number of independent field wells.
- Registration, normalization, wavelet estimation, label banks, and LFM inputs
use the exact inner training wells. The outer well supplies seismic input;
logs and markers enter only the separate scoring/sensitivity stage.
- Checkpoints use inner validation total MSE. The point baseline for G-C is
selected from inner validation, never by outer-test performance.
- G-C retains improvement at at least three of four wells and the original
coverage tolerances. Failure is reported; no post-hoc interval widening or
replacement by a better-looking ablation is allowed.
- F3 was already observed in P1. P3 is a descriptive follow-up on the same four
wells, not an untouched independent field replication.
- `B3d-Sa` averages forward maps `t(tau)` before inversion, matching P2r; it is
not the mean inverse map or mean porosity label.
- LOAO uses an explicitly identified linearized, anchor-only GP approximation.
It is not evidence that the SMC posterior is calibrated.
- The no-anchor ablation retains the common sonic datum. It is an information
removal diagnostic, not a new proof of absolute-time identifiability.
- The LFM ablation appends a training-only time trend. It is not the
horizon-guided classical inversion baseline.
- Maps report sonic-derived porosity and predictive dispersion. They do not
establish geological validity or calibrated uncertainty.
## Validation status
- Whole existing and P3 unit suite: **129 passed, 13 skipped** (Windows/POSIX
differences and unavailable optional datasets), recorded by `runlog`.
- Included synthetic-well integration: **2 passed**. It exercises the complete
registration/label-bank paths with and without anchors, without using real
held-out F3 outcomes.
- Final command-line, dashboard syntax and production-device checks are
recorded in `outputs/p3/review_checks.json` when completed.
- The streamed volume patch order was checked against `SeismicCube.patch` on
the real F3 cube. The cube and all seven restored horizons match the original
manifest's SHA-256 values.
- The real-data CUDA registration pilot used only `F02-1` and `F03-2`, with
P = 1024. The anchor-conditioned path took 122.3 seconds; removing anchors
took 256.7 seconds. Both completed. Outputs remain in the benchmark namespace,
separate from the registered experiment.
- A classical-baseline compatibility check produced finite 126-sample
predictions for B0a, B0b ridge/RF/GBM, and B1. It did not calculate held-out
performance or change settings from such performance.
- The protocol was frozen before any P3 smoke or production run. Its SHA-256
is `0c756d2825d9b6aa1520be6484f501a538f2ec14e5c8fe98a323cf3b6e1bc50c`.
The lock additionally checks the two protected historical artifacts; volume
prediction verifies the cube again. The scheduler emits a heartbeat every
30 seconds while waiting, and its Windows process prevents automatic sleep
only for its own lifetime.
- The full-runtime extrapolation is **2.57–6.35 hours** on the measured RTX
3060 setup with four workers. It includes registration, training, deployment,
scoring allowance and full-volume prediction; it is not a confidence interval.
- A full P3 experiment is separate from these correctness/timing checks;
passing tests and completing a smoke run are not scientific G-C verdicts.
The locked CUDA smoke completed on 28 October (6 registration jobs, 18 training
jobs, scoring diagnostics and summary, exit 0). Its gate file explicitly says
`evaluated: false`. The complete production command was then launched detached
at **00:15:47 +07:00 on 28 October**, with four workers on `cuda:0`. Its progress
and eventual verdict are published automatically to `report.html` through
`outputs/p3/progress.js`; this review does not pre-judge that verdict.
## Post-run operational interruption and recovery (28 October)
The full run completed registration, all 1,320 LOWO training trajectories,
diagnostics, scoring, and the 20 deployment models. It then stopped at 132/649
volume inlines at 03:57:33 +07:00: Windows denied atomic replacement of the
dashboard sidecar `outputs/p3/progress.js`. The exception handler encountered
the same lock. This was a publication failure, after model fitting and scoring;
the original failed log is retained at `logs/runs/20261028-001548_p3_all/`.
`operations/resume_f3_volume.py` is an explicitly post-run operational adapter.
It retries permission errors only for the two dashboard files, and defers a
persistently locked sidecar to the next update instead of aborting inference.
It calls the original frozen volume function, never registration or fitting.
The registered Python source, protocol, checkpoints, inference formula and
G-C remain unchanged. The adapter records its own hash and verifies the bytes
of the 132 previously completed rows before/after recovery. Its audit record
is `outputs/p3/volume_recovery.json`; the original protocol lock remains valid.
The completed LOWO result is **G-C failed**: M2-Sa improved band RMSE at one of
four wells, and macro coverage was 52.38% (nominal 80%) and 60.91% (nominal 90%).
Neither gate condition passes. Volume completion cannot change this verdict.
Recovery completed at **06:50:44 +07:00 on 28 October**, exit 0. The same dashboard
lock recurred once during inference and the retry succeeded. All 649 interior
inlines and eight section previews were produced; the previously completed rows
and G-C file were preserved byte-for-byte. The frozen code/data/environment
check still passes. The independent artifact audit is recorded in
`outputs/p3/completion_checks.json`.
## Protected artifacts and execution constraints
Do not run `04_wavelet_tie.py` or `09_fit_warp_prior_f3.py`. Do not overwrite
`outputs/wavelets.npz` or `outputs/p2/warp_prior_f3.json`. P3 estimates its own
fold-local quantities in its own output namespace. The frozen P1/P2/P2r YAML
content is preserved; LF checkout rules retain the original locked bytes on
Windows. No other user's GPU processes are stopped.
## Procedural assistance and provenance
Applied the local `scientific-critical-thinking`, `scikit-learn`,
`statistical-analysis`, and `scientific-visualization` skills for review guidance.
Their use does not constitute independent empirical validation of this code.
Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026).
*Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents.*
[arXiv:2609.00065](https://arxiv.org/abs/2609.00065).
[DOI: 10.48550/arXiv.2609.00065](https://doi.org/10.48550/arXiv.2609.00065).
Metadata verified against the current arXiv record (v2) on 27 October 2026;
no journal reference is listed there.

View File

@@ -0,0 +1,95 @@
# P4x — exploratory model variants on Volve (post hoc)
> **Dropped on 2026-10-29** (decision 5 of the Pivot 1 record, `docs/plan.md` §12 item 22). P4x is not summarised, cited or extended; V3 is not run. The job `exploratory/run_p4x.sh` that was running on cuda:0 (560/921 at 03:43 UTC) was stopped at 670/921 (about 04:05 UTC) and killed to free the GPU; the B3d-Sa stage and V3 never ran. A partial summary in `outputs/p4x/summary/` (04:07 UTC), generated before this decision was seen, has been deleted. The remaining output is unused, and Section 6 stays empty. `exploratory/` and `outputs/p4x/` remain on disk as a record only. The text below is kept unchanged as the pre-run declaration.
Created: 2026-10-29T02:40Z (09:40 +07:00), before any P4x training run, trend fit or P4x metric.
Status: **exploratory and post hoc**. Designed after the locked P4 result (`configs/protocol_volve.yaml`, gate G-D:
no blind-well skill, M2-Sa and B3b indistinguishable) was known, and motivated by a diagnosis of that result that
used outer-test labels (per-well bias of 3.4–5 p.u. with bias-removed RMSE close to the label SD). Nothing here
changes G-D, the P4 verdict or any locked protocol. No result here can support a claim listed in `docs/plan.md`
§10 or a confirmatory statement in the paper; at most it can be reported as an exploratory observation with this
status attached.
## 1. Purpose
1. Does a backbone with real blind-well skill on Volve exist within this data (same wells, inputs, labels, folds),
and if it does, does a gap between RML (M2-Sa) and the point tie (B3b) appear once there is skill?
2. If no variant has skill, what does the pattern of failures say about why (between-well level offset versus
within-well shape)?
## 2. Fixed elements (identical to locked P4)
- Six wells, label PHIF, main window 2400–2900 ms, 3×3 patch inputs along the deviated path, primary scoring
reference `calibrated`.
- σ_a = 7 ms only; registration banks reused read-only from `outputs/p4/registration/*_sa7.npz` (no new
registration).
- Nested folds of `ml_porosity.volve.folds` (schemes lowo and slot, 22 distinct inner training sets), seeds 0–4.
- Budget selection by inner-validation MSE only, inner models ensembled at the selected budget on the outer test
input (blind key T_out), then the five seeds (moment-matched Gaussian mixture): the unchanged
`ml_porosity.volve.evaluation.neural_predictions` code, called with an in-memory method list.
- Methods per variant: B3b and M2-Sa (required), B3d-Sa (run after the two required methods of every variant;
if not finished it is reported as not run).
- Locked code under `ml_porosity/` is imported read-only; P4x code lives in `exploratory/` (outside the P4 code
lock). Outputs go to `outputs/p4x/`.
## 3. Variants (complete list; frozen at creation time)
**V0 — reproduction.**
(a) Re-select and re-score the locked P4 trajectories (`outputs/p4/train`, σ_a = 7) through the P4x harness. The
combined-ensemble RMSE of B3b, B3d-Sa and M2-Sa per scheme and well must equal `outputs/p4/summary/metrics.csv`
within 1e-6. (b) Retrain seed 0 of B3b and M2-Sa for all 22 training sets through the P4x training path
(unmodified `train_trajectory`, cuda:0) and report the maximum absolute difference of the per-budget predictions
from the stored P4 trajectories. A non-zero difference from GPU non-determinism is reported, not hidden.
**V1a — velocity-trend residual.** Trend v(t) = a + b·V(t), where V is the 2011 TTI PSDM instantaneous interval
velocity (`data/Volve/Seismic/ST10010/Velocities/ST10010ZC11-MIG-VEL...segy`; depth domain, 20 m samples, 50 m
lateral grid), sampled trilinearly at the (inline, crossline, TVDSS) of each time sample of the path. Path: the
reference path for training wells, the blind path of key K for every other target; MD→TVD from the public survey
by linear interpolation, TVDSS = TVD − KB. a, b by ordinary least squares on all labelled samples of the training
wells of the trajectory (B3b bank labels, paired with V on the reference path at the same time sample). The network
(unchanged CNN-GRU, 64 channels, same loss, optimiser, budgets, seeds) learns the residual: targets
(Y_member − v)/s0 with s0 the P4 normalisation SD of the set; prediction μ = v + s0·μ_net, σ = s0·σ_net. The trend
is a function of the input location only, so it is the same for every bank member and method.
**V1b — TWT-trend residual.** As V1a with v(t) = a + b·t (two-way time in ms), OLS on the same training labels.
**V2a — narrow CNN-GRU.** The P4 architecture with 8 instead of 64 channels; everything else as P4 (no trend).
**V2b — linear-Gaussian model.** μ from one Conv1d over the 9 patch channels with kernel 9 (±16 ms) and a bias;
a single learned scalar σ (homoscedastic, softplus). 83 parameters, no dropout. Trained with the same masked bank
loss (M2-Sa: log-sum-exp over the 64 posterior members with λ = 1/τ_c; B3b and B3d-Sa: single-member masked
Gaussian NLL), Adam lr 0.005, gradient clip 5, same budgets, selection and seeds. This is the "ridge-like"
low-capacity model; a closed-form ridge is not used because it cannot be trained on the M2-Sa bank likelihood.
**V3 (optional) — V1a trend + V2b residual model.** Run only if V0–V2 finish by 05:30Z; otherwise reported as
not run.
**Reference predictors without training (context only).** Fitted on the outer training wells (B3b labels) and
applied to the outer test well along its blind path T_out: T0 constant (pooled mean, σ = pooled SD); T1a velocity
trend; T1b TWT trend (σ = residual SD of the fit).
## 4. Metrics
Per scheme (lowo, slot), per outer test well, per method, combined ensemble, primary reference: RMSE, bias
(mean of prediction − reference), |bias|, bias-removed RMSE (SD of the error), PCC, R² (relative to the test
well's own mean), coverage80 and coverage90, label SD of the test well (population SD on its labelled samples).
Macro = unweighted mean over the six wells. RML–point gap: M2-Sa − B3b in RMSE and bias-removed RMSE, per well
and macro, and the number of wells where M2-Sa < B3b. Porosity units (fraction × 100).
Blind-well skill (declared criteria): a variant/method/scheme has skill if its macro R² > 0, or if its macro
bias-removed RMSE is at most 0.9 × the macro label SD (a constant prediction gives exactly 1.0 × label SD).
Both are reported with the number of wells that meet each criterion per well.
## 5. Rules
- Outer-test labels are read only by scoring, after every prediction is fixed. Trend coefficients use the
training wells of the trajectory (or the outer training wells for T0/T1); the velocity cube is seismic-derived
and available at every location. Budgets are chosen by inner validation only.
- Every variant listed above that is started is reported, including failures and partial runs. No variant is
chosen, dropped or re-tuned using outer-test metrics. A variant added after results are seen will be labelled
as such with its time.
- No p-values (six wells, correlated samples).
## 6. Results
(Appended after the runs.)

View File

@@ -0,0 +1,245 @@
# Phân tích hiện trạng và hướng chuyển sang bài lý thuyết + synthetic benchmark
Ngày viết: **29/10/2026**. Trạng thái: **đã chốt** ở mục 6 (29/10/2026); mức A viết xong sớm ngày 29/10 (`docs/plan.md` §12 ý 24). Mục 0–5 giữ nguyên phân tích lúc viết; chỗ nào đã đổi có ghi chú *Cập nhật* hoặc *Sửa* kèm ngày. Mọi số liệu dưới đây lấy từ `docs/plan.md` §12, `docs/theory.md`, `outputs/p2r/summary/`, `outputs/p3/summary/`, `outputs/p4/summary/`, `outputs/p4x/summary/` và bản nháp `paper/sections/`. Không có kết quả mới nào được tính trong tài liệu này.
Bối cảnh: cả hai field test đều âm (G-C trên F3, G-D trên Volve). Plan §9 đã liệt kê sẵn **Pivot 1** ("chuyển thành bài phân tích: lý thuyết, benchmark và đánh giá có xét registration; phương pháp chỉ là phần phụ"). Tài liệu này rà lại toàn bộ đề tài để tìm các vấn đề tồn đọng, rồi đề xuất cách triển khai Pivot 1 thành một bài **lý thuyết + benchmark**.
---
## 0. Tóm tắt
1. **Phần đứng được** của đề tài là lý thuyết (Mệnh đề 1, 2; Bổ đề 1–5) và hai kết quả synthetic đã pre-register và đạt (H1; H2a, H2b của P2r). Phần **không đứng được** là mọi claim về field và về calibration.
2. Hai field test không bác bỏ phương pháp. Chúng **không có sức mạnh thống kê** để phát hiện hiệu ứng cỡ 10–20% khi mạng không có kỹ năng ở giếng blind (F3: band PCC ≤ 0.22; Volve: R² < 0 với mọi phương pháp, hằng số thắng mọi mạng). Đây là một kết quả có thể **chuyển thành lý thuyết** (mục 2.1, T3).
3. Lỗ hổng lý thuyết lớn nhất: **cơ chế của lợi ích H2b chưa được giải thích**. Ở 7/8 ô rộng, lợi ích vượt cận khử mờ 1/B(σ_post) của Mệnh đề 1. Giải thích được điều này là đóng góp lý thuyết mới quan trọng nhất của bài mới (T2). *(Cập nhật 29/10: 1/B(σ_post) là cận quần thể ρ* dưới cấu trúc sai số classical, còn tie trung bình posterior gần cấu trúc Berkson; tính cận tại sai số warp thì vẫn vượt ở 6/8 ô rộng. Bài mục 4.3 và 6.3; `docs/theory.md` mục 1.4 và 6.)* *(Sửa lần hai 29/10: nhận định "vượt cận" chỉ đúng với cận classical. Với cận Berkson, tính post hoc, chỉ 3/8 ô vượt tại σ_post (cả ba ở c = 1) và tối đa 1/8 tại sai số warp. Lý do là méo nằm quanh 70 Hz, nơi hai cấu trúc khác nhau nhiều. Câu hỏi của T2 vì vậy là: còn lợi ích nào vượt hiệu chỉnh quần thể của cấu trúc Berkson không. Xem `docs/plan.md` §12 ý 24.)*
4. Benchmark D2 đã có nhưng **chưa thành benchmark**: lưới phase diagram chưa đầy, các trục stress của plan §5.5 (rock physics sai, wavelet sai, σ_b) chưa chạy, chưa đóng gói, chưa có luật so sánh cho người ngoài.
5. Hạn 31/10/2026 **không đủ** cho pivot đầy đủ. Mục 4 chia hai mức: mức A (viết lại khung bài + các mệnh đề rẻ + phân tích power từ số liệu đã có) làm kịp 31/10; mức B (lấp lưới, trục stress, thí nghiệm cơ chế, đóng gói benchmark) cần 1–2 tuần nữa. Ngày là việc của người dùng quyết. *(Cập nhật: người dùng chọn mức B, hạn 14/11/2026; mục 6. Mức A xong ngày 29/10.)*
---
## 1. Kiểm kê bằng chứng
### 1.1 Bằng chứng dương (đã pre-register, đạt; giữ nguyên trong bài mới)
| # | Kết quả | Số liệu | Nguồn |
| --- | --- | --- | --- |
| D1 | **Mệnh đề 1 (blur)**: predictor tối ưu MSE dưới misregistration = m tích chập với p_δ; hệ quả cận std ratio, PCC trong băng; L_Var chỉ chỉnh biên độ | Chứng minh dưới (A1) δ ⊥ (X, y) | `docs/theory.md` §1; `paper/sections/04_theory.tex` |
| D2 | **H1** kiểm chứng định lượng Mệnh đề 1 | r(σ) = 1.009 / 1.009 / 1.007 / 1.093 tại σ = 4 / 8 / 16 / 32 ms; chỉ trên dải 6.8–22.5 Hz | `outputs/p2/h1/` |
| D3 | **Mệnh đề 2 (nhận dạng)**: không anchor thì dịch chung của mạng và warp là ridge; sd(β) ≈ σ_a/√ΣK | Chứng minh dưới (B) | `docs/theory.md` §2 |
| D4 | **H4** (anchor là cần thiết) | Bỏ anchor: warp RMSE 3.15 → 31.1 ms (×9.9), band RMSE 0.735 → 1.398 p.u. | P2 |
| D5 | **Bổ đề 1–5**: point tie, hard-min, soft-min, soft-DTW, DILATE là trường hợp riêng của RML_λ; có unit test | Chính xác | `docs/theory.md` §4; `tests/test_losses.py` |
| D6 | **H2a** (P2r): nhãn tại warp trung bình của posterior SMC hơn point tie tốt nhất | c = 1: R10 0.857 / 0.782; R0 0.888 / 0.888; Rm5 0.915 / 0.923 (N = 4 / 16). Phần lớn lợi ích đã có ở c = 0 (macro 0.81 / 0.85 / 0.88) | `outputs/p2r/summary/verdict.json` |
| D7 | **H2b** (P2r): RML trên bank hơn nhãn trung bình khi posterior rộng, tăng theo σ_post | N = 16: 8/8 ô rộng đạt, ρ = −0.85, ô hẹp 0.996 | như trên |
| D8 | **Nhánh σ_a**: lợi ích H2a biến mất khi σ_a sai ×0.5 hoặc ×2 | 3.5 ms: 0.977 / 1.141; 14 ms: 0.985 / 0.928; 0/2 ô | như trên |
| D9 | **P2 (G-B trượt)** là một kết quả về registration: posterior anchor + trọng số IS trên 64 mẫu không co về warp thật (3.25 ms, ngang B3c 3.85 ms); SMC co về 0.56 ms | Đã pre-register, báo cáo như ra | P2, P2 diag |
| D10 | **Audit F3** (C4): PHIE = f(DT) chính xác ở 3/4 giếng; density dự đoán ở 2 giếng; marker không phải checkshot độc lập; TD lệch 14–66 ms | [KT] | plan §1.2 |
| D11 | **Bộ sinh D2** hiệu chỉnh theo F3 (horizon thật, rock physics F3, wavelet F3, prior warp fit trên anchor F3) với warp thật đã biết | 8 realization × 5 regime | `ml_porosity/data/synth_d2.py`, `configs/d2_synth_p2r.yaml` |
| D12 | **Posterior tie SMC** (tempering theo ACF, ước lượng pha, tiêu chí ổn định 0.5 ms) | P = 1024 | `ml_porosity/registration/smc_torch.py` |
### 1.2 Bằng chứng âm (phải giữ trong bài, chuyển thành "phạm vi")
| # | Kết quả | Số liệu |
| --- | --- | --- |
| A1 | **H3 bác bỏ**, mọi ensemble under-cover, **tệ hơn khi nhãn tốt hơn** | cov90 ở R10, c = 1, N = 16: B5 0.79; M2-Sa-ens 0.58; Oracle-ens 0.48 |
| A2 | **G-C trượt** (F3): cải thiện 1/4 giếng; coverage 0.524 / 0.609 | M2-Sa 1.272 so với B3c-R 1.256 p.u.; chênh giữa seed tới 0.13 p.u. (8× khoảng cách); band PCC ≤ 0.22 với mọi mạng; chỉ B4b (1.211) thấp hơn mốc "không có nội dung băng" (1.224); B0a trend thắng mọi mạng về RMSE tổng (2.48 p.u.) |
| A3 | **G-D trượt** (Volve): 2/6 và 3/6 giếng; cov90 0.47–0.48 | R² −0.84 đến −1.71 với mọi phương pháp; hằng số tại trung bình giếng train (6.03 / 6.59) thắng mọi mạng; trend theo TWT (P4x, T1b) còn thấp hơn (5.37 / 5.83); mức PHIF giữa giếng chênh 8.5–17 p.u. |
| A4 | σ_a **không xác định được** trên F3: type-II ≈ 0.4 ms (coi marker chính xác), spread marker–horizon 7 ms; LOAO cho z² trung bình 0.21 (prior quá rộng) | F3 nằm ở hai đầu trục σ_post tùy σ_a: 0.6 ms hoặc 2.5–3.4 ms |
| A5 | **Pha wavelet không xác định được** trên F3 (6 ước lượng trải 214°, log-evidence chỉ đổi 1–5 nats) nhưng xác định tốt trên Volve (43°) | registration không phải nút thắt của Volve |
| A6 | Ablation F3: 9/11 biến thể có band RMSE thấp hơn M2-Sa; kích thước bank (1/8/64/256) không có ảnh hưởng; bỏ anchor lại *giảm* band RMSE (1.247) | khớp với giả thuyết "điểm số băng trên F3 không nhạy với timing của nhãn", chưa kiểm |
| A7 | Thứ tự phương pháp **đảo** giữa synthetic và F3: B4a–d (anchor-free) kém B3b 38–53% ở P2 nhưng thấp hơn mọi point tie trên F3 | chưa giải thích |
### 1.3 Đọc lại chuỗi suy luận: thất bại ở đâu
Chuỗi claim gốc: *(i)* tie không chắc chắn → *(ii)* nhãn bị blur (MĐ1) → *(iii)* posterior tie tốt + marginalize sửa được (H2a, H2b) → *(iv)* trên field cũng vậy (G-C, G-D) → *(v)* bất định truyền sang dự đoán (H3).
- (i), (ii): đứng vững, có cả chứng minh lẫn kiểm chứng định lượng.
- (iii): đứng trên synthetic, **có điều kiện** (σ_a đúng, posterior đủ rộng, N đủ lớn). Nhưng *cơ chế* của phần (iii)-H2b chưa rõ (mục 2.1 T2).
- (iv): **không có sức mạnh thống kê.** Trên F3 khoảng cách 0.016 p.u. so với dao động seed 0.13 p.u.; trên Volve mọi mạng thua hằng số. Field test không nói gì về (iii) theo cả hai chiều. Điều đáng nói: *điều này có thể tính trước* từ chính benchmark (mục 2.1 T3), và việc đó chưa làm.
- (v): bác bỏ, và hướng bác bỏ (nhãn tốt hơn → coverage tệ hơn) là một hiện tượng cần lý thuyết (T4), không chỉ là một thất bại.
Kết luận: bài hiện tại yếu vì nó được *đóng khung* như bài phương pháp có field validation, trong khi bằng chứng thật nằm ở (i)–(iii). Pivot 1 là đóng khung lại cho đúng với bằng chứng, không phải thay đổi bằng chứng.
---
## 2. Vấn đề tồn đọng
### 2.1 Lỗ hổng lý thuyết (T1–T8)
Xếp theo mức quan trọng cho bài mới. Cột "chi phí" là ước lượng [ĐX].
| ID | Vấn đề | Hiện trạng | Hướng giải | Chi phí |
| --- | --- | --- | --- | --- |
| **T2** | **Cơ chế lợi ích của RML trên bank (H2b).** Ở 7/8 ô rộng (N = 16; c = 1 và 2), tỉ số M2-Sa/B3d-Sa nằm *dưới* cận khử mờ 1/B(σ_post); ví dụ Rm5 c = 1: cận cho phép 0 lợi ích (1.000), đo được 0.982. Chỉ R10tb c = 2 nằm trong cận (0.667 so với 0.634). Hai giả thuyết chưa tách: (a) tăng cường nhãn (regularization), (b) warp trung bình lệch khi posterior đa mode. | Thảo luận trong paper nêu "mechanism is open"; thí nghiệm đối chứng "bank nhiễu ngẫu nhiên cùng độ rộng" **chưa chạy** | Giả thuyết thứ ba, chưa có trong paper, đáng kiểm nhất: **(c) tái đăng ký ngầm (implicit re-registration).** Với λ hữu hạn, Bổ đề 3 cho gradient = NLL có trọng số r = softmax(log π + λℓ). Mạng *dùng chung* giữa các giếng đóng vai trò prior về tính nhất quán liên giếng; responsibilities dồn về các hạt mà nhãn khớp với dự đoán nhất quán đó, tức posterior tie được *tinh chỉnh lại* bằng thông tin từ các giếng khác. Kiểm: (1) tính warp RMSE có trọng số r so với warp RMSE của τ̄ trên P2r; nếu r-weighted < τ̄ thì (c) đúng; (2) đối chứng (a): bank = τ̄ + nhiễu GP cùng σ_post, không mang thông tin; (3) đối chứng (b): tách ô posterior đa mode. Viết thành **Mệnh đề 3**: điều kiện để fixed point của RML_λ có responsibilities tập trung gần warp thật (kiểu EM với prior chia sẻ). *(Cập nhật 29/10: trong bài, (c) là Nhận xét 1, chưa thành mệnh đề; số "Mệnh đề 3" ở đây không phải Mệnh đề 3 của bài, vốn là hai cấu trúc sai số. Tính cận tại sai số warp RMS của B3d-Sa thì 6/8 ô vượt cận (thêm R10tb c = 1: cận 0.710, đo 0.890); R10tb c = 2 vượt mép lưới blur 6 ms nên cận bị kẹp ở 1/B(6 ms). Nguồn: `outputs/p2r/posthoc/`. Khai báo T2 phải ghi rằng các tỉ số này đã được xem post hoc. **Sửa lần hai 29/10:** với cận Berkson (post hoc; `bound_post_b` trong `outputs/p2r/posthoc/bound.csv`), chỉ 3/8 ô vượt tại σ_post và tối đa 1/8 tại sai số warp. Bài thêm test (iv), kiểm Berkson hay classical bằng hiệp phương sai của offset, và test (v), B3d-Sa ở số vòng lặp của Oracle. Câu hỏi của T2 đổi thành "còn lợi ích nào vượt hiệu chỉnh Berkson không". Khai báo phải ghi cả các cận (b), b60 và phổ chéo đã xem.)* | Thấp về GPU (bank P2r và budget đã có; mỗi run < 1 phút); trung bình về viết |
| **T3** | **Lý thuyết về khả năng phát hiện (power) của một field test.** Với n giếng test, chênh lệch thật Δ, độ lệch seed s, và tham chiếu chấm điểm *bản thân là một point tie* với sai số σ_ref, xác suất mà luật "≥ k/n giếng cải thiện" đạt là bao nhiêu? | Paper chỉ nói định tính ("needs more wells") | Hai phần: (1) **giải tích**: band RMSE đo với tham chiếu lệch δ_ref = RMSE thật ⊕ thành phần do δ_ref, chung cho mọi phương pháp → tỉ số bị kéo về 1 (đã quan sát: dải tham chiếu 0.06–0.15 p.u., khoảng cách 0.016 p.u.); (2) **mô phỏng trên D2**: lấy 4 giếng test, chấm bằng một point tie thay vì warp thật, lặp lại qua realization × seed, đếm tần suất luật G-C đạt khi lợi ích thật là 10–20% (đã biết từ H2a). Kết quả là một **đường cong "cần bao nhiêu giếng"**. Biến hai field test âm thành một kết luận định lượng, có thể tính trước. | Thấp (dùng dự đoán đã lưu `outputs/p2r/train/*/cells/*.npz`; chỉ cần code chấm điểm mới) |
| **T4** | **Vì sao nhãn tốt hơn → coverage tệ hơn** (A1). | Chỉ mô tả | Hệ quả trực tiếp của Bổ đề 2 (λ → 0: σ*² hấp thụ Var_π y): head heteroscedastic học *phương sai của nhãn*, không học sai số dự đoán ở giếng mới. Nhãn sạch hơn → σ nhỏ hơn, trong khi sai số epistemic theo không gian (giếng test cách ≥ 1 km) không đổi và seed-ensemble không bắt được. Viết thành **Mệnh đề 4** (hoặc hệ quả): coverage của ensemble seed với head heteroscedastic giảm đơn điệu theo chất lượng nhãn khi sai số không gian trội. Kiểm bằng số liệu H3 đã có (Oracle-ens 0.48 < M2 0.58 < B5 0.79) và tách σ_aleatoric / Var_seed trong các file npz. *(Cập nhật 29/10: thành Mệnh đề 5 của bài, phát biểu qua tỉ số ξ = E s²/E(y − μ)²; phần (a) là đồng nhất thức, (b) và (c) là giới hạn quần thể. T4 post hoc (`scripts/30_t4_coverage.py`): mọi ensemble quá hẹp (ξ 0.19 ở Oracle, tối đa 0.66), và độ dài huấn luyện lẫn với nguồn nhãn, nên "giảm đơn điệu theo chất lượng nhãn" chưa được kiểm.)* | Thấp |
| **T8** | **Posterior đa mode (cycle skip)**: ô có lợi ích lớn nhất (R10tb c = 2, 33%) lại bị gắn cờ "unstable". | Loại khỏi bằng chứng chính | Mệnh đề 1 với p_δ hai điểm ±Δ/2 cho P(f) = cos(πfΔ): nhãn trung bình của hai mode lệch nửa chu kỳ **triệt tiêu** băng seismic tại f = 1/(2Δ). Đây là lý do B3d-Sa sụp ở c = 2 và là trường hợp mà bank *được dự báo* hơn hẳn. Viết thành hệ quả rõ ràng, đưa "cycle-skip regime" vào benchmark như một trục có kiểm soát thay vì gắn cờ bỏ. *(Cập nhật 29/10: Hệ quả 3 của bài; phát biểu chính xác ở `docs/theory.md` mục 6.3: hệ số truyền âm trên 1/(2Δ) < |f| < 3/(2Δ).)* | Thấp (lý thuyết); trung bình (ổn định SMC đa mode hoặc chấp nhận báo cáo biến thiên giữa run) |
| **T1** | **(A1) bị vi phạm khi tie được ước lượng từ chính seismic X** (δ của τ̄ phụ thuộc X) và trên F3 (nhãn và trục thời gian chung DT). | Chỉ ghi là giới hạn | Mở rộng MĐ1: ŷ*(t) = ∫ p(δ \| X) m(t + δ) dδ, bộ lọc *phụ thuộc X* (không còn LTI). Với posterior hiệu chỉnh tốt, Var(δ \| X) ≈ σ_post(X)², cho đúng cận B(σ_post) đang dùng, nay có phát biểu chặt. **Sửa 29/10:** khi viết ra thì không đúng như vậy. Sai số của tie trung bình posterior gần cấu trúc *Berkson* (độc lập với D), không phải classical, nên nó làm *sắc* predictor (bộ lọc 1/Q), không làm mờ. Bài viết thành Mệnh đề 3 (hai cấu trúc) và Mệnh đề 4 (bank hiệu chỉnh: lợi ích quần thể so với nhãn điểm là bậc bốn theo σ); 1/B(σ_post) chỉ là ρ* dưới cấu trúc (a). Xem `docs/theory.md` mục 1.4 (ghi chú sửa) và mục 6. Trường hợp nhãn–trục chung DT: δ tương quan với ∂y/∂t; viết hệ quả về bias (không chỉ blur). | Thấp–trung bình |
| **T7** | **Đánh đổi dịch–pha** trong số hạng tie seismic (MĐ2 chỉ phác thảo). | Nhận xét định tính (43° ở ±30 Hz) | Thông tin Fisher về β từ likelihood tie: I(β) ∝ ∫ (2πf)² S_syn(f) df, trừ phần bị pha hấp thụ. Cho công thức sd(β) theo băng thông và SNR. Giải thích vì sao pha trên F3 không xác định (băng hẹp ở vùng kết hợp 7–23 Hz) mà trên Volve lại xác định. | Trung bình |
| **T5** | **Tương tác giữa N (số giếng) và σ_δ**: phase diagram "khi nào registration quan trọng" (C3 gốc) chỉ có một phần. | P2: c × N đủ nhưng posterior kém; P2r: chỉ c ∈ {0,1,2}, N ∈ {4,16} | Lấp lưới (mục 2.2 S1) rồi fit luật thang: band RMSE² ≈ e_oracle²(N) + e_blur²(σ). Kiểm tính cộng. | GPU 1 ngày |
| **T6** | λ = 1/τ_c là heuristic; F3 cho λ = 1 hơi tốt hơn; P2 diag ≤ 7% khác biệt. | Không claim | Giữ là heuristic; thêm một ablation λ trên benchmark và một đoạn nối với magnitude adjustment (Pauli 2011, Ribatet 2012; chưa đọc toàn văn). Ưu tiên thấp. | Thấp |
| T9 | H1 chỉ kiểm trên 6.8–22.5 Hz; σ = 32 ms lệch 9% chưa rõ nguyên nhân. | Ghi là giới hạn | Thử lại với predictor có công suất ở tần cao hơn (SNR ∞, N = 16, budget lớn) để mở rộng dải kiểm; hoặc chấp nhận và nói rõ. | Thấp |
| T10 | Định vị lý thuyết trong literature **label noise / errors-in-variables**: misregistration là nhiễu ở *chỉ số* (index) chứ không ở *giá trị* nhãn; MĐ1 là analog của attenuation bias. | Chưa có trong related work | Thêm một đoạn related work và một nhận xét; nâng tính tổng quát (áp dụng cho core–log depth shift, 4D time shift, nhãn đăng ký ảnh). | Thấp (viết) |
### 2.2 Lỗ hổng của benchmark (S1–S8)
| ID | Vấn đề | Hiện trạng | Việc cần làm |
| --- | --- | --- | --- |
| **S1** | Lưới phase diagram chưa đầy với posterior SMC | P2r: c ∈ {0, 1, 2}, N ∈ {4, 16}, 5 regime | Thêm c = 0.5 (và 1.5), N ∈ {2, 8}; cùng realization 8–15. Hình chính F4 của plan §8 chưa tồn tại ở dạng đầy đủ. |
| **S2** | Các trục stress của plan §5.5 **chưa chạy**: rock physics sai mô hình (φ–DT khác giữa train/test), wavelet sai pha/tần số, σ_b, drift sai mô hình (bước nhảy tại Truncation, jitter tần cao) | Bị cắt theo thứ tự cắt phạm vi | Cần sửa `synth_d2.py` (thêm tham số misspec), chạy ở R10 và Rm5, c = 1, N = 16. Đây là phần khiến benchmark "trung thực" thay vì "cùng simulator". |
| **S3** | B4a–d (anchor-free) chưa chạy lại trong regime SMC của P2r | Chỉ có ở P2 | Chạy lại để bảng kết quả benchmark đầy đủ một protocol. |
| **S4** | Chỉ một backbone trên synthetic | TCN chỉ có ở ablation F3 | Thêm TCN trên 2–3 ô đại diện. |
| **S5** | Thí nghiệm cơ chế (T2) | Chưa có | Xem T2. |
| **S6** | Nghiên cứu khả năng phát hiện (T3) | Chưa có | Xem T3. |
| **S7** | **Đóng gói**: generator + realization cố định (hash) + regime + luật đạt + metric + baseline + hướng dẫn | Code có, nhưng gắn với `scripts/14`, `15`, `18` và protocol nội bộ | Tách thành gói `ml_porosity.benchmark` (hoặc repo riêng), một lệnh sinh dữ liệu, một lệnh chấm, bảng kết quả tham chiếu, giấy phép (horizon F3 là CC BY-SA 3.0), DOI Zenodo. |
| **S8** | Ô c = 2 không ổn định giữa các run SMC | Gắn cờ, loại | Hoặc tăng P / nhiều run và báo cáo biến thiên như một phần của benchmark, hoặc định nghĩa "cycle-skip regime" có kiểm soát (đặt Δ mode tường minh). Gắn với T8. |
| S9 | Chỉ 2 realization dev (900/901) cho mọi quyết định thiết kế | Ghi là giới hạn | Thêm 2–4 realization dev nếu còn thiết kế mới (S2). |
| S10 | Khoảng cách giếng test ≥ 1 km cố định | Một giá trị | Thêm trục khoảng cách (500 m, 1, 2, 4 km) nếu muốn nói về sai số không gian (liên quan T4). |
### 2.3 Vấn đề field (giữ lại như phạm vi, không giải trong bài mới)
- F3: nhãn là sonic; F02-1 nhãn khác; marker không độc lập; σ_a và pha không xác định; mạng không có kỹ năng trong băng; tham chiếu chấm điểm là một point tie.
- Volve: 16–37 mẫu nhãn mỗi giếng; mức PHIF giữa giếng chênh lớn; không mạng nào có kỹ năng; P4x chỉ xong V0 (tái lập) và các trend tham chiếu, V1–V3 chưa chạy (`outputs/p4x/summary/checks.json`: danh sách method rỗng).
- Trong bài mới, hai field case phục vụ hai mục đích: (1) **hiệu chỉnh benchmark** (D2 lấy horizon, rock physics, wavelet, prior drift, σ_a từ F3); (2) **minh họa T3**: field test với 4–6 giếng không phát hiện được hiệu ứng cỡ benchmark. Không dùng để claim gì khác.
### 2.4 Vấn đề về quy trình và độ tin cậy
- P2r là pre-registration **sau khi P2 trượt** (deviation đã ghi). `protocol_f3` được tag git *sau* khi chạy (bằng chứng khóa là timestamp tự ghi). Bài mới phải giữ nguyên các ghi chú này.
- Pivot 1 có trong plan §9 **trước** mọi field test, nhưng quyết định pivot là **sau** khi thấy kết quả field. Bài phải nói rõ: khung "lý thuyết + benchmark" được chọn sau khi field test trượt; các kết quả synthetic được pre-register trước đó và không đổi.
- Nhiều kết quả hiện "descriptive only". Trong bài benchmark, cần tách rõ: kết quả **confirmatory** (H1, H2a, H2b, H4, σ_a arm), kết quả **benchmark reference** (bảng mọi phương pháp), và **exploratory** (T2, T3, S2 nếu thiết kế sau khi xem dữ liệu).
- `docs/plan.md` §10 (claim cấm) vẫn áp dụng, nhất là: không gọi kết quả synthetic là "generalization ra field"; không claim calibration.
---
## 3. Hướng mới: bài lý thuyết + benchmark
### 3.1 Luận điểm trung tâm
> Sai số đăng ký của nhãn (well tie) là một dạng **nhiễu ở chỉ số thời gian**, khác nhiễu nhãn cổ điển. Nó có hiệu ứng *dự đoán được* lên predictor học được (blur theo hàm đặc trưng của sai số; không nhận dạng được dịch chung nếu không có anchor). Trên một benchmark có warp thật, các cách dùng posterior tie (nhãn trung bình, bank) sửa được một phần, với điều kiện rõ ràng (σ_a đúng, posterior đủ rộng, N đủ lớn), và cơ chế của phần sửa thêm là [kết quả T2]. Cuối cùng, benchmark cho biết **một field test cần bao nhiêu giếng** để phát hiện hiệu ứng đó, và hai field test công khai hiện có nằm dưới ngưỡng ấy.
Tên làm việc (theo plan §9, Pivot 1): *Label registration error in sparse-well seismic property learning: theory, a registration-aware benchmark, and the limits of field validation.*
### 3.2 Đóng góp đề xuất
> *Ghi chú 29/10/2026:* "Mệnh đề 3" và "Mệnh đề 4" ở mục 3, 4 và 6 là đánh số lúc lập kế hoạch. Trong bài: Mệnh đề 3 là hai cấu trúc sai số của tie, Mệnh đề 4 là bank hiệu chỉnh, coverage là Mệnh đề 5, reference lệch là Mệnh đề 6; cơ chế bank (T2) chưa thành mệnh đề, giả thuyết tái đăng ký ngầm là Nhận xét 1.
| | Đóng góp | Thành phần đã có | Thành phần mới |
| --- | --- | --- | --- |
| **C1′** | Lý thuyết nhiễu đăng ký | MĐ1 + hệ quả; MĐ2; Bổ đề 1–5; H1 | T1 (δ phụ thuộc X), T2 (cơ chế bank, Mệnh đề 3), T4 (coverage, Mệnh đề 4), T8 (đa mode), T7 (dịch–pha) tùy thời gian |
| **C2′** | Benchmark có warp thật, hiệu chỉnh theo F3, với luật đạt pre-registered | D2, 5 regime, SMC posterior, kết quả P2 và P2r | S1 lấp lưới, S2 trục misspec, S3, S4, S8, S7 đóng gói |
| **C3′** | Khung loss thống nhất (RML_λ) làm **họ baseline** của benchmark, không phải "phương pháp đề xuất thắng" | Bổ đề 1–5, code | Trình bày lại: bảng phương pháp = các điểm trong không gian (bank, π, λ) |
| **C4′** | Lý thuyết và mô phỏng về **khả năng phát hiện** của field test; audit F3 | Số liệu F3, Volve, P4x; audit C4 | T3 (giải tích + mô phỏng trên D2); viết lại hai field case thành một mục "scope" ngắn, bảng chi tiết vào phụ lục |
### 3.3 Cấu trúc bài (đề xuất)
1. Introduction: nhiễu đăng ký của nhãn; vì sao khác label noise; C1′–C4′.
2. Related work: thêm nhóm label noise / errors-in-variables / misaligned supervision; thêm benchmark papers trong geoscience ML (so sánh cách đánh giá).
3. Theory: MĐ1, hệ quả, MĐ2, **Mệnh đề 3 (cơ chế bank)**, **Mệnh đề 4 (coverage)**, hệ quả đa mode; H1.
4. Benchmark: thiết kế D2 (nguồn hiệu chỉnh từ F3 → audit F3 chuyển vào đây hoặc phụ lục), các trục, luật đạt, metric, họ phương pháp (RML_λ), oracle.
5. Results on the benchmark: registration (P2 vs SMC), H2a, H2b, σ_a, S2 misspec, S1 phase diagram, cơ chế (T2), coverage (T4).
6. Detectability and the two field cases: T3; F3 và Volve tóm tắt 1–2 trang, bảng vào phụ lục.
7. Discussion: khi nào cần quan tâm registration; khuyến nghị cho field study (đo σ_a, số giếng, tham chiếu chấm điểm); giới hạn (cùng simulator, một backbone, λ heuristic).
8. Conclusion; data/code/benchmark availability.
### 3.4 Venue
- Phù hợp nhất với "theory + benchmark": *Computers & Geosciences* (mạnh về benchmark/code), *Geophysical Prospecting*, *Journal of Applied Geophysics*. Plan §9 nêu *Frontiers in Earth Science*, *Earth Science Informatics* cho Pivot 1.
- Nếu nhấn mạnh lý thuyết tổng quát (T10) có thể cân nhắc venue ML, nhưng lịch không cho phép trong tuần này. Quartile phải tra lại khi nộp [XM].
### 3.5 Claim vẫn cấm (kế thừa plan §10)
Không "first"; không gọi synthetic là generalization ra field; không claim calibration; không claim field superiority; không gọi marker là checkshot; không dùng số liệu luận văn làm baseline.
---
## 4. Kế hoạch với hai mức
### 4.1 Mức A: kịp 31/10/2026 (chỉ viết + tính toán trên số liệu đã có) — xong ngày 29/10/2026
| Việc | Đầu vào | Ghi chú |
| --- | --- | --- |
| A1. Viết lại abstract, intro, contributions, discussion, conclusion theo 3.1–3.3 | bản nháp hiện tại | Chuyển F3/Volve thành mục "scope"; bảng chi tiết sang phụ lục |
| A2. Viết T1, T4, T8 thành mệnh đề/hệ quả (chứng minh ngắn, đều là hệ quả của MĐ1 và Bổ đề 2) | `docs/theory.md` | Không cần GPU |
| A3. T4: tách σ_aleatoric và Var_seed từ `outputs/p2r/train/*/cells/*.npz` để minh họa Mệnh đề 4 | file đã có | Vài giờ |
| A4. T3 phần giải tích + phần mô phỏng dùng dự đoán đã lưu của P2r (chấm 4 giếng test bằng tham chiếu point tie thay vì warp thật, đếm tần suất đạt luật G-C) | `cells/*.npz`, nhãn point tie | 1 ngày; cần kiểm xem npz có lưu nhãn point tie của giếng test hay phải dựng lại từ realization |
| A5. T10: đoạn related work về label noise / errors-in-variables | — | Cần trích dẫn đúng; kiểm bằng OpenAlex |
| A6. Ghi quyết định pivot vào `docs/plan.md` §12 với ngày và lý do; cập nhật `AGENTS.md` | — | Ghi rõ là quyết định sau khi thấy field test |
**Trạng thái (29/10/2026): A1–A6 xong** (`docs/plan.md` §12 ý 24).
- A1: abstract (292 từ sau lượt tự sửa A6), intro, đóng góp C1–C4, discussion, conclusion, tiêu đề, keywords, `paper/highlights.txt` viết lại theo khung Pivot 1. F3 và Volve thành mục "scope" (bài mục 6.6); chi tiết sang Phụ lục B.
- A2: T1 thành Mệnh đề 3–4 (kèm sửa cách đọc cận, xem hàng T1 ở mục 2.1), T4 thành Mệnh đề 5, T8 thành Hệ quả 3; thêm Nhận xét 1 (λ > 0), Mệnh đề 6 và Hệ quả 4 (reference lệch, dung sai σ_r < σ/√2).
- A3: `scripts/30_t4_coverage.py` → `outputs/t4/` (bài mục 6.3, Bảng `tab:t4`).
- A4: `scripts/27_t3_power.py` → `outputs/t3/` (bài mục 6.5). Khác với phác thảo ở bảng trên: reference là nhãn thật đọc tại một warp nhiễu loạn có độ lớn σ_ref (không phải nhãn point tie), và luật được đánh giá là sign test một phía; luật k-of-n chỉ dùng để chỉ ra nó không phải phép kiểm. Khai báo trước ở `docs/research/applicability-teapot.md` (Deviation 1: mở rộng lưới σ_ref).
- A5: đoạn "Label noise and errors in variables" ở bài mục 2 (Mnih & Hinton 2012 đọc toàn văn; Balakrishnan 1962 chỉ có metadata).
- A6: `docs/plan.md` §12 ý 22–24, `AGENTS.md`, `report.html`, `docs/theory.md` mục 6. Trong A6, agent phát hiện và sửa hai nhận định sai của chính mình về cận ρ*: hệ số giữa hai cấu trúc, và câu "lợi ích vượt cận" (`docs/plan.md` §12 ý 24).
Mức A cho ra một bản nộp được nhưng benchmark **chưa đầy** (thiếu S1–S3, S7) và cơ chế T2 chỉ ở mức giả thuyết.
### 4.2 Mức B: thêm 1–2 tuần (GPU + đóng gói)
| Tuần | Việc | GPU |
| --- | --- | --- |
| 1 | T2: ba thí nghiệm cơ chế (responsibility-weighted warp error; bank nhiễu ngẫu nhiên đối chứng; tách ô đa mode) trên realization 8–15, 2–3 regime | < 0.5 ngày (bank có sẵn, budget 250) |
| 1 | S1: lấp lưới c ∈ {0.5, 1.5}, N ∈ {2, 8} với SMC | ≈ 1 ngày trên 2 GPU (P2r mất vài giờ cho 30 ô; SMC là phần chậm) |
| 1 | S3, S4 | < 0.5 ngày |
| 2 | S2: sửa generator cho misspec rock physics / wavelet / σ_b / drift; dev trên realization mới 902–905; khóa protocol mới; chạy ở 2 regime | 1 ngày code + 1 ngày GPU |
| 2 | S8/T8: regime cycle-skip có kiểm soát | 0.5 ngày |
| 2 | S7: đóng gói benchmark, README, hash, Zenodo | 1–2 ngày |
| 2 | Viết lại §4–5 theo kết quả; review nội bộ | — |
Mọi thí nghiệm mới ở mức B phải có **protocol mới** (`configs/protocol_bench.yaml`) khóa trước khi chạy, và ghi rõ là thiết kế sau khi đã thấy P2r. T2 và T3 là **exploratory/explanatory**, không phải confirmatory, trừ khi pre-register trên realization mới (16–23).
### 4.3 Hạ tầng tái dùng và chi phí
| Thành phần | Tái dùng | Ghi chú |
| --- | --- | --- |
| `ml_porosity/data/synth_d2.py` (267 dòng) | S1, S2 (cần thêm tham số misspec) | Generator identical giữa P2 và P2r |
| `ml_porosity/registration/smc_torch.py`, `warp_prior.py`, `ties.py` | Toàn bộ | P = 1024, tiêu chí ổn định đã có |
| `ml_porosity/losses/rml.py`, `softdtw.py` | Toàn bộ | Bổ đề 1–5 có test |
| `scripts/14_diag_posterior.py`, `15_diag_train.py`, `18_summarize_p2r.py` | S1, S3, T2 | Resume theo cell; nhận realization mới khi protocol khớp hash |
| `outputs/p2r/posterior/*/*_particles.npz` (bank), `outputs/p2r/train/*/cells/*.npz` (μ, σ từng seed trên giếng test) | T2, T3, T4 | 7.7 GB; mô hình không lưu trọng số, cần train lại cho T2 (rẻ) |
| `outputs/p2/h1/` | T9 | — |
| GPU | cuda:0 / cuda:1 theo tải | P2 grid 128 ô × 11 phương pháp × 5 seed: 89 phút; SMC P = 1024 ≈ 3.3× P = 256 |
---
## 5. Rủi ro của hướng mới
| Rủi ro | Mức | Giảm thiểu |
| --- | --- | --- |
| Reviewer: "benchmark cùng simulator với phương pháp" | Cao | S2 (misspec) là bắt buộc nếu muốn gọi là benchmark; không có S2 thì gọi là "controlled experiment", không gọi là benchmark |
| T2 cho kết quả: lợi ích chỉ là regularization (giả thuyết a) | Trung bình | Vẫn là kết quả có giá trị (nói rõ RML là một dạng augmentation có thông tin); không làm bài sụp |
| Pivot bị đọc là "HARKing" | Trung bình | Pivot 1 có trong plan §9 trước field test; mọi kết quả synthetic đã pre-register; nói thẳng thời điểm quyết định |
| Hạn 31/10 không đủ cho mức B | Chắc chắn | Người dùng chọn: nộp mức A (benchmark chưa đầy, ghi rõ) hoặc dời hạn. *(Đã giải quyết 29/10: mức B, hạn 14/11/2026.)* |
| Bản thảo dài gấp khoảng 2,7 lần giới hạn số từ của venue (thêm 29/10: thân bài khoảng 14.750 từ sau A6; C&G khoảng 5.500 từ theo nguồn thứ cấp, chưa kiểm trên trang chính thức) | Cao | Người dùng bỏ lượt rút gọn độ dài ngày 29/10 (plan §12 ý 25); rủi ro vẫn mở, chưa có biện pháp. Nếu sau này có rút gọn thì không bỏ kết quả âm hay deviation đã ghi (plan §9, R9). |
| Novelty của phần lý thuyết bị trùng với label-noise literature | Thấp–trung bình | T10: tìm kiếm "misaligned labels / index noise / registration noise regression" trước khi viết; khác biệt là nhiễu ở chỉ số + anchor + vật lý |
| Benchmark không ai dùng | Trung bình | S7 làm tử tế: một lệnh sinh, một lệnh chấm, bảng tham chiếu; giấy phép rõ |
---
## 6. Quyết định (chốt 29/10/2026)
Người dùng chốt ý 1 và 5; ý 2–4 do agent chốt theo bằng chứng (quy ước AGENTS.md: không chờ GVHD). Đã ghi vào `docs/plan.md` §12 ý 22, `AGENTS.md` và `report.html`.
| # | Việc | Quyết định | Căn cứ |
| --- | --- | --- | --- |
| 1 | Hạn nộp | **Mức B. Hạn mới: thứ 7, 14/11/2026** (dời 2 tuần). Ngưỡng và luật của mọi gate không đổi; chỉ ngày đổi. | Mức A chỉ cho một "controlled study" chưa đầy lưới; mục 4.2 cần 1–2 tuần GPU và đóng gói. |
| 2 | S2 (misspec) | **Bắt buộc, phạm vi hẹp**: ba trục (rock physics sai hệ số; wavelet sai pha và băng thông; σ_b / prior drift sai), hai regime (R10, Rm5), c = 1, N ∈ {4, 16}, realization 8–15, tập phương pháp rút gọn (Oracle, B3c-R, B3d-Sa, M2-Sa). Thiết kế trên dev 902–905; khóa trong `configs/protocol_bench.yaml` trước lần chạy đầu. Nếu đến 10/11 chưa xong S2 thì bài gọi là "controlled synthetic study", không gọi là benchmark. | Rủi ro cao nhất ở mục 5 là "cùng simulator"; không có S2 thì không trả lời được. |
| 3 | T2 | **Exploratory / explanatory**, trên realization 8–15 với bank P2r đã có. Khai báo trước khi chạy ở `docs/research/t2-mechanism.md` (cách làm như P4x). Trong bài là "mechanism analysis" kèm Mệnh đề 3 (*ghi chú 29/10: đánh số lúc lập kế hoạch; trong bài, giả thuyết tái đăng ký ngầm là Nhận xét 1, còn Mệnh đề 3 của bài là hai cấu trúc sai số của tie*); không phải gate, không claim confirmatory. Không sinh realization 16–23 cho T2. | Giả thuyết (c) hình thành sau khi thấy H2b; ba thí nghiệm cần lặp; một lượt SMC riêng cho T2 không vừa hai tuần. |
| 4 | Venue | **Chính: *Computers & Geosciences*.** Dự phòng: *Geophysical Prospecting*. Quartile tra lại khi nộp [XM]. | C&G nhận bài benchmark kèm code và yêu cầu code/data availability, khớp S7. |
| 5 | P4x | **Bỏ hẳn.** Không dùng trong bài, không chạy V3, không tổng hợp. `exploratory/` và `outputs/p4x/` giữ trên đĩa làm hồ sơ, không xóa. Job `exploratory/run_p4x.sh` (cuda:0) ở 560/921 lúc 03:43 UTC 29/10 khi chốt; lệnh dừng từ phiên agent bị từ chối, nên job tự chạy hết (khoảng 40 phút) và kết quả không dùng. | Không phục vụ bài mới; biến thể chọn sau khi thấy nhãn test. |
### 6.1 Lịch mức B (29/10 → 14/11/2026)
| Ngày | Việc | Tham chiếu |
| --- | --- | --- |
| T5 29/10 | Chốt quyết định; cập nhật plan, AGENTS, report; khảo sát dataset field public (`field-dataset-survey.md`: chưa có dataset nào xác nhận đủ điều kiện). *Cập nhật:* trong ngày còn thử Teapot Dome (T0 và pilot P-a đều trượt; người dùng chọn quay về lịch mức B; plan §12 ý 23) và viết xong mức A (plan §12 ý 24) | A6; A1–A5 |
| T6 30/10 – T7 31/10 | ~~Mức A: viết lại abstract, intro, contributions, discussion, conclusion theo 3.1–3.3; T1, T4, T8 thành mệnh đề; T4 từ npz; T3 giải tích + mô phỏng trên dự đoán P2r; T10 related work~~ (xong sớm ngày 29/10). Thêm trích dẫn dataset F3 và Volve; còn lại là dự phòng. ~~Lượt rút gọn độ dài~~ (bỏ theo quyết định của người dùng ngày 29/10; plan §12 ý 25) | plan §6.1; rủi ro ở mục 5 |
| CN 1/11 | T2 exploratory: khai báo `t2-mechanism.md` rồi chạy ba thí nghiệm | 4.2 tuần 1 |
| T2 2/11 – T3 3/11 | Sửa generator cho S2 (tham số misspec); dev trên 902–905; viết và **khóa `protocol_bench.yaml`** (S1, S2, S3, S4, S8) kèm `.sha256` và `.lock.json` trước lần chạy đầu | 4.2 |
| T4 4/11 – T5 5/11 | S1 (lấp lưới c ∈ {0.5, 1.5}, N ∈ {2, 8}), S3 (B4 dưới SMC), S4 (backbone thứ hai) trên hai GPU | 4.2 tuần 1 |
| T6 6/11 – T7 7/11 | S2 ba trục; S8/T8 cycle-skip | 4.2 tuần 2 |
| CN 8/11 – T3 10/11 | S7: đóng gói benchmark (một lệnh sinh, một lệnh chấm, bảng tham chiếu, README, hash, Zenodo); viết lại §4–5 theo kết quả | 4.2 |
| T4 11/11 – T5 12/11 | Review nội bộ; hình; phụ lục chứng minh; gói tái lập | — |
| T6 13/11 | Kiểm tra novelty lần cuối; tra quartile; preprint | — |
| **T7 14/11** | **Nộp** | — |
**Thứ tự cắt phạm vi nếu trễ** (cắt từ trên xuống; không cắt ngưỡng): (1) S4 backbone thứ hai; (2) S8/T8; (3) S2 rút còn một trục rock physics, khi đó tên gọi đổi thành "controlled synthetic study"; (4) S1 rút còn c ∈ {0.5, 1.5} với N = 4/16; (5) T2 chỉ giữ thí nghiệm (1), responsibility-weighted warp error.

View File

@@ -37,7 +37,7 @@
pages = {M93--M108}, pages = {M93--M108},
doi = {10.1190/geo2023-0614.1}, doi = {10.1190/geo2023-0614.1},
url = {https://doi.org/10.1190/geo2023-0614.1}, url = {https://doi.org/10.1190/geo2023-0614.1},
note = {P03; survey evidence level A; full text added 2026-10-26 (refs/geo-2023-0614.1.pdf): labels matched to seismic with time-depth from well-to-seismic ties taken as given; carbonate reservoir, 48 wells} note = {P03; survey evidence level A; full text added 2026-10-26 (refs/xu2024sts.pdf): labels matched to seismic with time-depth from well-to-seismic ties taken as given; carbonate reservoir, 48 wells}
} }
@article{chen2024multidimensional, @article{chen2024multidimensional,
@@ -49,7 +49,7 @@
pages = {1--15}, pages = {1--15},
doi = {10.1109/TGRS.2024.3460184}, doi = {10.1109/TGRS.2024.3460184},
url = {https://doi.org/10.1109/TGRS.2024.3460184}, url = {https://doi.org/10.1109/TGRS.2024.3460184},
note = {P04; survey evidence level A; accessed 2026-10-23} note = {P04; survey evidence level A; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
} }
@article{li2024bpinn, @article{li2024bpinn,
@@ -62,7 +62,7 @@
pages = {M185--M196}, pages = {M185--M196},
doi = {10.1190/geo2023-0737.1}, doi = {10.1190/geo2023-0737.1},
url = {https://doi.org/10.1190/geo2023-0737.1}, url = {https://doi.org/10.1190/geo2023-0737.1},
note = {P05; survey evidence level A; accessed 2026-10-23} note = {P05; survey evidence level A; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
} }
@article{ntibahanana2024ensemble, @article{ntibahanana2024ensemble,
@@ -88,7 +88,7 @@
pages = {698--712}, pages = {698--712},
doi = {10.1111/1365-2478.13333}, doi = {10.1111/1365-2478.13333},
url = {https://doi.org/10.1111/1365-2478.13333}, url = {https://doi.org/10.1111/1365-2478.13333},
note = {P07; survey evidence level F; accessed 2026-10-23} note = {P07; survey evidence level F; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
} }
@article{li2025cascadedtie, @article{li2025cascadedtie,
@@ -113,7 +113,7 @@
eid = {106194}, eid = {106194},
doi = {10.1016/j.compgeo.2024.106194}, doi = {10.1016/j.compgeo.2024.106194},
url = {https://doi.org/10.1016/j.compgeo.2024.106194}, url = {https://doi.org/10.1016/j.compgeo.2024.106194},
note = {P09; survey evidence level A; accessed 2026-10-23} note = {P09; survey evidence level A; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
} }
@article{li2026leakage, @article{li2026leakage,
@@ -203,7 +203,7 @@
pages = {2000--2009}, pages = {2000--2009},
doi = {10.1190/1.1635053}, doi = {10.1190/1.1635053},
url = {https://doi.org/10.1190/1.1635053}, url = {https://doi.org/10.1190/1.1635053},
note = {Full text read; marker mistie modeled as latent time shifts with a triangular prior, estimated jointly with the wavelet by MCMC; refs/Bayesian wavelet estimation from seismic and well data.pdf} note = {Full text read; marker mistie modeled as latent time shifts with a triangular prior, estimated jointly with the wavelet by MCMC; refs/buland2003bayesianwavelet.pdf}
} }
@article{gunning2006waveletextractor, @article{gunning2006waveletextractor,
@@ -215,7 +215,7 @@
pages = {681--695}, pages = {681--695},
doi = {10.1016/j.cageo.2005.10.001}, doi = {10.1016/j.cageo.2005.10.001},
url = {https://doi.org/10.1016/j.cageo.2005.10.001}, url = {https://doi.org/10.1016/j.cageo.2005.10.001},
note = {Full text read (added 2026-10-26); MAP estimate of wavelet jointly with checkshot/marker times (Gaussian prior), registration shift and lateral positioning error per well, Laplace posterior, wavelet span by marginal likelihood; refs/j.cageo.2005.10.001.pdf} note = {Full text read (added 2026-10-26); MAP estimate of wavelet jointly with checkshot/marker times (Gaussian prior), registration shift and lateral positioning error per well, Laplace posterior, wavelet span by marginal likelihood; refs/gunning2006waveletextractor.pdf}
} }
@article{wu2017multiwelltie, @article{wu2017multiwelltie,
@@ -228,7 +228,7 @@
pages = {IM13--IM20}, pages = {IM13--IM20},
doi = {10.1190/geo2016-0295.1}, doi = {10.1190/geo2016-0295.1},
url = {https://doi.org/10.1190/geo2016-0295.1}, url = {https://doi.org/10.1190/geo2016-0295.1},
note = {Full text read (HAL version, refs/geo2016-0295.pdf); first published online 2016-11-09} note = {Full text read (HAL version, refs/wu2017multiwelltie.pdf); first published online 2016-11-09}
} }
@article{tschannen2022partialtie, @article{tschannen2022partialtie,
@@ -240,7 +240,7 @@
pages = {105120}, pages = {105120},
doi = {10.1016/j.cageo.2022.105120}, doi = {10.1016/j.cageo.2022.105120},
url = {https://doi.org/10.1016/j.cageo.2022.105120}, url = {https://doi.org/10.1016/j.cageo.2022.105120},
note = {Full text read; variational CNN for wavelet (phase uncertainty), Bayesian optimization of bulk shift within user bounds; refs/1-s2.0-S0098300422000784-main.pdf} note = {Full text read; variational CNN for wavelet (phase uncertainty), Bayesian optimization of bulk shift within user bounds; refs/tschannen2022partialtie.pdf}
} }
@article{ali2025syntheticpseudowells, @article{ali2025syntheticpseudowells,
@@ -253,7 +253,7 @@
eid = {31}, eid = {31},
doi = {10.1007/s10462-024-11030-8}, doi = {10.1007/s10462-024-11030-8},
url = {https://doi.org/10.1007/s10462-024-11030-8}, url = {https://doi.org/10.1007/s10462-024-11030-8},
note = {Full text read; target is P-impedance from prestack gathers, not porosity; published online 2024-11-30; refs/s10462-024-11030-8.pdf} note = {Full text read; target is P-impedance from prestack gathers, not porosity; published online 2024-11-30; refs/ali2025syntheticpseudowells.pdf}
} }
@misc{herrera2012automatedtie, @misc{herrera2012automatedtie,
@@ -278,7 +278,7 @@
eprint = {1703.01541}, eprint = {1703.01541},
archivePrefix = {arXiv}, archivePrefix = {arXiv},
url = {https://proceedings.mlr.press/v70/cuturi17a.html}, url = {https://proceedings.mlr.press/v70/cuturi17a.html},
note = {refs/SoftDTW_Cuturi2017.pdf} note = {refs/cuturi2017softdtw.pdf}
} }
@inproceedings{leguen2019dilate, @inproceedings{leguen2019dilate,
@@ -289,7 +289,7 @@
eprint = {1909.09020}, eprint = {1909.09020},
archivePrefix = {arXiv}, archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1909.09020}, url = {https://arxiv.org/abs/1909.09020},
note = {DILATE; refs/DILATE_LeGuen2019.pdf} note = {DILATE; refs/leguen2019dilate.pdf}
} }
@inproceedings{lakshminarayanan2017deepensembles, @inproceedings{lakshminarayanan2017deepensembles,
@@ -300,7 +300,7 @@
eprint = {1612.01474}, eprint = {1612.01474},
archivePrefix = {arXiv}, archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1612.01474}, url = {https://arxiv.org/abs/1612.01474},
note = {refs/DeepEnsembles_Lakshminarayanan2017.pdf} note = {refs/lakshminarayanan2017deepensembles.pdf}
} }
@inproceedings{kendall2017uncertainties, @inproceedings{kendall2017uncertainties,
@@ -311,7 +311,7 @@
eprint = {1703.04977}, eprint = {1703.04977},
archivePrefix = {arXiv}, archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1703.04977}, url = {https://arxiv.org/abs/1703.04977},
note = {refs/HeteroscedasticUQ_Kendall2017.pdf} note = {refs/kendall2017uncertainties.pdf}
} }
@article{gneiting2007scoringrules, @article{gneiting2007scoringrules,
@@ -324,7 +324,7 @@
pages = {359--378}, pages = {359--378},
doi = {10.1198/016214506000001437}, doi = {10.1198/016214506000001437},
url = {https://doi.org/10.1198/016214506000001437}, url = {https://doi.org/10.1198/016214506000001437},
note = {Proper scoring rules and CRPS; refs/ProperScoringRules_Gneiting2007.pdf} note = {Proper scoring rules and CRPS; refs/gneiting2007scoringrules.pdf}
} }
@inproceedings{murray2010ess, @inproceedings{murray2010ess,
@@ -338,7 +338,7 @@
eprint = {1001.0175}, eprint = {1001.0175},
archivePrefix = {arXiv}, archivePrefix = {arXiv},
url = {https://proceedings.mlr.press/v9/murray10a.html}, url = {https://proceedings.mlr.press/v9/murray10a.html},
note = {refs/EllipticalSliceSampling_Murray2010.pdf} note = {refs/murray2010ess.pdf}
} }
@article{ravasi2020pylops, @article{ravasi2020pylops,
@@ -350,7 +350,7 @@
pages = {100361}, pages = {100361},
doi = {10.1016/j.softx.2019.100361}, doi = {10.1016/j.softx.2019.100361},
url = {https://doi.org/10.1016/j.softx.2019.100361}, url = {https://doi.org/10.1016/j.softx.2019.100361},
note = {Local copy is the arXiv version (1907.12349); refs/PyLops_Ravasi2020.pdf} note = {Local copy is the arXiv version (1907.12349); refs/ravasi2020pylops.pdf}
} }
@inproceedings{alfarraj2019semisupervised, @inproceedings{alfarraj2019semisupervised,
@@ -361,5 +361,5 @@
year = {2019}, year = {2019},
doi = {10.1190/segam2019-3215902.1}, doi = {10.1190/segam2019-3215902.1},
url = {https://doi.org/10.1190/segam2019-3215902.1}, url = {https://doi.org/10.1190/segam2019-3215902.1},
note = {Local copy is the arXiv version (1905.13412); refs/AlfarrajAlRegib2019_semi-supervised-AI-inversion.pdf} note = {Local copy is the arXiv version (1905.13412); refs/alfarraj2019semisupervised.pdf}
} }

View File

@@ -12,7 +12,7 @@ Ngày chốt tìm kiếm: **23/10/2026**. Mục tiêu: bài phương pháp có
- Research gap dưới đây là **gap ứng viên trong nhóm tài liệu đã rà soát**, không phải chứng nhận rằng chưa ai từng làm trên toàn bộ literature. - Research gap dưới đây là **gap ứng viên trong nhóm tài liệu đã rà soát**, không phải chứng nhận rằng chưa ai từng làm trên toàn bộ literature.
- Không lập bảng xếp hạng MSE/R² giữa các paper khác dataset, đơn vị, preprocessing, lượng giếng và kiểu ground truth. - Không lập bảng xếp hạng MSE/R² giữa các paper khác dataset, đơn vị, preprocessing, lượng giếng và kiểu ground truth.
Tài liệu dự án đối chiếu: [báo cáo hiện tại](../../outputs/LeVietHoangLam_22BI13235.pdf), [code huấn luyện v2](</Users/hola/Downloads/test 2/train_open_patch_v2.py>), [chuẩn bị dữ liệu](</Users/hola/Downloads/test 2/prepare_data.py>) và [suy luận volume](</Users/hola/Downloads/test 2/predict_porosity_volume.py>). Tài liệu dự án đối chiếu: [báo cáo hiện tại](../LeVietHoangLam_22BI13235.pdf), [code huấn luyện v2](<../../code_thesis/train_open_patch_v2.py>), [chuẩn bị dữ liệu](<../../code_thesis/prepare_data.py>) và [suy luận volume](<../../code_thesis/predict_porosity_volume.py>).
## 2. Những công trình cần đặt cạnh bài của bạn ## 2. Những công trình cần đặt cạnh bài của bạn

View File

@@ -0,0 +1,46 @@
# Kiểm tra output luận văn
Ngày kiểm tra: **27/10/2026**. Code nằm ở [`code_thesis/`](../../code_thesis/); output gốc ở [`outputs_thesis/`](../../outputs_thesis/); kích thước và SHA-256 của cả 7 file nằm trong [manifest](../../data_manifest/thesis_outputs.json).
## Bộ artifact hiện có
| File | Kích thước (byte) | Kết quả kiểm tra |
| --- | ---: | --- |
| `f3_wells_dataset.npz` | 439189 | Có 3 giếng F03-4, F02-1, F06-1; SHA-256 trùng dataset đã audit ngày 26/10 |
| `open_loop_patch_best_v2.pt` | 680434 | Đọc được cấu trúc ZIP của PyTorch; metadata có GRU tầng 2, `head_skip` và `bias`, phù hợp kiến trúc v2 |
| `open_loop_patch_preds_F06-1_v2.npz` | 5316 | 126 mẫu; có `time`, `y_true`, `y_pred`, bản Z-score và thống kê chuẩn hóa |
| `porosity_volume_600_1100ms.npz` | 278756708 | `vol` float32, shape `(651, 951, 126)`; 78006726 giá trị hữu hạn, không còn rỗng |
| `porosity_comparison_F06-1.png` | 87965 | Đã ghi SHA-256 |
| `plots/F06-1_overlay.png` | 94437 | Đã ghi SHA-256 |
| `plots/F06-1_overlay_scatter.png` | 48344 | Đã ghi SHA-256 |
Kiểm tra được thực hiện bằng cách đọc ZIP/NPY, tính SHA-256 và tính lại metric trực tiếp từ các mảng dự đoán đã lưu. Máy hiện chưa có Python/PyTorch, nên **chưa chạy suy luận lại checkpoint** và chưa giải tuần tự các object giếng trong dataset. Nhận định về kiến trúc checkpoint dựa trên metadata, chưa phải kiểm chứng đầu ra của mô hình.
## Kết quả F06-1 từ file v2
Tính trên 126 cặp `y_true`/`y_pred` đã lưu, không dịch thời gian:
| Metric | Giá trị |
| --- | ---: |
| MSE, thang porosity | 0.0018714971 |
| RMSE | 0.04326080 (4.326 p.u.) |
| PCC | 0.02947452 |
| R² | -0.34600558 |
| std(pred) / std(true) | 0.48645224 |
| MSE, thang Z-score | 1.48250972 |
`y_mu = 0.2904474239`, `y_std = 0.0355300465`, `C = 9`. Dự đoán porosity nằm trong `[0.25163853, 0.34457749]`. File lưu `lags = (3, 0, -13)` theo thứ tự F03-4, F02-1, F06-1. Trong code v2 hiện có, nhãn test được giữ nguyên; lag test chỉ được in để chẩn đoán.
Thử best-shift theo đúng quy ước của `best_shift_metrics` trong khoảng ±16 mẫu cho lag +16 (64 ms), còn 110 cặp: PCC 0.10677496, MSE 0.0015107914. Kết quả này khớp `best_shift_real = 16` đã lưu. Đây là chẩn đoán dùng nhãn test, không phải metric blind test. Cả hai cách tính đều chưa khớp PCC 0.34 / MSE 0.015 được trích từ luận văn.
## Thang đo volume và các ghi chú cần thay thế
Volume lưu giá trị trong `[-3.84333062, 3.74447894]`, cùng `y_lo = 0.2319448653`, `y_hi = 0.4878670500`. Trong code suy luận, `vol` là đầu ra thô của mạng; các script vẽ giải chuẩn bằng min–max `y_lo`/`y_hi`, trong khi code train v2 dùng Z-score `y_mu`/`y_std`. Vấn đề thang đo đã nêu trong plan vẫn còn; không diễn giải trực tiếp `vol` như porosity vật lý.
Nhận định ngày 26/10 về checkpoint v1, PCC 0.18 và volume 0 byte thuộc bộ file cũ. Bộ hiện tại đã có v2 và volume đọc được. Dataset giữ nguyên SHA-256, nên các phát hiện trước về tọa độ giếng và TWT vẫn áp dụng. Nội dung 8 script trong `code_thesis/` khớp bản trước khi đổi tên sau khi chuẩn hóa xuống dòng.
Giữ code và output gốc để đối chiếu. Pipeline nghiên cứu tiếp tục dùng `ml_porosity/`, `scripts/` và ghi vào `outputs/`. Khi đã có môi trường Python của dự án, kiểm tra lại manifest bằng:
```bash
python scripts/00_data_manifest.py --dataset thesis --check
```

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,8 @@
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. 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.
**Bổ sung ngày 29/10/2026 (Pivot 1, [plan.md](plan.md) §12 ý 24):** mục 6 là bản tiếng Việt của mục 4.3–4.5 trong bài (`paper/sections/04_theory.tex`): Mệnh đề 3–6, Hệ quả 3–4, Nhận xét 1, cận ρ* và lập luận mẫu hữu hạn. Số mệnh đề theo bài. Mục 1.4 và 6.4 có ghi chú sửa cách đọc cận 1/B(σ_post): cận đã đăng ký là cấu trúc (a); bài báo thêm cận (b) post hoc. Cũng ngày 29/10, nhận định trước đó "hai cấu trúc gần như cho cùng một cận" đã được rút lại.
- Mục 1–2 là chứng minh, đúng dưới các giả thiết được nêu rõ. - 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 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`. - 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`.
@@ -156,7 +158,7 @@ Gọi δ(t) = τ̄(t) − τ(t) là sai số của warp trung bình. Nếu poste
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". 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.** **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. - 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. (Sửa 29/10/2026: méo quần thể có trọng số f⁴, nên trung vị tần số của méo nằm ở 67–72 Hz dù phần lớn công suất ở dưới 25 Hz; xem ghi chú cuối mục.)
- 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). - 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). - 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. - 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.
@@ -168,6 +170,16 @@ Gọi δ(t) = τ̄(t) − τ(t) là sai số của warp trung bình. Nếu poste
- 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. - 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. - 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.
**Sửa ngày 29/10/2026 (bài mục 4.3 và 6.3; chi tiết ở mục 6 dưới đây).**
- Hệ quả 1 ở trên coi sai số của warp trung bình là *classical* (độc lập với y), nên B3d-S bị làm mờ. Đó là một giả thiết, không phải hệ quả. Tie lấy bằng trung bình posterior là lý tưởng hoá tự nhiên của cấu trúc *Berkson* (Mệnh đề 3(b)): tối ưu quần thể của nó bị làm **sắc** bởi 1/Q, không bị làm mờ.
- 1/B(σ_post) đúng là ρ* (mục 6.4) dưới cấu trúc (a) với sai số Gauss, lấy dự đoán của Oracle thay cho m (trong bài: 1/B_a). Dưới (b), tích phân méo lớn hơn một hệ số e^{4π²σ²f²}. Với σ = 2 ms, hệ số này là 1,10 ở 25 Hz và 1,77 ở 60 Hz. Trọng số f⁴ đẩy méo lên cao: với dự đoán Oracle của P2r (N = 16), 71–73% công suất kết hợp với nhãn nằm dưới 25 Hz, nhưng trung vị tần số của méo bậc dẫn là 67–72 Hz. Ở đó tích phân (b) bằng 1,5–1,7 lần tích phân (a) tại σ = 1,5 ms, 2,1–2,6 lần tại 2 ms và 3,3–4,6 lần tại 2,5 ms (`outputs/p2r/posthoc/meta.json`, `n16_spectra`). Cận tính cho cấu trúc này vì vậy không dùng được cho cấu trúc kia. Bản ghi trước đó viết "hệ số < 1,17, cấu trúc gần như không đổi cận". Nhận định đó sai vì chỉ xét |f| ≤ 25 Hz. Méo quần thể là bậc bốn theo σ, nên cận rất gần 1 khi posterior hẹp.
- Kiểm post hoc (`scripts/31_p2r_posthoc.py` → `outputs/p2r/posthoc/{bound.csv, blur_ab.csv, meta.json}`). Script đọc summary đã đăng ký và dự đoán Oracle trong `outputs/p2r/train/<regime>/cells/*.npz`, chạy khoảng 6 phút. Kết quả ở N = 16, 8 ô rộng:
- **Cận (a), đã đăng ký.** Tỉ số M2-Sa/B3d-Sa thấp hơn cận ở 7/8 ô tại σ_post và 6/8 tại sai số warp RMS của B3d-Sa trên giếng train. Ngoại lệ: R10tb c = 2 (σ_post 11,5 ms, sai số warp 19,1 ms; vượt mép lưới blur 6 ms nên `np.interp` trả 1/B(6 ms) = 0,634, cận tính đúng tại σ_post là 0,481; tỉ số 0,667), và R10tb c = 1 khi tính tại sai số warp (4,8 ms so với σ_post 1,9 ms; cận 0,710; tỉ số 0,890).
- **Cận (b), post hoc.** Làm sắc dự đoán Oracle bằng e^{+2π²σ²f²} và tính đúng tại độ rộng của từng ô. Tỉ số thấp hơn cận ở 3/8 ô tại σ_post, cả ba ở c = 1 (R0, R0h, R10tb). Lề ở R0h và R10tb < 0,004, nằm trong CI 95%. Tại sai số warp: 0/8.
- **Hai biến thể của (b).** Làm sắc cũng khuếch đại sai số ước lượng của chính Oracle, nên 1/B_b bị kéo thấp, nhất là ở c = 2. Biến thể b60 giữ hệ số ở giá trị 60 Hz phía trên 60 Hz. Biến thể phổ chéo thay phổ dự đoán Oracle bằng phổ chéo với nhãn thật. Cả hai cho cùng 3/8 tại σ_post; tại sai số warp chỉ còn R0 c = 1 (1/8). Với phổ chéo, cận (a) cũng chỉ bị vượt ở 5/8 ô tại σ_post và 3/8 tại sai số warp.
- **Oracle/B3d-Sa (post hoc; c = 1, N = 16).** 0,927 / 0,919 / 0,758 / 0,933 ở R0 / R0h / R10tb / Rm5. Tỉ số dưới cận (a) ở cả 4 ô, dưới cận (b) tại σ_post ở 3–4 ô tuỳ ước lượng, tại sai số warp ở 1–2 ô. Ở c = 0, mọi cận nằm trong 0,4% quanh 1, nhưng Oracle vẫn tốt hơn B3d-Sa 1–3%. Hai bên còn khác số vòng lặp (500 và 250).
- Vì vậy câu "tỉ số M2-S/B3d-S tốt nhất là ≈ 1/B(σ_post)" chỉ là cận quần thể. Nhận định "lợi ích của bank vượt cận" ghi trước đây không được xác lập. Nó chỉ đúng dưới (a). Dưới (b) nó chỉ còn ở c = 1 và gần như biến mất tại sai số warp đo được. Chưa kiểm sai số của warp trung bình có cấu trúc Berkson hay không (phép kiểm hiệp phương sai ở mục 6.1; T2 test (iv)). Nguồn lợi ích chưa xác định: có thể là hiệu chỉnh quần thể của cấu trúc Berkson, có thể là hiệu ứng mẫu hữu hạn (mục 6.5; T2, `docs/research/t2-mechanism.md`). M2-Sa không đạt Oracle ở ô rộng nào. Ở c = 1, N = 16 nó còn kém Oracle 4–6% (R0, R0h, Rm5) và 17% (R10tb); ở R10tb c = 2 là 63%. Nó đóng 27–46% khoảng cách B3d-Sa–Oracle ở c = 1 và 39–65% ở c = 2.
## 2. Mệnh đề 2 (nhận dạng) ## 2. Mệnh đề 2 (nhận dạng)
**Thiết lập.** **Thiết lập.**
@@ -380,11 +392,96 @@ Test: `test_rml_between_hard_min_and_mixture_mean` và `test_rml_small_lambda_is
- 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 đề 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. - Mệnh đề 2: dưới (B); sd(β) là xấp xỉ bậc hai.
- Bổ đề 1–5: chính xác, có test số. - Bổ đề 1–5: chính xác, có test số.
- **Heuristic.** λ = 1/τ_c (mục 3). - Mệnh đề 3–6, Hệ quả 3–4 (mục 6, thêm 29/10/2026): ở mức quần thể; chứng minh ở Phụ lục A của bài. Bank hiệu chỉnh (Mệnh đề 4) là lý tưởng hoá. Hệ quả 4 chỉ cho dấu ở bậc dẫn.
- **Heuristic.** λ = 1/τ_c (mục 3); lập luận mẫu hữu hạn (mục 6.5).
- **Chưa làm.** - **Chưa làm.**
- Tính nhất quán của estimator marginal likelihood (tuỳ chọn ở plan §4.6). - Tính nhất quán của estimator marginal likelihood (tuỳ chọn ở plan §4.6).
- Chẩn đoán strain energy. - Chẩn đoán strain energy.
- RML-EM (M3). - RML-EM (M3).
- Xác định nguồn lợi ích của bank: hiệu chỉnh quần thể trong cận ρ* dưới (b), hay hiệu ứng mẫu hữu hạn vượt cận đó (T2, exploratory, `docs/research/t2-mechanism.md`, khai báo trước khi chạy; test (iv) kiểm cấu trúc Berkson hay classical).
- Kiểm phần (b), (c) của Mệnh đề 5: ở P2r độ dài huấn luyện và nguồn nhãn lẫn vào nhau.
## 6. Cấu trúc sai số của tie, bank hiệu chỉnh, coverage, reference lệch (thêm 29/10/2026)
Bản tiếng Việt của mục 4.3–4.5 trong bài. Chứng minh ở Phụ lục A của bài (`paper/sections/A_proofs.tex`); ở đây chỉ phát biểu và nêu ý nghĩa.
**Ký hiệu thêm.** D là toàn bộ dữ liệu ở giếng (seismic, log, anchor); input X là hàm của D. u* là warp thật, y = y^{u*}; û = û(D) là tie điểm với nhãn ỹ = y^{û}. Sai số viết được theo hai chiều:
- ỹ(t) = y(t + δ(t)), với δ(t) = t_{u*}(z_{û}(t)) − t;
- y(t) = ỹ(t + ε(t)), với ε(t) = t_{û}(z_{u*}(t)) − t.
m̃(t) = E[ỹ(t) | X] là predictor tối ưu của nhãn điểm; P(f) = E e^{i2πfδ}, Q(f) = E e^{i2πfε}.
### 6.1 Mệnh đề 3 (hai cấu trúc sai số)
Giả thiết (A2) cho y và ỹ.
- **(a) Classical.** Nếu δ(t) độc lập với y(·) khi biết X, với phân phối có điều kiện p_t(·|X), thì m̃(t) = ∫ p_t(d|X) m(t + d) dd và Var(ỹ(t)|X) = ∫ p_t(d|X) Var(y(t + d)|X) dd + Var_{p_t}[m(t + d)].
- **(b) Berkson.** Nếu ε(t) độc lập với D khi biết X, với phân phối có điều kiện q_t(·|X), thì m(t) = ∫ q_t(e|X) m̃(t + e) de và Var(y(t)|X) = ∫ q_t(e|X) Var(ỹ(t + e)|X) de + Var_{q_t}[m̃(t + e)].
- Nếu p_t, q_t không phụ thuộc t thì, trung bình trên cửa sổ và bỏ hiệu ứng biên, nhãn điểm có phương sai có điều kiện lớn hơn dưới (a) và nhỏ hơn dưới (b). Nếu chúng không phụ thuộc cả t lẫn X thì m̃ là m lọc bởi P dưới (a), và m là m̃ lọc bởi Q dưới (b). Với sai số Gauss trung bình 0, phương sai σ², hệ số truyền từ m sang m̃ là e^{−2π²σ²f²} dưới (a) và e^{+2π²σ²f²} dưới (b).
**Ý nghĩa.**
- (a) là cấu trúc classical của mô hình sai số đo (sai số độc lập với giá trị thật); (b) là cấu trúc Berkson (sai số độc lập với giá trị được gán). Ở đây sai số nằm ở chỉ số thời gian của nhãn, và hai cấu trúc làm lệch predictor học được theo hai chiều ngược nhau: (a) làm mờ predictor và nới rộng phương sai học được; (b) làm sắc predictor và thu hẹp phương sai.
- Tie lấy bằng trung bình posterior, û = E[u* | D], là lý tưởng hoá tự nhiên của (b): E[u* − û | D] = 0 theo cách dựng, và trong mô hình tuyến tính–Gauss u* − û độc lập với D. Với offset b của warp, sai số thời gian bằng sai số posterior của b nên thừa hưởng tính chất này; với drift thì chỉ gần đúng, khi posterior hẹp.
- Tie khớp theo cách khác (ví dụ cực đại tương quan synthetic–seismic) có thể theo một trong hai cấu trúc hoặc không theo cấu trúc nào. Trên dữ liệu synthetic phân biệt được: với offset, classical nghĩa là Cov(b̂ − b*, b*) = 0, Berkson nghĩa là Cov(b* − b̂, b̂) = 0.
### 6.2 Mệnh đề 4 (bank hiệu chỉnh)
Bank {(u_s, π_s)} gọi là *hiệu chỉnh* nếu Σ_s π_s G(u_s, D) = E[G(u*, D) | D] với mọi G khả tích. Với bank hiệu chỉnh:
- (a) nhãn trung bình ȳ = Σ_s π_s y^{u_s} thoả ȳ(t) = E[y(t) | D] và E[ȳ(t) | X] = m(t);
- (b) với mọi mạng (μ_θ, σ_θ) chỉ phụ thuộc dữ liệu qua X, E[Σ_s π_s ℓ_s] = E[ℓ*], trong đó ℓ* là log-likelihood cửa sổ của nhãn tại warp thật.
Do đó giới hạn λ → 0 của RML (Bổ đề 2) có cùng nghiệm tối ưu quần thể với huấn luyện trên nhãn thật (μ = m, σ² = Var(y | X)), và MSE trên nhãn trung bình có nghiệm μ = m.
**Lưu ý.**
- Hiệu chỉnh là lý tưởng hoá; nó đúng với mẫu posterior chính xác khi S → ∞. Dưới giả thiết này, lấy biên theo posterior khử sai lệch quần thể của cả hai cấu trúc.
- Warp trung bình không có tính chất này. B3d-Sa học nhãn tại warp trung bình ū, không phải nhãn trung bình. Khai triển y^u quanh ū: ȳ − y^{ū} = ½ Σ_s π_s (u_s − ū)ᵀ ∇²_u y^{ū} (u_s − ū) + O(‖u_s − ū‖³), nên hai nhãn chỉ trùng nhau tới bậc một theo độ trải posterior. Nếu sai số thời gian của warp trung bình theo (b), tối ưu quần thể của B3d-Sa bị làm sắc bởi 1/Q, còn của nhãn trung bình thì đúng.
### 6.3 Hệ quả 3 (hai mode) và Nhận xét 1 (λ > 0)
- **Hệ quả 3.** Cho sai số (δ dưới (a), ε dưới (b)) hằng trên cửa sổ, bằng ±Δ/2 với xác suất ½ mỗi bên, độc lập với X. Khi đó P = Q = cos(πfΔ), và dưới cả hai cấu trúc hệ số truyền từ m sang m̃ âm khi 1/(2Δ) < |f| < 3/(2Δ): ở đó nhãn điểm kéo mạng về sai dấu. Sai số Gauss cùng phương sai Δ²/4 có P = e^{−π²Δ²f²/2} > 0 ở mọi tần số. Nhãn trung bình của bank hiệu chỉnh có hệ số truyền 1. Dưới (a), bank gồm nhãn điểm dịch ±Δ/2 với trọng số bằng nhau có hệ số truyền cos²(πfΔ) ≥ 0.
- Đảo pha là tính chất của sai số đa mode mà một tóm tắt Gauss che mất. Nếu hai mode cách nhau một chu kỳ trội, Δ = 1/f_0, dải đảo là f_0/2 < |f| < 3f_0/2. Seismic F3 có đỉnh gần 60 Hz, nên dải đảo là 30–90 Hz. Bước nhảy chu kỳ cho sai số kiểu này; ở c = 2 posterior SMC đa mode. Trong ví dụ này, bank đặt tâm tại nhãn điểm chỉ khử đảo dấu bằng cách làm suy giảm thêm băng.
- **Nhận xét 1.** Mệnh đề 4 chỉ nói về giới hạn λ → 0. Khai triển hàm sinh cumulant: RML_λ = −(1/n)[Σ_s π_s ℓ_s + (λ/2) Var_π(ℓ) + O(λ²)]. Số hạng thứ hai thưởng cho predictor khớp một số thành viên của bank tốt hơn hẳn các thành viên khác. Với λ > 0, responsibilities của Bổ đề 3 dồn trọng số về các thành viên khớp với mạng hiện tại, tức một kiểu tái đăng ký ngầm, và nghiệm tối ưu quần thể nói chung không còn là (m, Var(y | X)).
### 6.4 Bank được lợi tối đa bao nhiêu (ρ*)
- Vì E[y − m | X] = 0, mọi predictor h chỉ phụ thuộc dữ liệu qua X thoả E|B(h − y)|² = E|B(m − y)|² + E|B(h − m)|². Ở mức quần thể, không phương pháp nào thắng Oracle về band MSE.
- Nếu phương pháp nhãn điểm hội tụ về m̃ và phương pháp bank về m, tỉ số band RMSE của chúng là ρ* = (1 + E|B(m̃ − m)|² / E|B(m − y)|²)^{−1/2}, và không phương pháp nào hơn nhãn điểm quá hệ số này.
- Với sai số không phụ thuộc t và X: E|B(m̃ − m)|² = ∫_{|f|≥f_c} |1 − P|² S_m df dưới (a), và ∫_{|f|≥f_c} |1 − Q|² |Q|^{−2} S_m df dưới (b). Với sai số Gauss, cả hai tích phân bằng (2π²σ²f²)² S_m ở bậc dẫn, nên **méo quần thể là bậc bốn theo σ**. Ngoài bậc dẫn, tích phân (b) lớn hơn tích phân (a) một hệ số e^{4π²σ²f²}. Với σ = 2 ms, hệ số này là 1,10 ở 25 Hz và 1,77 ở 60 Hz. Trọng số f⁴ đẩy méo lên tần số cao. Với dự đoán Oracle của P2r, 71–73% công suất kết hợp với nhãn nằm dưới 25 Hz, nhưng trung vị tần số của méo bậc dẫn là 67–72 Hz. Tích phân (b) bằng 1,5–1,7 lần, 2,1–2,6 lần và 3,3–4,6 lần tích phân (a) tại σ = 1,5, 2 và 2,5 ms. Cận tính cho cấu trúc này vì vậy không dùng được cho cấu trúc kia. Bản trước viết "hệ số < 1,17, cấu trúc gần như không đổi ρ*". Nhận định đó sai vì chỉ xét |f| ≤ 25 Hz (sửa 29/10/2026).
- Cận 1/B(σ_post) dùng ở mục 1.4 và trong H2b là ρ* dưới (a) với sai số Gauss, lấy dự đoán của mạng Oracle thay cho m (trong bài: 1/B_a). Bài báo cũng báo 1/B_b, cùng ước lượng đó dưới (b), tính post hoc (Bảng `tab:h2b`). Kết quả kiểm post hoc ở ghi chú cuối mục 1.4.
### 6.5 Mẫu hữu hạn (heuristic, không phải định lý)
- Bản thân sai số của nhãn là bậc một. Với sai số trung bình 0, phương sai σ²: ỹ − y ≈ δ·y′ dưới (a) và ỹ − y ≈ −ε·ỹ′ dưới (b). Ở bậc này trung bình có điều kiện theo X bằng 0, và với sai số hằng trên cửa sổ, phương sai trong băng là σ² ∫_{|f|≥f_c} (2πf)² S_y df. Phần lớn phương sai này chỉ dịch chuyển phần nhiễu nhãn vốn không đoán được từ X.
- Tới bậc hai theo σ và trung bình trên cửa sổ, phương sai có điều kiện mà một mạng học trên ỹ phải hấp thụ tăng khoảng trung bình của σ² m′² dưới (a) và giảm khoảng chừng đó dưới (b) (Mệnh đề 3). Đây là hiệu ứng bậc hai, so với méo bậc bốn của m̃, nên khi có ít giếng, hiệu ứng mẫu hữu hạn có thể lớn hơn sai lệch quần thể.
- Lập luận gợi ý rằng sai số đúng cấu trúc (b) sẽ không làm mạng kém hơn Oracle tới bậc hai, vì nhãn mang ít nhiễu có điều kiện hơn nhãn thật. Bank còn có thể đổi việc học mẫu hữu hạn theo cách ρ* không thấy: phương sai học được hấp thụ độ trải của bank và giảm trọng số các mẫu mà thành viên bank bất đồng; với λ > 0, responsibilities tái đăng ký nhãn trong lúc huấn luyện (Nhận xét 1). Bài mục 6.3 so lợi ích đo được với ρ*.
### 6.6 Mệnh đề 5 (coverage)
Ký hiệu: phương pháp j dự báo trung bình μ và phương sai s² ở mọi mẫu test; v_j = E s², w_j = E(y − μ)², ξ_j = v_j / w_j, kỳ vọng lấy trên mẫu test. ξ = 1 nghĩa là phương sai dự báo khớp sai số bình phương trung bình. `scripts/30_t4_coverage.py` ghi ξ ở cột `kappa`.
- (a) Với mọi j và O: ξ_j − ξ_O = (Δv − ξ_O Δw) / w_j, với Δv = v_j − v_O, Δw = w_j − w_O.
- (b) Cho y dừng và (A1) với P thực, 0 ≤ P ≤ 1. So nhãn điểm tại tối ưu quần thể (μ = m̃, s² = Var(ỹ | X)) với Oracle tại tối ưu (μ = m, s² = Var(y | X)). Khi đó ξ_O = 1 và ξ_j − ξ_O = (2 / w_j) ∫ P(1 − P) S_m df ≥ 0.
- (c) Dưới cấu trúc (b) của Mệnh đề 3, với q_t không phụ thuộc t và y dừng, nhãn điểm tại tối ưu quần thể có ξ_j ≤ 1. Bank hiệu chỉnh có ξ_j = 1.
- Nếu y − μ = sZ/√ξ với Z chuẩn tắc độc lập với s, khoảng μ ± z·s phủ với xác suất 2Φ(z√ξ) − 1, tăng theo ξ.
**Ý nghĩa và T4 (post hoc, bài mục 6.3, Bảng `tab:t4`).**
- (a) là đồng nhất thức, đúng cho mọi ensemble hữu hạn: j phủ nhiều hơn Oracle khi phương sai dự báo vượt Oracle quá ξ_O lần phần sai số bình phương dư. (b) và (c) là giới hạn quần thể: classical làm rộng khoảng của nhãn điểm, Berkson làm hẹp, bank hiệu chỉnh khớp Oracle.
- Ở ô R10, c = 1, N = 16, mọi ensemble đều quá hẹp: ξ là 0,19 ở Oracle và tối đa 0,66 (B5). Vì ξ_O nhỏ, chỉ cần dư một chút phương sai là phủ nhiều hơn Oracle.
- Độ dài huấn luyện và nguồn nhãn lẫn nhau: B3c-R học 500 vòng lặp (như Oracle) đạt cùng ξ với B3d-Sa ở 250 vòng. Trên dev của Thí nghiệm 1, coverage90 của Oracle đơn lẻ giảm 0,47 → 0,23 → 0,10 sau 125/500/2000 vòng lặp. Vì vậy (b) và (c) **chưa được kiểm**. Không claim hiệu chỉnh.
### 6.7 Mệnh đề 6 (reference lệch) và Hệ quả 4 (dung sai)
Thiết lập: reference ở giếng blind là y_ref(t) = y(t + ε_r), với ε_r hằng trên cửa sổ, độc lập với dự đoán ŷ và với nhãn thật y, có hàm đặc trưng Q_r; ŷ và y đồng dừng với phổ chéo S_{ŷy}.
- **Mệnh đề 6.** E|B(ŷ − y_ref)|² = E|B(ŷ − y)|² + 2 ∫_{|f|≥f_c} Re[(1 − Q_r(f)) S_{ŷy}(f)] df.
- Với sai số đối xứng, 0 ≤ 1 − Q_r ≤ 2, nên reference phạt sự khớp trong băng với nhãn thật. Số hạng thêm phụ thuộc phương pháp, nên có thể đảo thứ hạng hai phương pháp, và không triệt tiêu khi lấy trung bình qua giếng: thêm giếng blind giảm phương sai của phép so sánh, không giảm độ lệch.
- **Hệ quả 4.** Với hai phương pháp A và B, gọi G là lợi thế band MSE thật của A và G_r là lợi thế đo với y_ref. Khi đó G_r − G = 2 ∫_{|f|≥f_c} Re[(1 − Q_r)(S_{ŷ_B y} − S_{ŷ_A y})] df.
- Lấy ŷ_A = Hm và ŷ_B = HPm với các bộ lọc thực 0 ≤ H, P ≤ 1 (A học Oracle, B học tối ưu bị mờ của (a), cả hai bị co bởi cùng hệ số mẫu hữu hạn H). Khi đó G = ∫ H(1 − P)[2 − H(1 + P)] S_m df ≥ 0 và G_r = ∫ H(1 − P)[2Q_r − H(1 + P)] S_m df.
- Với H = 1 và sai số Gauss trung bình 0 có độ lệch chuẩn σ (tie của nhãn điểm) và σ_r (reference): 2Q_r − 1 − P = 2π²f²(σ² − 2σ_r²) + O(f⁴). Ở bậc dẫn, **lợi thế đo được cùng dấu với lợi thế thật chỉ khi σ_r < σ/√2**.
- Co rút nới điều kiện này, vì 2Q_r − H(1 + P) tăng khi H giảm. Nếu B quá sắc, như dưới (b), với ŷ_B = HKm và K ≥ 1, thì G_r − G = 2 ∫ H(K − 1)(1 − Q_r) S_m df ≥ 0: reference phóng đại lợi thế của A.
- Độc lập giữa ε_r và dự đoán hợp lý với reference từ checkshot hoặc VSP. Reference tie bằng khớp synthetic–seismic phụ thuộc cùng seismic với dự đoán, và sai số của nó thêm một số hạng hiệp phương sai vào công thức của Mệnh đề 6.
**Kiểm bằng mô phỏng (T3, exploratory; bài mục 6.5, Bảng `tab:t3`; `scripts/27_t3_power.py`).**
- Ở ba ô N = 16, tỉ số band RMSE trung vị M2-Sa/đối thủ cắt 1 ở σ_ref = 3,6–4,3 ms, so với σ/√2 = 3,0/4,1/5,1 ms (sai số warp RMS của B3c-R trên giếng train là 4,2/5,8/7,3 ms ở R10/R0/Rm5): cùng thứ tự, lệch không quá 1 ms.
- Với reference chính xác, sign test một phía (α = 0,05) đạt power 0,8 với 5–18 giếng blind ở 5/6 ô (ô R10, N = 4 không đạt vì ICC 0,45). Ở σ_ref = 1 ms, bốn ô cần 11–30 giếng; ở 2 ms chỉ R0 còn trong 40 giếng (23 và 37); từ 3 ms trở lên không ô nào đạt.
- Luật k-of-n của hai gate field không phải phép kiểm: khi không có khác biệt thật và giếng độc lập, nó vẫn đạt với xác suất 5/16 = 0,31 (n = 4) và 7/64 = 0,11 (n = 6).
## Tài liệu ## Tài liệu

416
exploratory/p4x_volve.py Normal file
View File

@@ -0,0 +1,416 @@
"""P4x: exploratory, post hoc model variants on Volve (docs/research/p4-exploratory.md).
Not part of any locked protocol. Imports the locked P4 code read-only (data views, folds, banks, trajectory trainer,
nested selection and scoring) and changes only what a variant declares: a low-frequency trend subtracted from the
targets (V1a velocity, V1b TWT), the network width (V2a) or a linear-Gaussian model (V2b, V3).
python exploratory/p4x_volve.py paths # velocity/TVDSS along every path (no label)
python exploratory/p4x_volve.py train --variants V0 V1a ... --methods B3b M2-Sa --workers 8 --device cuda:0
python exploratory/p4x_volve.py summarize # V0a check, every variant, reference predictors
"""
from __future__ import annotations
import argparse
import copy
import itertools
import json
import sys
import time
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
from datetime import datetime, timezone
from multiprocessing import get_context
from pathlib import Path
import numpy as np
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO))
from ml_porosity.volve.folds import prediction_targets, target_name # noqa: E402
from ml_porosity.volve.runner import fold_sets, job_path, load_bundle, reg_path, save_npz # noqa: E402
P4 = REPO / "outputs" / "p4"
OUT = REPO / "outputs" / "p4x"
VEL = (REPO / "data/Volve/Seismic/ST10010/Velocities"
/ "ST10010ZC11-MIG-VEL.MIG_VEL.VELOCITY.3D.JS-017527.segy")
SA = 7.0
LABEL = "PHIF"
VARIANTS = {
"V0": dict(trend=None, model="cnn", d=64), # retraining check (seed 0 only)
"V1a": dict(trend="velocity", model="cnn", d=64),
"V1b": dict(trend="twt", model="cnn", d=64),
"V2a": dict(trend=None, model="cnn", d=8),
"V2b": dict(trend=None, model="linear"),
"V3": dict(trend="velocity", model="linear"),
}
def stamp() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def protocol() -> dict:
from ml_porosity.volve.protocol import load_protocol
return load_protocol()
# ---------------------------------------------------------------- velocity and depth along every path (no label)
def velocity_cube():
import segyio
with segyio.open(VEL, iline=189, xline=193) as f:
cube = segyio.tools.cube(f).astype(np.float64)
il, xl, z = np.asarray(f.ilines, float), np.asarray(f.xlines, float), np.asarray(f.samples, float)
h = np.array([[t[segyio.su.iline], t[segyio.su.xline], t[segyio.su.cdpx], t[segyio.su.cdpy],
t[segyio.su.scalco]] for t in f.header], float)
scale = np.where(h[:, 4] < 0, -1.0 / h[:, 4], np.where(h[:, 4] > 0, h[:, 4], 1.0))
xy = h[:, 2:4] * scale[:, None]
A = np.c_[xy, np.ones(len(xy))]
coef, *_ = np.linalg.lstsq(A, h[:, :2], rcond=None) # (x, y, 1) -> (il, xl)
resid = np.abs(A @ coef - h[:, :2]).max()
return cube, (il, xl, z), coef, float(resid)
def build_paths() -> None:
"""V(t) and TVDSS(t) on the main window for every (well, key) path in the dataset: key 'reference' and every
blind key. Uses the well path (public survey) and the seismic-derived velocity only; no log, pick or label."""
from scipy.interpolate import RegularGridInterpolator
from ml_porosity.volve.data import load_arrays
p = protocol()
arrays = load_arrays()
cube, (il, xl, z), coef, resid = velocity_cube()
interp = RegularGridInterpolator((il, xl, z), cube, method="linear", bounds_error=True)
main = arrays[f"{p['data']['wells'][0]}/main_mask"].astype(bool)
t_main = arrays[f"{p['data']['wells'][0]}/times_ms"][main]
out, qc = {"times_ms": t_main}, {"affine_max_residual_bins": resid, "paths": {}}
for w in p["data"]["wells"]:
smd, stvd = arrays[f"{w}/survey/md"], arrays[f"{w}/survey/tvd"]
sx, sy, kb = arrays[f"{w}/survey/x"], arrays[f"{w}/survey/y"], float(arrays[f"{w}/kb_msl"])
keys = ["reference"] + sorted({k.split("/")[2] for k in arrays if k.startswith(f"{w}/blind/")})
for key in keys:
base = f"{w}/{'reference' if key == 'reference' else 'blind/' + key}"
md = arrays[f"{base}/md"][main]
x, y = np.interp(md, smd, sx), np.interp(md, smd, sy)
tvdss = np.interp(md, smd, stvd) - kb
ij = np.c_[x, y, np.ones_like(x)] @ coef
v = interp(np.c_[ij, tvdss])
out[f"{w}|{key}/velocity"], out[f"{w}|{key}/tvdss"] = v, tvdss
q = {"dil_vs_dataset": float(np.abs(ij[:, 0] - arrays[f"{base}/il"][main]).max()),
"dxl_vs_dataset": float(np.abs(ij[:, 1] - arrays[f"{base}/xl"][main]).max()),
"v_range": [float(v.min()), float(v.max())]}
if key == "reference":
q["dtvd_vs_dataset_m"] = float(np.abs(tvdss + kb - arrays[f"{base}/tvd"][main]).max())
qc["paths"][f"{w}|{key}"] = q
OUT.mkdir(parents=True, exist_ok=True)
np.savez_compressed(OUT / "paths.npz", **out)
worst = {k: max(q[k] for q in qc["paths"].values() if k in q)
for k in ("dil_vs_dataset", "dxl_vs_dataset", "dtvd_vs_dataset_m")}
qc["worst"] = worst
(OUT / "paths_qc.json").write_text(json.dumps(qc, indent=1), encoding="utf-8")
print(json.dumps({"affine_max_residual_bins": resid, **worst}))
# ---------------------------------------------------------------- trends (training wells of each set only)
def covariate(paths: dict, kind: str, well: str, key: str) -> np.ndarray:
if kind == "velocity":
return paths[f"{well}|{key}/velocity"]
return paths["times_ms"].astype(float)
def fit_trend(kind: str, paths: dict, labels: dict[str, np.ndarray]) -> tuple[float, float, float]:
"""OLS of the label on the covariate over all labelled samples of the given wells (path: reference).
Returns (a, b, residual SD)."""
c = np.concatenate([covariate(paths, kind, w, "reference")[np.isfinite(y)] for w, y in labels.items()])
y = np.concatenate([y[np.isfinite(y)] for y in labels.values()])
if kind is None or kind == "constant":
return float(y.mean()), 0.0, float(y.std())
A = np.c_[np.ones_like(c), c]
(a, b), *_ = np.linalg.lstsq(A, y, rcond=None)
return float(a), float(b), float(np.std(y - A @ np.array([a, b])))
def b3b_labels(names) -> dict[str, np.ndarray]:
"""B3b-tie labels (fraction, main window, NaN off support) of the wells of a registration set."""
z = load_bundle(reg_path(P4, names, SA))
Y = z[f"{LABEL}/B3b"]
return {w: Y[i, 0] for i, w in enumerate(z["wells"])}
# ---------------------------------------------------------------- linear-Gaussian model (V2b, V3)
def linear_factory(method, channels, cfg):
import torch
from torch import nn
import torch.nn.functional as F
class LinearGaussian(nn.Module):
"""μ = Conv1d(patch channels → 1, kernel k) + bias; a single scalar σ = softplus(s) + σ_min."""
def __init__(self, in_ch: int, k: int = 9, sigma_min: float = 1e-3):
super().__init__()
self.conv = nn.Conv1d(in_ch, 1, k, padding=k // 2)
self.s = nn.Parameter(torch.zeros(1))
self.sigma_min = sigma_min
def forward(self, x):
mu = self.conv(x)
return mu, (F.softplus(self.s) + self.sigma_min).expand_as(mu)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
return LinearGaussian(channels, cfg.get("kernel", 9))
# ---------------------------------------------------------------- one trajectory
def train_job(job: dict) -> dict:
import torch
import ml_porosity.volve.training as T
from ml_porosity.f3.training import make_model as cnn_factory
from ml_porosity.volve.data import VolveData
p, v = job["p"], VARIANTS[job["variant"]]
root = OUT / job["variant"]
names = tuple(sorted(job["names"]))
path = job_path(root, names, job["method"], LABEL, job["seed"], SA)
if path.exists():
return {"cached": True, "path": str(path)}
T.make_model = linear_factory if v["model"] == "linear" else cnn_factory
cfg = dict(p["training"])
if v["model"] == "cnn":
cfg["d_channels"] = v["d"]
data = VolveData(p, training_wells=names)
bundle = load_bundle(reg_path(P4, names, SA))
if tuple(bundle["wells"]) != names:
raise RuntimeError("Registration cache contains different wells")
targets = prediction_targets(data.wells, names)
X = np.stack([data.X(w, "reference") for w in names])
X_targets = np.stack([data.X(w, k) for w, k in targets])
spec = T.method_spec(bundle, LABEL, job["method"])
m0, s0 = bundle[f"{LABEL}/norm"]
trend_meta = {}
if v["trend"]:
with np.load(OUT / "paths.npz") as z:
paths = {k: z[k] for k in z.files}
Yb = bundle[f"{LABEL}/B3b"]
a, b, rsd = fit_trend(v["trend"], paths, {w: Yb[i, 0] for i, w in enumerate(names)})
tr_train = np.stack([a + b * covariate(paths, v["trend"], w, "reference") for w in names])
tr_targets = np.stack([a + b * covariate(paths, v["trend"], w, k) for w, k in targets])
spec["Y"] = spec["Y"] - ((tr_train - m0) / s0)[:, None, :]
trend_meta = {"trend": v["trend"], "a": a, "b": b, "residual_sd": rsd}
else:
tr_targets = np.full((len(targets), X.shape[2]), m0)
pred, meta = T.train_trajectory(X, X_targets, spec, job["method"], cfg, job["seed"], p["training"]["budgets"],
job["device"], None, p["runtime"]["cpu_threads_per_worker"])
pred = {k: (val * s0 + tr_targets if k.endswith("/mu") else val * s0) for k, val in pred.items()}
pred |= {"targets": np.asarray([target_name(w, k) for w, k in targets]), "wells": np.asarray(names),
"norm": bundle[f"{LABEL}/norm"]}
if v["trend"]:
pred["trend_targets"] = tr_targets
save_npz(path, pred)
path.with_suffix(".json").write_text(json.dumps(meta | trend_meta | {
"variant": job["variant"], "training_wells": list(names), "method": job["method"], "seed": job["seed"],
"device": job["device"], "finished": stamp(), "torch": torch.__version__}, indent=1), encoding="utf-8")
return {"cached": False, "path": str(path), "wall_seconds": meta["wall_seconds"]}
def run_train(variants, methods, seeds, workers, device) -> None:
p = protocol()
jobs = [dict(p=p, variant=var, names=list(n), method=m, seed=s, device=device)
for var in variants for m in methods for s in ([0] if var == "V0" else seeds) for n in fold_sets(p)]
todo = [j for j in jobs if not job_path(OUT / j["variant"], j["names"], j["method"], LABEL, j["seed"],
SA).exists()]
print(f"{stamp()} train: {len(jobs)} jobs, {len(todo)} to run, workers={workers}, device={device}", flush=True)
begin, done = time.time(), 0
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
pending = {ex.submit(train_job, j): j for j in todo}
while pending:
finished, _ = wait(pending, return_when=FIRST_COMPLETED)
for f in finished:
j = pending.pop(f)
f.result()
done += 1
if done % 10 == 0 or not pending:
el = time.time() - begin
print(f"{stamp()} {done}/{len(todo)} {j['variant']} {j['method']} s{j['seed']} "
f"elapsed {el / 60:.1f} min, eta {el / done * (len(todo) - done) / 60:.1f} min", flush=True)
# ---------------------------------------------------------------- evaluation
def extra(y: np.ndarray, mu: np.ndarray, sigma: np.ndarray) -> dict:
"""Porosity units; labelled samples only."""
from scipy.stats import norm
ok = np.isfinite(y)
y, mu, sigma = 100 * y[ok], 100 * mu[ok], np.maximum(100 * sigma[ok], 1e-6)
e = mu - y
bias = e.mean()
out = dict(n=int(ok.sum()), rmse=float(np.sqrt(np.mean(e ** 2))), bias=float(bias), abs_bias=float(abs(bias)),
rmse_debiased=float(np.sqrt(np.mean((e - bias) ** 2))), label_sd=float(y.std()),
pcc=float(np.corrcoef(y, mu)[0, 1]) if mu.std() > 0 else np.nan,
r2=float(1 - np.mean(e ** 2) / y.var()))
for lev in (80, 90):
zq = norm.ppf(0.5 + lev / 200)
out[f"coverage_{lev}"] = float(np.mean(np.abs(e) <= zq * sigma))
out["debiased_over_sd"] = out["rmse_debiased"] / out["label_sd"]
return out
def variant_predictions(variant: str, p: dict, arrays: dict) -> tuple[list[dict], list[str]]:
from ml_porosity.volve.evaluation import neural_predictions
root = OUT / variant
methods = [m for m in ("B3b", "B3d-Sa", "M2-Sa")
if all(job_path(root, n, m, LABEL, s, SA).exists()
for n in fold_sets(p) for s in p["split"]["seeds"])]
if not methods:
return [], []
q = copy.deepcopy(p)
q["methods"]["main"] = methods
pred, _ = neural_predictions(q, root, arrays, [SA])
return [a for a in pred if a["seed"] == "ensemble"], methods
def reference_predictors(p: dict, arrays: dict, paths: dict) -> list[dict]:
"""T0 constant, T1a velocity trend, T1b TWT trend: fitted on the outer training wells (B3b labels), applied
along the outer test well's blind path T_out."""
from ml_porosity.data.volve_wells import blind_key
from ml_porosity.volve.folds import outer_folds
from ml_porosity.volve.protocol import source_config
p4 = source_config(p)["p4"]
labels = {}
for names in fold_sets(p):
for w, y in b3b_labels(names).items():
if w in labels and not np.allclose(labels[w], y, equal_nan=True):
raise RuntimeError(f"B3b labels of {w} differ between sets")
labels[w] = y
out = []
for scheme in p["split"]["schemes"]:
for test, train in outer_folds(p["data"]["wells"], scheme, p4):
key = blind_key(train)
for name, kind in (("T0", "constant"), ("T1a", "velocity"), ("T1b", "twt")):
a, b, rsd = fit_trend(kind, paths, {w: labels[w] for w in train})
mu = a + b * (covariate(paths, kind, test, key) if kind != "constant" else 0.0)
mu = np.broadcast_to(mu, paths["times_ms"].shape).astype(float)
out.append(dict(variant=name, scheme=scheme, test_well=test, method="trend-only",
mu=mu, sigma=np.full_like(mu, rsd), a=a, b=b))
return out
def summarize() -> None:
import pandas as pd
from ml_porosity.volve.data import VolveData, load_arrays
from ml_porosity.volve.evaluation import neural_predictions
p = protocol()
arrays = load_arrays()
full = VolveData(p, arrays=arrays)
ref = p["data"]["primary_reference"]
report = {"created": stamp()}
# V0a: locked trajectories through this harness
locked = pd.read_csv(P4 / "summary" / "metrics.csv")
locked = locked[(locked.seed.astype(str) == "ensemble") & (locked.reference == ref) & (locked.sigma_a_ms == SA)]
pred, _ = neural_predictions(p, P4, arrays, [SA])
diffs = []
for a in pred:
if a["seed"] != "ensemble":
continue
row = locked[(locked.scheme == a["scheme"]) & (locked.test_well == a["test_well"])
& (locked.method == a["method"])]
diffs.append(abs(extra(full.y(a["test_well"], ref), a["mu"], a["sigma"])["rmse"] - float(row.rmse.iloc[0])))
report["V0a_max_abs_rmse_diff"] = float(max(diffs))
report["V0a_rows"] = len(diffs)
rows = []
for a in pred:
if a["seed"] == "ensemble" and a["method"] in ("B3b", "B3d-Sa", "M2-Sa"):
rows.append(dict(variant="P4", scheme=a["scheme"], test_well=a["test_well"], method=a["method"])
| extra(full.y(a["test_well"], ref), a["mu"], a["sigma"]))
# V0b: retrained seed-0 trajectories versus the stored P4 ones
v0 = []
for names in fold_sets(p):
for m in ("B3b", "M2-Sa"):
mine, theirs = job_path(OUT / "V0", names, m, LABEL, 0, SA), job_path(P4, names, m, LABEL, 0, SA)
if not mine.exists():
continue
a, b = load_bundle(mine), load_bundle(theirs)
assert list(a["targets"]) == list(b["targets"])
v0.append(max(float(np.max(np.abs(a[k] - b[k]))) for k in a if k.endswith("/mu") or k.endswith("/sigma")))
report["V0b_trajectories"] = len(v0)
report["V0b_max_abs_diff_fraction"] = float(max(v0)) if v0 else None
report["V0b_median_max_abs_diff_fraction"] = float(np.median(v0)) if v0 else None
for variant in ("V1a", "V1b", "V2a", "V2b", "V3"):
preds, methods = variant_predictions(variant, p, arrays)
report[f"{variant}_methods"] = methods
for a in preds:
rows.append(dict(variant=variant, scheme=a["scheme"], test_well=a["test_well"], method=a["method"])
| extra(full.y(a["test_well"], ref), a["mu"], a["sigma"]))
with np.load(OUT / "paths.npz") as z:
paths = {k: z[k] for k in z.files}
for a in reference_predictors(p, arrays, paths):
rows.append({k: a[k] for k in ("variant", "scheme", "test_well", "method")}
| extra(full.y(a["test_well"], ref), a["mu"], a["sigma"]) | dict(trend_a=a["a"], trend_b=a["b"]))
per = pd.DataFrame(rows)
dest = OUT / "summary"
dest.mkdir(parents=True, exist_ok=True)
per.to_csv(dest / "per_well.csv", index=False)
cols = ["rmse", "abs_bias", "rmse_debiased", "label_sd", "debiased_over_sd", "pcc", "r2", "coverage_80",
"coverage_90"]
g = per.groupby(["variant", "scheme", "method"], sort=False)
macro = g[cols].mean().join(g.size().rename("n_wells"))
macro["wells_r2_pos"] = g.r2.apply(lambda s: int((s > 0).sum()))
macro["wells_debiased_le_0.9sd"] = g.debiased_over_sd.apply(lambda s: int((s <= 0.9).sum()))
macro = macro.reset_index()
macro["skill"] = (macro.r2 > 0) | (macro.rmse_debiased <= 0.9 * macro.label_sd)
macro.to_csv(dest / "macro.csv", index=False)
gaps = []
for (variant, scheme), d in per[per.method.isin(["B3b", "M2-Sa"])].groupby(["variant", "scheme"], sort=False):
w = d.pivot(index="test_well", columns="method", values=["rmse", "rmse_debiased"])
if ("rmse", "M2-Sa") not in w or ("rmse", "B3b") not in w:
continue
dr = w[("rmse", "M2-Sa")] - w[("rmse", "B3b")]
dd = w[("rmse_debiased", "M2-Sa")] - w[("rmse_debiased", "B3b")]
gaps.append(dict(variant=variant, scheme=scheme, macro_gap_rmse=float(dr.mean()),
macro_gap_rmse_debiased=float(dd.mean()), wells_m2_better=int((dr < 0).sum()),
n_wells=int(dr.size), **{f"gap_{k}": float(x) for k, x in dr.items()}))
gaps = pd.DataFrame(gaps)
gaps.to_csv(dest / "gap_m2_minus_b3b.csv", index=False)
(dest / "checks.json").write_text(json.dumps(report, indent=1), encoding="utf-8")
text = ["# P4x — exploratory Volve variants (post hoc; see docs/research/p4-exploratory.md)", "",
f"Generated {report['created']}. σ_a = 7 ms, primary reference `{ref}`, combined ensembles, "
"porosity units. Exploratory: cannot support plan §10 claims or alter G-D.", "",
"## Checks", "", "```", json.dumps(report, indent=1), "```", "",
"## Macro over wells", "", macro.to_markdown(index=False, floatfmt=".3f"), "",
"## M2-Sa − B3b (RMSE, p.u.; negative = M2-Sa better)", "",
gaps.to_markdown(index=False, floatfmt=".3f") if len(gaps) else "(none)", "",
"Per-well rows: per_well.csv. Skill: macro R² > 0 or macro bias-removed RMSE ≤ 0.9 × macro label SD."]
(dest / "summary.md").write_text("\n".join(text) + "\n", encoding="utf-8")
print(json.dumps(report, indent=1))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("stage", choices=["paths", "train", "summarize"])
ap.add_argument("--variants", nargs="+", default=["V0", "V1a", "V1b", "V2a", "V2b"])
ap.add_argument("--methods", nargs="+", default=["B3b", "M2-Sa"])
ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2, 3, 4])
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--device", default="cuda:0")
a = ap.parse_args()
if a.stage == "paths":
build_paths()
elif a.stage == "train":
run_train(a.variants, a.methods, a.seeds, a.workers, a.device)
else:
summarize()
if __name__ == "__main__":
main()

13
exploratory/run_p4x.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# P4x exploratory driver (docs/research/p4-exploratory.md): required methods of every variant first, then B3d-Sa,
# then the optional V3. Completed trajectories are skipped, so the driver can be restarted.
set -euo pipefail
cd "$(dirname "$0")/.."
DEVICE="${DEVICE:-cuda:0}"
WORKERS="${WORKERS:-8}"
export OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 NUMEXPR_NUM_THREADS=2 NUMBA_NUM_THREADS=2 \
PYTHONHASHSEED=0 PYTHONUTF8=1 CUBLAS_WORKSPACE_CONFIG=:4096:8
run() { scripts/runlog.sh -n "p4x_$1" -- exploratory/p4x_volve.py train --device "$DEVICE" --workers "$WORKERS" "${@:2}"; }
run required --variants V0 V1a V1b V2a V2b --methods B3b M2-Sa
run b3d --variants V1a V1b V2a V2b --methods B3d-Sa
run v3 --variants V3 --methods B3b M2-Sa B3d-Sa

View File

@@ -128,3 +128,27 @@ run_id,parent,name,status,exit_code,start,end,wall_s,wall,device,git,dirty,code_
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-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/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 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
20261027-232902_p3_review,,p3_review,ok,0,2026-10-27T23:29:02+07:00,2026-10-27T23:29:25+07:00,23.2,0:00:23,,a22f9d951fe3,True,6d0adcbe80a99baa,runlog,'.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
20261027-233342_p3_review_final,,p3_review_final,ok,0,2026-10-27T23:33:42+07:00,2026-10-27T23:34:05+07:00,23.0,0:00:23,,a22f9d951fe3,True,df7ba5091d4a2220,runlog,'.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
20261027-233920_p3_status,,p3_status,ok,0,2026-10-27T23:39:20+07:00,2026-10-27T23:39:23+07:00,3.6,0:00:04,cuda:0,a22f9d951fe3,True,7e29d408c3ca7123,runlog,'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' status --device cuda:0 --workers 3
20261027-234538_p3_skill_review,,p3_skill_review,failed,1,2026-10-27T23:45:38+07:00,2026-10-27T23:46:01+07:00,23.3,0:00:23,,a22f9d951fe3,True,dd0bf33779a88c71,runlog,'.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
20261027-235355_p3_review_verified,,p3_review_verified,ok,0,2026-10-27T23:53:55+07:00,2026-10-27T23:54:19+07:00,23.7,0:00:24,,a22f9d951fe3,True,c5b59e87c2a1dc29,runlog,'.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
20261027-235601_p3_rtx3060_benchmark,,p3_rtx3060_benchmark,ok,0,2026-10-27T23:56:01+07:00,2026-10-27T23:57:00+07:00,58.9,0:00:59,cuda:0,a22f9d951fe3,True,c5b59e87c2a1dc29,runlog,'.\.venv\Scripts\python.exe' -X utf8 scripts/19_run_f3.py benchmark --device cuda:0 --benchmark-steps 200 --benchmark-workers 1 2 3
20261028-000434_p3_rtx3060_parallel_benchmark,,p3_rtx3060_parallel_benchmark,ok,0,2026-10-28T00:04:34+07:00,2026-10-28T00:05:11+07:00,37.0,0:00:37,cuda:0,a22f9d951fe3,True,7b39175dd2ab49b2,runlog,'.\.venv\Scripts\python.exe' -X utf8 scripts/19_run_f3.py benchmark --device cuda:0 --benchmark-steps 200 --benchmark-workers 4 6
20261028-001108_p3_final_preflight,,p3_final_preflight,ok,0,2026-10-28T00:11:08+07:00,2026-10-28T00:11:32+07:00,24.3,0:00:24,,a22f9d951fe3,True,4f86170b90ec313f,runlog,'.\.venv\Scripts\python.exe' -X utf8 -m pytest -q
20261028-001241_p3_classical_preflight,,p3_classical_preflight,ok,0,2026-10-28T00:12:41+07:00,2026-10-28T00:12:50+07:00,8.7,0:00:09,,a22f9d951fe3,True,4f86170b90ec313f,runlog,"'.\.venv\Scripts\python.exe' -X utf8 -c 'from types import SimpleNamespace; import numpy as np; from ml_porosity.f3.protocol import load_protocol; from ml_porosity.f3.evaluation import classical_predictions; p=load_protocol(); p['""'""'data'""'""']['""'""'labels'""'""']=['""'""'PHIE_DT'""'""']; p['""'""'split'""'""']['""'""'seeds'""'""']=[0]; pred=classical_predictions(SimpleNamespace(wells=[p['""'""'data'""'""']['""'""'wells'""'""'][0]]),p); assert all(a['""'""'mu'""'""'].shape==(126,) and np.isfinite(a['""'""'mu'""'""']).all() for a in pred); print('""'""'Classical predictions finite, 126 samples:'""'""', [a['""'""'method'""'""'] for a in pred]); print('""'""'No test metrics computed; no parameter changes based on outcomes.'""'""');'"
20261028-000739_p3_registration_benchmark,,p3_registration_benchmark,ok,0,2026-10-28T00:07:39+07:00,2026-10-28T00:14:03+07:00,383.1,0:06:23,cuda:0,a22f9d951fe3,True,7b39175dd2ab49b2,runlog,'.\.venv\Scripts\python.exe' -X utf8 scripts/19_run_f3.py benchmark-registration --device cuda:0
20261028-001446_p3_lock,,p3_lock,ok,0,2026-10-28T00:14:46+07:00,2026-10-28T00:14:51+07:00,4.8,0:00:05,cuda:0,a22f9d951fe3,True,6a1de0d9c735015e,runlog,'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' lock --device cuda:0 --workers 4
20261028-001505_p3_all,,p3_all,ok,0,2026-10-28T00:15:05+07:00,2026-10-28T00:15:34+07:00,29.1,0:00:29,cuda:0,a22f9d951fe3,True,04bf3e1e27b1e1b7,runlog,'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' all --device cuda:0 --workers 4 --smoke
20261028-001548_p3_all,,p3_all,failed,1,2026-10-28T00:15:48+07:00,2026-10-28T03:57:33+07:00,13305.6,3:41:46,cuda:0,a22f9d951fe3,True,04bf3e1e27b1e1b7,runlog,'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' all --device cuda:0 --workers 4
20261028-064743_p3_volume_recovery,,p3_volume_recovery,ok,0,2026-10-28T06:47:43+07:00,2026-10-28T06:50:45+07:00,182.2,0:03:02,cuda:0,a22f9d951fe3,True,04bf3e1e27b1e1b7,runlog,'.\.venv\Scripts\python.exe' -X utf8 operations/resume_f3_volume.py --device cuda:0
20261028-065050_p3_completion_audit,,p3_completion_audit,ok,0,2026-10-28T06:50:50+07:00,2026-10-28T06:51:16+07:00,26.1,0:00:26,,a22f9d951fe3,True,04bf3e1e27b1e1b7,runlog,'.\.venv\Scripts\python.exe' -X utf8 operations/check_f3_completion.py
20261029-011622_p4_benchmark,,p4_benchmark,ok,0,2026-10-29T01:16:22+00:00,2026-10-29T01:16:48+00:00,25.5,0:00:25,cuda:1,7da6b077b6e3,True,d3410f1130a74cc3,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/24_run_volve.py benchmark --device cuda:1
20261029-011736_p4_lock_primary,,p4_lock_primary,ok,0,2026-10-29T01:17:36+00:00,2026-10-29T01:17:43+00:00,6.2,0:00:06,cuda:1,7da6b077b6e3,True,a6f9ea223246c9b7,runlog,.venv/bin/python scripts/24_run_volve.py lock --device cuda:1 --workers 8 --arms primary
20261029-011750_p4_register_primary,,p4_register_primary,ok,0,2026-10-29T01:17:50+00:00,2026-10-29T01:20:36+00:00,166.6,0:02:47,cuda:1,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py register --device cuda:1 --workers 8 --arms primary
20261029-012257_p4_register_sensitivity,,p4_register_sensitivity,ok,0,2026-10-29T01:22:57+00:00,2026-10-29T01:28:25+00:00,327.6,0:05:28,cuda:0,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py register --device cuda:0 --workers 8 --arms sensitivity
20261029-012036_p4_train_primary,,p4_train_primary,ok,0,2026-10-29T01:20:36+00:00,2026-10-29T02:07:23+00:00,2806.5,0:46:46,cuda:1,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py train --device cuda:1 --workers 8 --arms primary
20261029-020723_p4_summarize_primary,,p4_summarize_primary,ok,0,2026-10-29T02:07:23+00:00,2026-10-29T02:07:32+00:00,8.4,0:00:08,cuda:1,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py summarize --device cuda:1 --workers 8 --arms primary
20261029-012825_p4_train_sensitivity,,p4_train_sensitivity,ok,0,2026-10-29T01:28:25+00:00,2026-10-29T02:21:04+00:00,3159.2,0:52:39,cuda:0,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py train --device cuda:0 --workers 8 --arms sensitivity
20261029-022117_p4_summarize_all,,p4_summarize_all,ok,0,2026-10-29T02:21:17+00:00,2026-10-29T02:21:36+00:00,18.7,0:00:19,cpu,7da6b077b6e3,True,984655c40e2413fc,runlog,.venv/bin/python scripts/24_run_volve.py summarize --device cpu --workers 4 --arms all
20261029-040703_p4x_summarize_partial,,p4x_summarize_partial,ok,0,2026-10-29T04:07:03+00:00,2026-10-29T04:07:10+00:00,7.1,0:00:07,,7da6b077b6e3,True,9b97ea3ba76b1136,runlog,/home/jovyan/lamlvh/ML-Porosity/.venv/bin/python exploratory/p4x_volve.py summarize
1 run_id parent name status exit_code start end wall_s wall device git dirty code_sha source cmd
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
131 20261027-232902_p3_review p3_review ok 0 2026-10-27T23:29:02+07:00 2026-10-27T23:29:25+07:00 23.2 0:00:23 a22f9d951fe3 True 6d0adcbe80a99baa runlog '.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
132 20261027-233342_p3_review_final p3_review_final ok 0 2026-10-27T23:33:42+07:00 2026-10-27T23:34:05+07:00 23.0 0:00:23 a22f9d951fe3 True df7ba5091d4a2220 runlog '.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
133 20261027-233920_p3_status p3_status ok 0 2026-10-27T23:39:20+07:00 2026-10-27T23:39:23+07:00 3.6 0:00:04 cuda:0 a22f9d951fe3 True 7e29d408c3ca7123 runlog 'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' status --device cuda:0 --workers 3
134 20261027-234538_p3_skill_review p3_skill_review failed 1 2026-10-27T23:45:38+07:00 2026-10-27T23:46:01+07:00 23.3 0:00:23 a22f9d951fe3 True dd0bf33779a88c71 runlog '.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
135 20261027-235355_p3_review_verified p3_review_verified ok 0 2026-10-27T23:53:55+07:00 2026-10-27T23:54:19+07:00 23.7 0:00:24 a22f9d951fe3 True c5b59e87c2a1dc29 runlog '.\.venv\Scripts\python.exe' -X utf8 -m pytest -q tests
136 20261027-235601_p3_rtx3060_benchmark p3_rtx3060_benchmark ok 0 2026-10-27T23:56:01+07:00 2026-10-27T23:57:00+07:00 58.9 0:00:59 cuda:0 a22f9d951fe3 True c5b59e87c2a1dc29 runlog '.\.venv\Scripts\python.exe' -X utf8 scripts/19_run_f3.py benchmark --device cuda:0 --benchmark-steps 200 --benchmark-workers 1 2 3
137 20261028-000434_p3_rtx3060_parallel_benchmark p3_rtx3060_parallel_benchmark ok 0 2026-10-28T00:04:34+07:00 2026-10-28T00:05:11+07:00 37.0 0:00:37 cuda:0 a22f9d951fe3 True 7b39175dd2ab49b2 runlog '.\.venv\Scripts\python.exe' -X utf8 scripts/19_run_f3.py benchmark --device cuda:0 --benchmark-steps 200 --benchmark-workers 4 6
138 20261028-001108_p3_final_preflight p3_final_preflight ok 0 2026-10-28T00:11:08+07:00 2026-10-28T00:11:32+07:00 24.3 0:00:24 a22f9d951fe3 True 4f86170b90ec313f runlog '.\.venv\Scripts\python.exe' -X utf8 -m pytest -q
139 20261028-001241_p3_classical_preflight p3_classical_preflight ok 0 2026-10-28T00:12:41+07:00 2026-10-28T00:12:50+07:00 8.7 0:00:09 a22f9d951fe3 True 4f86170b90ec313f runlog '.\.venv\Scripts\python.exe' -X utf8 -c 'from types import SimpleNamespace; import numpy as np; from ml_porosity.f3.protocol import load_protocol; from ml_porosity.f3.evaluation import classical_predictions; p=load_protocol(); p['"'"'data'"'"']['"'"'labels'"'"']=['"'"'PHIE_DT'"'"']; p['"'"'split'"'"']['"'"'seeds'"'"']=[0]; pred=classical_predictions(SimpleNamespace(wells=[p['"'"'data'"'"']['"'"'wells'"'"'][0]]),p); assert all(a['"'"'mu'"'"'].shape==(126,) and np.isfinite(a['"'"'mu'"'"']).all() for a in pred); print('"'"'Classical predictions finite, 126 samples:'"'"', [a['"'"'method'"'"'] for a in pred]); print('"'"'No test metrics computed; no parameter changes based on outcomes.'"'"');'
140 20261028-000739_p3_registration_benchmark p3_registration_benchmark ok 0 2026-10-28T00:07:39+07:00 2026-10-28T00:14:03+07:00 383.1 0:06:23 cuda:0 a22f9d951fe3 True 7b39175dd2ab49b2 runlog '.\.venv\Scripts\python.exe' -X utf8 scripts/19_run_f3.py benchmark-registration --device cuda:0
141 20261028-001446_p3_lock p3_lock ok 0 2026-10-28T00:14:46+07:00 2026-10-28T00:14:51+07:00 4.8 0:00:05 cuda:0 a22f9d951fe3 True 6a1de0d9c735015e runlog 'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' lock --device cuda:0 --workers 4
142 20261028-001505_p3_all p3_all ok 0 2026-10-28T00:15:05+07:00 2026-10-28T00:15:34+07:00 29.1 0:00:29 cuda:0 a22f9d951fe3 True 04bf3e1e27b1e1b7 runlog 'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' all --device cuda:0 --workers 4 --smoke
143 20261028-001548_p3_all p3_all failed 1 2026-10-28T00:15:48+07:00 2026-10-28T03:57:33+07:00 13305.6 3:41:46 cuda:0 a22f9d951fe3 True 04bf3e1e27b1e1b7 runlog 'C:\Users\PC\Documents\ML-Porosity\.venv\Scripts\python.exe' -X utf8 'C:\Users\PC\Documents\ML-Porosity\scripts\19_run_f3.py' all --device cuda:0 --workers 4
144 20261028-064743_p3_volume_recovery p3_volume_recovery ok 0 2026-10-28T06:47:43+07:00 2026-10-28T06:50:45+07:00 182.2 0:03:02 cuda:0 a22f9d951fe3 True 04bf3e1e27b1e1b7 runlog '.\.venv\Scripts\python.exe' -X utf8 operations/resume_f3_volume.py --device cuda:0
145 20261028-065050_p3_completion_audit p3_completion_audit ok 0 2026-10-28T06:50:50+07:00 2026-10-28T06:51:16+07:00 26.1 0:00:26 a22f9d951fe3 True 04bf3e1e27b1e1b7 runlog '.\.venv\Scripts\python.exe' -X utf8 operations/check_f3_completion.py
146 20261029-011622_p4_benchmark p4_benchmark ok 0 2026-10-29T01:16:22+00:00 2026-10-29T01:16:48+00:00 25.5 0:00:25 cuda:1 7da6b077b6e3 True d3410f1130a74cc3 runlog /home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/24_run_volve.py benchmark --device cuda:1
147 20261029-011736_p4_lock_primary p4_lock_primary ok 0 2026-10-29T01:17:36+00:00 2026-10-29T01:17:43+00:00 6.2 0:00:06 cuda:1 7da6b077b6e3 True a6f9ea223246c9b7 runlog .venv/bin/python scripts/24_run_volve.py lock --device cuda:1 --workers 8 --arms primary
148 20261029-011750_p4_register_primary p4_register_primary ok 0 2026-10-29T01:17:50+00:00 2026-10-29T01:20:36+00:00 166.6 0:02:47 cuda:1 7da6b077b6e3 True 984655c40e2413fc runlog .venv/bin/python scripts/24_run_volve.py register --device cuda:1 --workers 8 --arms primary
149 20261029-012257_p4_register_sensitivity p4_register_sensitivity ok 0 2026-10-29T01:22:57+00:00 2026-10-29T01:28:25+00:00 327.6 0:05:28 cuda:0 7da6b077b6e3 True 984655c40e2413fc runlog .venv/bin/python scripts/24_run_volve.py register --device cuda:0 --workers 8 --arms sensitivity
150 20261029-012036_p4_train_primary p4_train_primary ok 0 2026-10-29T01:20:36+00:00 2026-10-29T02:07:23+00:00 2806.5 0:46:46 cuda:1 7da6b077b6e3 True 984655c40e2413fc runlog .venv/bin/python scripts/24_run_volve.py train --device cuda:1 --workers 8 --arms primary
151 20261029-020723_p4_summarize_primary p4_summarize_primary ok 0 2026-10-29T02:07:23+00:00 2026-10-29T02:07:32+00:00 8.4 0:00:08 cuda:1 7da6b077b6e3 True 984655c40e2413fc runlog .venv/bin/python scripts/24_run_volve.py summarize --device cuda:1 --workers 8 --arms primary
152 20261029-012825_p4_train_sensitivity p4_train_sensitivity ok 0 2026-10-29T01:28:25+00:00 2026-10-29T02:21:04+00:00 3159.2 0:52:39 cuda:0 7da6b077b6e3 True 984655c40e2413fc runlog .venv/bin/python scripts/24_run_volve.py train --device cuda:0 --workers 8 --arms sensitivity
153 20261029-022117_p4_summarize_all p4_summarize_all ok 0 2026-10-29T02:21:17+00:00 2026-10-29T02:21:36+00:00 18.7 0:00:19 cpu 7da6b077b6e3 True 984655c40e2413fc runlog .venv/bin/python scripts/24_run_volve.py summarize --device cpu --workers 4 --arms all
154 20261029-040703_p4x_summarize_partial p4x_summarize_partial ok 0 2026-10-29T04:07:03+00:00 2026-10-29T04:07:10+00:00 7.1 0:00:07 7da6b077b6e3 True 9b97ea3ba76b1136 runlog /home/jovyan/lamlvh/ML-Porosity/.venv/bin/python exploratory/p4x_volve.py summarize

View File

@@ -0,0 +1,281 @@
"""Deviated-well geometry and time–depth relationships (Volve, plan phase P4).
Conventions: MD and TVD are metres below the rotary kelly bushing (RKB); TVDSS = TVD − (KB − MSL), positive
down; X/Y are projected easting/northing (m) with grid north; times are two-way times (ms) from the seismic datum.
Seismic time is vertical time, whereas a sonic tool measures slowness along the borehole. The vertical sonic TDR
therefore integrates DT over TVD instead of MD (isotropic, flat-layer approximation). Anisotropy and dip are left
to the anchor calibration and, in RML, to the warp prior. All TDRs stay keyed by MD, so `log_to_time` and
`calibrate_to_anchors` apply unchanged.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from scipy import integrate
from ml_porosity.data.tdr import TDR, US_PER_M_TO_S_PER_M, _interp_extrap, calibrate_to_anchors
_COLUMNS = ("MD", "Inc", "Azim", "TVD")
_NODE_STEP_M = 1.0 # MD spacing of TDR nodes outside the logged interval (TVD is curved between survey stations)
def _tangent(inc_deg, azi_deg) -> np.ndarray:
"""Unit tangent (east, north, down) from inclination and grid azimuth in degrees."""
i, a = np.radians(inc_deg), np.radians(azi_deg)
return np.stack([np.sin(i) * np.sin(a), np.sin(i) * np.cos(a), np.cos(i)], axis=-1)
def _mc_step(t0: np.ndarray, t1: np.ndarray, dmd) -> np.ndarray:
"""Minimum-curvature displacement over arc length `dmd` between unit tangents t0 and t1 (exact on a circular arc)."""
beta = np.arccos(np.clip(np.sum(t0 * t1, axis=-1), -1.0, 1.0))
small = beta < 1e-9
rf = np.where(small, 1.0, 2.0 / np.where(small, 1.0, beta) * np.tan(beta / 2))
return 0.5 * np.asarray(dmd, dtype=float)[..., None] * (t0 + t1) * rf[..., None]
def read_compass_header(path: str | Path) -> dict[str, str]:
"""`key: value` lines above `SURVEY LIST` in a Compass survey export."""
head = {}
for s in Path(path).read_text(encoding="latin-1").splitlines():
if s.strip() == "SURVEY LIST":
return head
if ":" in s:
k, v = s.split(":", 1)
head[k.strip()] = v.strip()
raise ValueError(f"{path}: no SURVEY LIST section")
@dataclass(frozen=True)
class Trajectory:
"""Survey stations of one wellbore."""
name: str
md: np.ndarray # (N,) m RKB, strictly increasing
inc: np.ndarray # deg
azi: np.ndarray # deg from grid north
tvd: np.ndarray # m RKB
x: np.ndarray # easting (m)
y: np.ndarray # northing (m)
kb_msl: float = 0.0 # RKB elevation above MSL (m)
def __post_init__(self):
arrays = {k: np.asarray(getattr(self, k), dtype=float) for k in ("md", "inc", "azi", "tvd", "x", "y")}
n = arrays["md"].size
if n < 2 or any(a.shape != (n,) for a in arrays.values()):
raise ValueError("trajectory arrays must be 1-D of equal length ≥ 2")
if np.any(np.diff(arrays["md"]) <= 0):
raise ValueError(f"trajectory {self.name!r}: MD is not strictly increasing")
for k, a in arrays.items():
object.__setattr__(self, k, a)
@classmethod
def from_compass(cls, path: str | Path, name: str | None = None) -> Trajectory:
"""Read a Compass "ACTUAL" survey export (header, then `SURVEY LIST`, a column line, a unit line and
one row per station: MD, Inc, Azim, TVD, X/Y offsets, UTM E/N, DLS)."""
head = read_compass_header(path)
if head.get("Calculation Method") != "Minimum Curvature" or head.get("North Reference") != "Grid":
raise ValueError(f"{path}: expected minimum curvature and grid north, got {head.get('Calculation Method')!r}"
f" / {head.get('North Reference')!r}")
lines = Path(path).read_text(encoding="latin-1").splitlines()
start = next(k for k, s in enumerate(lines) if s.strip() == "SURVEY LIST")
if tuple(lines[start + 1].split()[:4]) != _COLUMNS or "UTM N/S" not in lines[start + 1]:
raise ValueError(f"{path}: unexpected survey columns {lines[start + 1]!r}")
if lines[start + 2].split()[:2] != ["m", "RKB"]:
raise ValueError(f"{path}: MD is not referenced to RKB")
rows = np.array([[float(v) for v in s.split()] for s in lines[start + 3:] if s.strip()])
if rows.ndim != 2 or rows.shape[1] != 9:
raise ValueError(f"{path}: expected 9 numeric columns per station")
md, inc, azi, tvd, _, _, x, y, _ = rows.T
kb = float(head["KB-MSL"].removesuffix("m"))
return cls(name or head.get("WELLBORE NAME", Path(path).name), md, inc, azi, tvd, x, y, kb)
def recompute(self) -> np.ndarray:
"""Station positions (x, y, tvd) by minimum curvature from the first station; QC against the listed ones."""
t = _tangent(self.inc, self.azi)
start = np.array([self.x[0], self.y[0], self.tvd[0]])
return np.vstack([start, start + np.cumsum(_mc_step(t[:-1], t[1:], np.diff(self.md)), axis=0)])
def dls(self) -> np.ndarray:
"""Dogleg severity (deg/30 m) of each survey interval."""
t = _tangent(self.inc, self.azi)
beta = np.arccos(np.clip(np.sum(t[:-1] * t[1:], axis=-1), -1.0, 1.0))
return np.degrees(beta) * 30.0 / np.diff(self.md)
def at(self, md) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""(tvd, x, y) at MD: minimum curvature between stations, anchored on the listed station coordinates
(the small closure residual of each interval is spread linearly over it). No extrapolation."""
md = np.asarray(md, dtype=float)
if np.any(md < self.md[0] - 1e-9) or np.any(md > self.md[-1] + 1e-9):
raise ValueError(f"trajectory {self.name!r}: MD outside the survey {self.md[0]}–{self.md[-1]} m")
i = np.clip(np.searchsorted(self.md, md, side="right") - 1, 0, self.md.size - 2)
dmd = self.md[i + 1] - self.md[i]
f = np.clip((md - self.md[i]) / dmd, 0.0, 1.0)
t = _tangent(self.inc, self.azi)
t0, t1 = t[i], t[i + 1]
beta = np.arccos(np.clip(np.sum(t0 * t1, axis=-1), -1.0, 1.0))
sb = np.sin(beta)
small = sb < 1e-9
w0 = np.where(small, 1 - f, np.sin((1 - f) * beta) / np.where(small, 1.0, sb))
w1 = np.where(small, f, np.sin(f * beta) / np.where(small, 1.0, sb))
tf = w0[..., None] * t0 + w1[..., None] * t1 # tangent at fraction f of the circular arc
tf = tf / np.linalg.norm(tf, axis=-1, keepdims=True)
p = np.stack([self.x, self.y, self.tvd], axis=-1)
closure = p[i + 1] - p[i] - _mc_step(t0, t1, dmd)
q = p[i] + _mc_step(t0, tf, f * dmd) + f[..., None] * closure
return q[..., 2], q[..., 0], q[..., 1]
def tvdss(self, md) -> np.ndarray:
return self.at(md)[0] - self.kb_msl
def vertical_sonic_tdr(md, tvd, dt_us_per_m, md0: float, t0_ms: float, name: str = "sonic") -> TDR:
"""Vertical-time sonic TDR through (md0, t0_ms): t(md) = t0 + 2·∫ DT dTVD from md0 to md.
Only valid DT samples are used (gaps are integrated as DT varying linearly between their ends). md0 must lie
within the valid DT range, and TVD must increase strictly along it (no well turning upwards)."""
md, tvd, dt = (np.asarray(v, dtype=float) for v in (md, tvd, dt_us_per_m))
ok = np.isfinite(dt) & (dt > 0) & np.isfinite(tvd)
md_v, tvd_v, dt_v = md[ok], tvd[ok], dt[ok]
if md_v.size < 2:
raise ValueError("no valid DT")
if np.any(np.diff(tvd_v) <= 0):
raise ValueError("TVD does not increase strictly over the logged interval")
if not md_v[0] <= md0 <= md_v[-1]:
raise ValueError(f"anchor MD {md0} lies outside the valid DT range {md_v[0]}–{md_v[-1]} m")
t = 2000.0 * integrate.cumulative_trapezoid(dt_v * US_PER_M_TO_S_PER_M, tvd_v, initial=0.0)
return TDR(md_v, t - np.interp(md0, md_v, t) + t0_ms, name)
def _sorted_anchors(anchor_md, anchor_twt_ms) -> tuple[np.ndarray, np.ndarray]:
za, ta = np.asarray(anchor_md, dtype=float), np.asarray(anchor_twt_ms, dtype=float)
order = np.argsort(za, kind="stable")
za, ta = za[order], ta[order]
if np.any(np.diff(za) <= 0) or np.any(np.diff(ta) <= 0):
raise ValueError("anchors must be strictly increasing in MD and TWT")
return za, ta
def _nodes(traj: Trajectory, lo: float, hi: float, extra=()) -> np.ndarray:
"""Survey stations, a regular MD grid and `extra` points strictly inside (lo, hi), clipped to the survey."""
grid = np.arange(np.ceil(traj.md[0]), traj.md[-1], _NODE_STEP_M)
z = np.union1d(np.union1d(grid, traj.md), np.asarray(extra, dtype=float))
return z[(z > lo) & (z < hi)]
def calibrated_vertical_tdr(traj: Trajectory, md, dt_us_per_m, anchor_md, anchor_twt_ms, edge_m: float = 30.0,
name: str = "calibrated") -> TDR:
"""Marker-calibrated vertical sonic TDR (the scoring reference of plan §5.2) over the whole survey.
Within the valid DT range: the vertical sonic through the first anchor in that range, stretched between
consecutive anchors in the range and bulk-shifted beyond them (`calibrate_to_anchors`). Outside the valid DT
range, which only places the well path in time and never carries labels: piecewise linear in TVD through the
anchors there, continued at the outermost segment's velocity; with no anchor on that side, constant vertical
velocity equal to the median sonic velocity over the adjacent `edge_m` of logged hole."""
md, dt = np.asarray(md, dtype=float), np.asarray(dt_us_per_m, dtype=float)
ok = np.isfinite(dt) & (dt > 0)
if ok.sum() < 2:
raise ValueError("no valid DT")
md_v, dt_v = md[ok], dt[ok]
m0, m1 = md_v[0], md_v[-1]
za, ta = _sorted_anchors(anchor_md, anchor_twt_ms)
inside = (za >= m0) & (za <= m1)
if inside.sum() < 2:
raise ValueError(f"{traj.name}: fewer than two anchors within the valid DT range {m0}–{m1} m")
base = vertical_sonic_tdr(md_v, traj.at(md_v)[0], dt_v, za[inside][0], ta[inside][0])
core = calibrate_to_anchors(base, za[inside], ta[inside], name)
def extend(nodes: np.ndarray, beyond: np.ndarray, edge_md: float, edge_t: float, edge_dt: np.ndarray):
if nodes.size == 0:
return nodes
zc = np.r_[traj.at(za[beyond])[0], traj.at(edge_md)[0]]
tc = np.r_[ta[beyond], edge_t]
zn = traj.at(nodes)[0]
if zc.size >= 2:
order = np.argsort(zc)
return _interp_extrap(zn, zc[order], tc[order])
return edge_t + 2000.0 * (zn - zc[0]) / float(np.median(1e6 / edge_dt))
up, down = za < m0, za > m1
md_up = _nodes(traj, -np.inf, m0, za[up])
md_down = _nodes(traj, m1, np.inf, za[down])
t_up = extend(md_up, up, m0, core.twt_ms[0], dt_v[md_v <= m0 + edge_m])
t_down = extend(md_down, down, m1, core.twt_ms[-1], dt_v[md_v >= m1 - edge_m])
return TDR(np.r_[md_up, core.md, md_down], np.r_[t_up, core.twt_ms, t_down], name)
def anchor_tdr(traj: Trajectory, anchor_md, anchor_twt_ms, name: str = "anchors") -> TDR:
"""Piecewise linear in TVD between anchors, without the sonic. Meaningful only within the anchor span."""
za, ta = _sorted_anchors(anchor_md, anchor_twt_ms)
nodes = np.union1d(_nodes(traj, za[0], za[-1]), za)
return TDR(nodes, np.interp(traj.at(nodes)[0], traj.at(za)[0], ta), name)
def path_at_times(traj: Trajectory, tdr: TDR, t_ms) -> dict[str, np.ndarray]:
"""Well position at each time of `t_ms` under `tdr`. Below TD (or above the first station) the position is
held at the end station, i.e. the path continues vertically; `beyond` flags those samples."""
md = tdr.depth_at(t_ms)
tvd, x, y = traj.at(np.clip(md, traj.md[0], traj.md[-1]))
return {"md": md, "tvd": tvd, "x": x, "y": y, "beyond": (md < traj.md[0]) | (md > traj.md[-1])}
def tvdss_td_model(trajs: list[Trajectory], tdrs: list[TDR], z) -> np.ndarray:
"""Mean TWT over wells at TVDSS `z`; each well's MD-keyed TDR is mapped through its own trajectory and
extrapolated linearly beyond its nodes. Used to place a held-out well in time without its own TD data."""
z = np.asarray(z, dtype=float)
out = []
for traj, tdr in zip(trajs, tdrs, strict=True):
md = tdr.md[(tdr.md >= traj.md[0]) & (tdr.md <= traj.md[-1])]
zs = traj.tvdss(md)
if np.any(np.diff(zs) <= 0):
raise ValueError(f"{traj.name}: TVDSS does not increase strictly along the TDR nodes")
out.append(_interp_extrap(z, zs, tdr.time_at(md)))
return np.mean(out, axis=0)
def tdr_from_tvdss(traj: Trajectory, z_model, t_model, name: str = "tvdss_model") -> TDR:
"""MD-keyed TDR of `traj` over its survey from a TVDSS → TWT function (z_model, t_model)."""
md = np.union1d(_nodes(traj, -np.inf, np.inf), traj.md)
return TDR(md, _interp_extrap(traj.tvdss(md), np.asarray(z_model, float), np.asarray(t_model, float)), name)
def composite_patch(cube, il, xl, times_ms, radius: int = 1, method: str = "bilinear",
cache: dict | None = None) -> np.ndarray:
"""Seismic patch along a well path, shape (C, L) with C = (2r+1)²: channel (di, dx), in the IL-major order of
`SeismicCube.patch`, holds at sample n the trace at (il[n] + di, xl[n] + dx) evaluated at times_ms[n], which
must lie on the cube's sample grid. 'bilinear' interpolates the four surrounding bins; 'nearest' takes the
nearest one. `cube` needs `times_ms`, `dt_ms` and `trace(il, xl)`; `cache` maps (il, xl) to traces."""
if method not in ("bilinear", "nearest"):
raise ValueError(f"unknown method {method!r}")
il, xl, t = (np.asarray(v, dtype=float) for v in (il, xl, times_ms))
k = np.rint((t - cube.times_ms[0]) / cube.dt_ms).astype(int)
if np.any(k < 0) or np.any(k >= len(cube.times_ms)) or not np.allclose(cube.times_ms[k], t, rtol=0, atol=1e-6):
raise ValueError("times_ms must lie on the cube's sample grid")
cache = {} if cache is None else cache
def add(out: np.ndarray, i: np.ndarray, j: np.ndarray, w: np.ndarray) -> None:
on = w > 0
for key in set(zip(i[on].tolist(), j[on].tolist())):
if key not in cache:
cache[key] = cube.trace(*key)
sel = on & (i == key[0]) & (j == key[1])
out[sel] += w[sel] * cache[key][k[sel]]
channels = []
for di in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
fi, fj = il + di, xl + dx
out = np.zeros(t.size)
if method == "nearest":
add(out, np.rint(fi).astype(int), np.rint(fj).astype(int), np.ones(t.size))
else:
i0, j0 = np.floor(fi).astype(int), np.floor(fj).astype(int)
wi, wj = fi - i0, fj - j0
for a, b, w in ((0, 0, (1 - wi) * (1 - wj)), (0, 1, (1 - wi) * wj),
(1, 0, wi * (1 - wj)), (1, 1, wi * wj)):
add(out, i0 + a, j0 + b, w)
channels.append(out)
return np.stack(channels).astype(np.float32)

View File

@@ -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")
# IL/XL locations used in the thesis (test 2/prepare_data.py:17–21); for auditing only, not used. # IL/XL locations used in the thesis (code_thesis/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)}

View File

@@ -0,0 +1,126 @@
"""P4 Volve wells: survey, petrophysical logs and TWT anchors of one wellbore (`p4` section of configs/d3_volve.yaml).
Logs are taken from the petrophysical interpretation (WLC_PETRO_COMPUTED_INPUT/OUTPUT LAS, MD from RKB) and
converted to the F3 units: DT µs/m, RHOB kg/m³, AI = RHOB·Vp in (m/s)·(kg/m³). Anchors are the well picks with a
TWT, minus the excluded surfaces and quality flags; picks at the same MD (e.g. SHETLAND GP. Top = Ekofisk Fm. Top)
or within `min_sep_m` of a shallower anchor are one marker.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from ml_porosity.data.deviated import Trajectory, read_compass_header
from ml_porosity.data.las_io import read_las
from ml_porosity.paths import volve_root
FT_M = 0.3048
_UNITS = {"DT": {"us/ft"}, "RHOB": {"g/cm3"}, "NPHI": {"v/v", "v/v_decimal"}, "PHIF": {"v/v", "v/v_decimal"}}
ANCHOR_COLUMNS = ["surface", "qlf", "md", "tvd", "tvdss", "twt_ms", "x", "y"]
@dataclass(frozen=True)
class VolveWell:
name: str # short name used in P4, e.g. "F-11 T2"
pick_name: str # name in the well picks, e.g. "NO 15/9-F-11 T2"
traj: Trajectory
header: dict[str, str] # Compass survey header
logs: pd.DataFrame # index MD (m RKB) within the survey; DT, RHOB, NPHI, GR, PHIF, AI
anchors: pd.DataFrame # ANCHOR_COLUMNS, strictly increasing in MD and TWT
excluded: pd.DataFrame # picks with a TWT that are not anchors: ANCHOR_COLUMNS + `reason`
qc: dict = field(default_factory=dict) # loader counts: DT samples rejected, samples dropped beyond the survey
def valid_range(self, curve: str) -> tuple[float, float]:
v = self.logs[curve].dropna()
return float(v.index[0]), float(v.index[-1])
def label_support(self, label: str = "PHIF") -> tuple[float, float]:
"""MD range of the label within the valid DT range: labels are never placed by an extrapolated TDR."""
(a, b), (c, d) = self.valid_range(label), self.valid_range("DT")
if max(a, c) >= min(b, d):
raise ValueError(f"{self.name}: {label} and DT do not overlap")
return max(a, c), min(b, d)
def blind_training_wells(test: str, scheme: str, p4: dict) -> tuple[str, ...]:
"""Wells whose data may be used when `test` is held out: `lowo` all others, `slot` all outside its slot group."""
if scheme == "lowo":
out = set(p4["wells"]) - {test}
elif scheme == "slot":
group = next(set(g) for g in p4["slot_groups"] if test in g)
out = set(p4["wells"]) - group
else:
raise ValueError(f"unknown blind scheme {scheme!r}")
return tuple(w for w in p4["wells"] if w in out)
def blind_key(wells) -> str:
"""npz key of the blind input placed in time by the TD model of `wells` (any order)."""
return "+".join(sorted(wells))
def well_anchors(picks: pd.DataFrame, pick_name: str, exclude_surfaces, exclude_qlf,
min_sep_m: float = 0.0) -> tuple[pd.DataFrame, pd.DataFrame]:
"""(anchors, excluded) for one well from `read_well_picks` output. A pick at most `min_sep_m` below the last
kept anchor is dropped, preferring picks without a quality flag at equal MD; picks at the same MD must agree
in TWT."""
p = picks[(picks.well == pick_name) & picks.twt_ms.notna()].copy()
p["reason"] = ""
p.loc[p.qlf.isin(exclude_qlf), "reason"] = "qlf " + p.qlf
p.loc[p.surface.isin(exclude_surfaces), "reason"] = "surface"
cand = p[p.reason == ""].assign(flagged=lambda d: d.qlf != "").sort_values(["md", "flagged"], kind="stable")
keep: list = []
for i, r in cand.iterrows():
if keep and r.md - p.at[keep[-1], "md"] <= min_sep_m:
first = p.loc[keep[-1]]
if r.md == first.md and abs(r.twt_ms - first.twt_ms) > 0.1:
raise ValueError(f"{pick_name}: picks at MD {r.md} disagree in TWT")
p.at[i, "reason"] = (f"same MD as {first.surface}" if r.md == first.md
else f"{r.md - first.md:.2f} m below {first.surface}")
else:
keep.append(i)
anchors = p.loc[keep, ANCHOR_COLUMNS].reset_index(drop=True)
if np.any(np.diff(anchors.twt_ms) <= 0):
raise ValueError(f"{pick_name}: anchor TWT does not increase with MD")
excluded = p.loc[p.reason != "", ANCHOR_COLUMNS + ["reason"]].sort_values("md", kind="stable")
return anchors, excluded.reset_index(drop=True)
def load_volve_well(name: str, cfg: dict, picks: pd.DataFrame) -> VolveWell:
p4, spec, root = cfg["p4"], cfg["p4"]["wells"][name], volve_root()
survey = root / p4["survey_dir"] / spec["survey"]
traj = Trajectory.from_compass(survey, name)
folder = root / cfg["well_logs_dir"] / spec["logs"] / p4["log_subdir"]
li, ui, _ = read_las(folder / p4["las_input"])
lo, uo, _ = read_las(folder / p4["las_output"])
units = ui | {"PHIF": uo.get("PHIF", "")}
for c, ok in _UNITS.items():
if units.get(c, "").lower() not in ok:
raise ValueError(f"{name}: unexpected unit {units.get(c)!r} for {c}")
# OUTPUT is sampled on the INPUT MD grid (0.1 m; 0.5 ft for F-12)
key = np.round(li.index.to_numpy(), 3)
phif = pd.Series(lo["PHIF"].to_numpy(), index=np.round(lo.index.to_numpy(), 3))
if not phif.index.isin(key).all():
raise ValueError(f"{name}: OUTPUT depths are not on the INPUT grid")
dt_ft = li["DT"].to_numpy(dtype=float)
lo_ft, hi_ft = p4["dt_valid_us_per_ft"]
bad = np.isfinite(dt_ft) & ((dt_ft < lo_ft) | (dt_ft > hi_ft))
dt = np.where(bad, np.nan, dt_ft) / FT_M
rhob = li["RHOB"].to_numpy(dtype=float) * 1000.0
logs = pd.DataFrame({"DT": dt, "RHOB": rhob, "NPHI": li["NPHI"].to_numpy(dtype=float),
"GR": li["GR"].to_numpy(dtype=float), "PHIF": phif.reindex(key).to_numpy(dtype=float),
"AI": rhob * 1e6 / dt}, index=pd.Index(li.index.to_numpy(dtype=float), name="MD"))
# Only positions on the survey can be placed in time. F-12 has GR down to 4187 m below its 3520 m TD.
inside = (logs.index >= traj.md[0]) & (logs.index <= traj.md[-1])
beyond = logs[~inside].notna().sum()
if beyond[["DT", p4["label"]]].any():
raise ValueError(f"{name}: DT or {p4['label']} beyond the survey {traj.md[0]}–{traj.md[-1]} m")
anchors, excluded = well_anchors(picks, spec["picks"], cfg["anchor_exclude_surfaces"], p4["anchor_exclude_qlf"],
p4["anchor_min_sep_m"])
qc = {"n_dt_rejected": int(bad.sum()), "n_beyond_survey": {c: int(n) for c, n in beyond.items() if n}}
return VolveWell(name, spec["picks"], traj, read_compass_header(survey), logs[inside], anchors, excluded, qc)

View File

@@ -0,0 +1 @@
"""P3: blind-well F3 experiments, separate from the frozen P1/P2 protocols."""

85
ml_porosity/f3/data.py Normal file
View File

@@ -0,0 +1,85 @@
"""Explicit separation between training logs, seismic-only targets, and scoring references."""
from __future__ import annotations
import numpy as np
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
from ml_porosity.models.bank_train import zscore_patch
from ml_porosity.paths import outputs_dir
from ml_porosity.registration.warp_prior import WarpGrid
class F3Data:
def __init__(self, protocol: dict, training_wells: tuple[str, ...] | None = None):
self.protocol = protocol
self.wells = protocol['data']['wells']
self.training_wells = None if training_wells is None else frozenset(training_wells)
if self.training_wells is not None and not self.training_wells <= set(self.wells):
raise ValueError('Unknown training well')
public = {'seismic_patch', 'times_ms', 'main_mask', 'il', 'xl', 'x', 'y'}
with np.load(outputs_dir() / 'f3_wells.npz') as z:
self.arrays = {k: z[k] for k in z.files if self.training_wells is None
or k.split('/', 1)[0] in self.training_wells or k.split('/', 1)[1] in public}
self.t = self.ext(self.wells[0], 'times_ms')
self.main = self.ext(self.wells[0], 'main_mask').astype(bool)
self.t_main = self.t[self.main]
r = protocol['registration']
self.dt = float(np.diff(self.t)[0])
self.grid = WarpGrid(*r['tau_range_ms'], r['warp_dtau_ms'])
self.tau = np.arange(*[r['tau_range_ms'][0], r['tau_range_ms'][1] + r['fine_dt_ms'] / 2, r['fine_dt_ms']])
self.t_fine = np.arange(self.t[0] - 300, self.t[-1] + 300 + r['fine_dt_ms'] / 2, r['fine_dt_ms'])
for w in self.wells:
if not np.array_equal(self.ext(w, 'times_ms'), self.t):
raise ValueError('F3 well time axes differ')
if self.training_wells is not None and w not in self.training_wells:
continue
for label in protocol['data']['labels']:
for ref in protocol['data']['references']:
if not np.isfinite(self.y(w, ref, label)).all():
raise ValueError(f'Non-finite scoring labels: {w}/{ref}/{label}')
def ext(self, well: str, key: str):
return self.arrays[f'{well}/{key}']
def X(self, well: str) -> np.ndarray:
return zscore_patch(self.ext(well, 'seismic_patch'), self.main)
def y(self, well: str, reference: str, label: str) -> np.ndarray:
if self.training_wells is not None and well not in self.training_wells:
raise RuntimeError('Held-out labels are unavailable in a training data view')
return self.ext(well, f'{reference}/{label}')[self.main]
def training_observations(self, names: tuple[str, ...], omit_anchor: tuple[str, int] | None = None) -> list[dict]:
"""Only named wells are loaded here; callers pass the exact inner training set."""
if self.training_wells is not None and not set(names) <= self.training_wells:
raise RuntimeError('Held-out logs and anchors are unavailable in a training data view')
obs = []
for name in names:
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())
mask = (tk >= self.t[0]) & (tk <= self.t[-1])
tau_k, tk = tau_k[mask], tk[mask]
if omit_anchor is not None and omit_anchor[0] == name:
keep = np.arange(len(tk)) != omit_anchor[1]
tau_k, tk = tau_k[keep], tk[keep]
kwargs = dict(fine_dt_ms=0.25, cutoff_frac=0.8)
curves = {'AI': w.curve('AI'), 'PHIE_DT': -0.2018 + 0.0011 * w.curve('DT'), 'PHIE': w.curve('PHIE')}
resampled = {}
valid_labels = {}
for label, values in curves.items():
v = log_to_time(w.md, values, base, self.tau, **kwargs)
good = np.isfinite(v)
if good.sum() < 2:
raise ValueError(f'No sonic-domain log: {name}/{label}')
resampled[label] = np.interp(self.tau, self.tau[good], v[good])
if label != 'AI':
valid_labels[label] = good
obs.append({'name': name, 'tau_k': tau_k, 't_k': tk, 'ai_log': resampled.pop('AI'),
'labels': resampled, 'label_valid': valid_labels,
'seis': self.ext(name, 'seismic_patch')[4].astype(float)})
return obs

View File

@@ -0,0 +1,269 @@
"""Nested selection, scoring-only registration sensitivity, and the unchanged G-C gate."""
from __future__ import annotations
import importlib.util
import json
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pandas as pd
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
from ml_porosity.f3.data import F3Data
from ml_porosity.f3.progress import update, write_json
from ml_porosity.f3.protocol import inner_folds
from ml_porosity.f3.runner import job_path, load_bundle
from ml_porosity.f3.training import ensemble
from ml_porosity.paths import REPO_ROOT
def choose_budget(curves: np.ndarray, budgets: list[int]) -> int:
"""curves=(inner validation wells, budgets); equal weight per well, earliest tie."""
curves = np.asarray(curves, float)
if curves.ndim != 2 or curves.shape[1] != len(budgets) or not np.isfinite(curves).all():
raise ValueError('Invalid inner-validation curves')
return int(budgets[int(np.argmin(curves.mean(axis=0)))])
def neural_predictions(data: F3Data, p: dict, root: Path) -> tuple[list[dict], list[dict]]:
predictions, selections = [], []
variants = [(p['registration']['sigma_a_ms'], lab, m) for lab in p['data']['labels'] for m in p['methods']['main']]
variants += [(p['registration']['sigma_a_ms'], lab, m) for lab in p['methods']['ablation_labels'] for m in p['methods']['ablations']]
variants += [(sa, lab, m) for sa in p['registration']['sigma_a_sensitivity_ms']
for lab in p['registration']['sensitivity_labels'] for m in p['registration']['sensitivity_methods']]
budgets = p['training']['budgets']
for outer in data.wells:
for sa, label, method in variants:
per_seed = []
for seed in p['split']['seeds']:
folds = inner_folds(data.wells, outer)
curves, cache = [], []
for validation, train in folds:
if outer in train or validation in train:
raise RuntimeError('Held-out well entered training')
z = load_bundle(job_path(root, train, method, label, seed, sa))
names = list(z['wells'])
curves.append([np.mean((z[f'{b}/mu'][names.index(validation)] - data.y(validation, 'calibrated', label))**2) for b in budgets])
cache.append((validation, train, z, names))
budget = choose_budget(np.array(curves), budgets)
k = budgets.index(budget)
mu, sigma = ensemble(np.stack([z[f'{budget}/mu'][names.index(outer)] for _, _, z, names in cache]),
np.stack([z[f'{budget}/sigma'][names.index(outer)] for _, _, z, names in cache]))
entry = dict(test_well=outer, method=method, label=label, sigma_a_ms=sa, seed=seed, members=len(folds), mu=mu, sigma=sigma)
predictions.append(entry)
per_seed.append(entry)
selections.append(dict(test_well=outer, method=method, label=label, sigma_a_ms=sa, seed=seed,
budget=budget, validation_mse=float(np.mean(np.asarray(curves)[:, k])),
validation_wells=';'.join(v for v, _ in folds),
training_sets=';'.join(','.join(tr) for _, tr in folds)))
mu, sigma = ensemble(np.stack([v['mu'] for v in per_seed]), np.stack([v['sigma'] for v in per_seed]))
predictions.append(dict(test_well=outer, method=method, label=label, sigma_a_ms=sa, seed='ensemble',
members=sum(v['members'] for v in per_seed), mu=mu, sigma=sigma))
return predictions, selections
def gate_verdict(metrics: pd.DataFrame, selection: pd.DataFrame, p: dict) -> dict:
primary = metrics[(metrics.label == p['data']['primary_label']) & (metrics.reference == 'calibrated')
& (metrics.seed.astype(str) == 'ensemble') & (metrics.sigma_a_ms == p['registration']['sigma_a_ms'])]
selected, per_well = {}, []
for well in p['data']['wells']:
scores = selection[(selection.test_well == well) & (selection.label == p['data']['primary_label'])
& (selection.sigma_a_ms == p['registration']['sigma_a_ms'])
& selection.method.isin(p['gate']['point_competitors'])].groupby('method').validation_mse.mean()
if len(scores) != len(p['gate']['point_competitors']):
return {'evaluated': False, 'pass': None, 'reason': 'Reduced smoke run or incomplete point competitors'}
selected[well] = str(scores.idxmin())
candidate = primary[(primary.test_well == well) & (primary.method == p['gate']['candidate'])]
base = primary[(primary.test_well == well) & (primary.method == selected[well])]
if len(candidate) != 1 or len(base) != 1:
raise ValueError(f'Incomplete G-C predictions for {well}')
a, b = candidate.iloc[0], base.iloc[0]
per_well.append(dict(well=well, competitor=selected[well], ratio=float(a.band_rmse/b.band_rmse),
improved=bool(a.band_rmse < b.band_rmse), coverage_80=float(a.coverage_80), coverage_90=float(a.coverage_90)))
wins = sum(v['improved'] for v in per_well)
c80 = float(np.mean([v['coverage_80'] for v in per_well]))
c90 = float(np.mean([v['coverage_90'] for v in per_well]))
direction, calibration = wins >= 3, abs(c80-0.8) <= 0.05+1e-12 and abs(c90-0.9) <= 0.05+1e-12
return dict(evaluated=True, direction_pass=direction, improved_wells=wins,
coverage_pass=calibration, coverage_80=c80, coverage_90=c90, per_well=per_well,
**{'pass': direction and calibration})
def diagnostics(p: dict, root: Path) -> None:
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.pipeline import fit_cell_hyper
from ml_porosity.registration.sampler import sample_warps
from ml_porosity.registration.warp_prior import loao_zscores
from ml_porosity.f3.registration import valid_label_warps
smoke = root.name == 'smoke'
update(status='Đánh giá độ nhạy registration', message='Log và marker giếng test chỉ được dùng trong giai đoạn chấm điểm.',
tasks={} if smoke else {'p3-abl': 'doing'})
data = F3Data(p)
refs, rows, metadata = {}, [], []
r = p['registration']
for idx, test in enumerate(data.wells):
train_names = tuple(w for w in data.wells if w != test)
train_obs = data.training_observations(train_names)
h, info = fit_cell_hyper(SimpleNamespace(grid=data.grid), train_obs, r, 0)
o = data.training_observations((test,))[0]
anchor = {'grid': data.grid, 'tau_k': o['tau_k'], 'd_k': o['t_k']-o['tau_k']}
zs = loao_zscores([anchor], h)[0]
for k, z in enumerate(zs):
rows.append(dict(well=test, anchor=k, twt_ms=float(o['t_k'][k]), z=float(z),
inside90=bool(abs(z) <= 1.6448536269514722), approximation='linearized_anchor_GP',
hyper_training_wells=';'.join(train_names)))
count = p['data']['posterior_reference_samples']
smp = sample_warps(data.grid, h, o['tau_k'], o['t_k'], 4*count, r['g_max'],
np.random.default_rng([idx, 53]))
tg = data.grid.t_of_tau(smp['b'], smp['g'], data.tau)
valid = valid_label_warps(data, o, tg, p['data']['labels'])
if valid.sum() < count:
raise ValueError(f'Insufficient scoring-reference samples covering measured labels: {test}')
tg = tg[valid][:count]
for label in p['data']['labels']:
y = antialias(o['labels'][label], r['fine_dt_ms'], data.dt)
ref = labels_for_warps(data.tau, y, tg, data.t_main)
if not np.isfinite(ref).all():
raise ValueError(f'Non-finite posterior scoring reference: {test}/{label}')
refs[f'{test}/{label}'] = ref
metadata.append(dict(scoring_well=test, prior_training_wells=train_names, hyper=h.as_dict(), hyper_info=info,
valid_samples_before_selection=int(valid.sum()), samples_scored=count))
dest = root/'diagnostics'
dest.mkdir(parents=True, exist_ok=True)
pd.DataFrame(rows).to_csv(dest/'loao.csv', index=False)
np.savez_compressed(dest/'evaluation_references.npz', **refs)
write_json(dest/'evaluation_references.json', {'role': 'scoring sensitivity only; never checkpoint selection', 'folds': metadata})
update(status='Đã tính độ nhạy tham chiếu', message='LOAO là xấp xỉ GP chỉ dùng anchor; trạng thái ablation chỉ hoàn tất sau khi tổng hợp đầy đủ.')
def classical_predictions(data: F3Data, p: dict) -> list[dict]:
spec = importlib.util.spec_from_file_location('p1_lowo', REPO_ROOT/'scripts/05_lowo.py')
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
import yaml
prior = yaml.safe_load((REPO_ROOT/'configs/protocol.yaml').read_text(encoding='utf-8'))
d = mod.Data(prior)
d.proto = prior
result = []
for label in p['data']['labels']:
for test in data.wells:
pred, _ = mod.run_classical(d, label, test, p['split']['seeds'])
for method in sorted({m for m, *_ in pred}):
mu = np.mean([a for m, _, a, _ in pred if m == method], axis=0)
result.append(dict(test_well=test, method=method, label=label, sigma_a_ms=p['registration']['sigma_a_ms'],
seed='ensemble', members=sum(m == method for m, *_ in pred), mu=mu, sigma=None))
return result
def score(data: F3Data, pred: dict, reference: str, f_c: float) -> dict:
y, mu = 100*data.y(pred['test_well'], reference, pred['label']), 100*pred['mu']
row = {k: v for k, v in pred.items() if k not in ('mu', 'sigma')}
row |= dict(reference=reference, f_c_hz=f_c) | point_metrics(y, mu) | band_metrics(y, mu, f_c, data.dt)
if pred['sigma'] is not None:
row |= gaussian_metrics(y, mu, np.maximum(100*pred['sigma'], 1e-6))
return row
def summarize(p: dict, root: Path) -> dict:
data = F3Data(p)
pred, sel = neural_predictions(data, p, root)
smoke = root.name == 'smoke'
if not smoke and p['methods']['classical']:
pred += classical_predictions(data, p)
rows = [score(data, a, ref, p['metrics']['f_c_hz']) for a in pred for ref in p['data']['references']]
frame, selections = pd.DataFrame(rows), pd.DataFrame(sel)
gate = gate_verdict(frame, selections, p)
if smoke:
gate = {'evaluated': False, 'pass': None, 'reason': 'Smoke run; not the registered P3 experiment'}
dest = root/'summary'
dest.mkdir(parents=True, exist_ok=True)
frame.to_csv(dest/'metrics.csv', index=False)
selections.to_csv(dest/'selection.csv', index=False)
main = frame[(frame.seed.astype(str) == 'ensemble') & (frame.reference == 'calibrated')
& (frame.sigma_a_ms == p['registration']['sigma_a_ms'])]
cols = ['rmse', 'pcc', 'r2', 'band_rmse', 'band_pcc', 'std_ratio', 'coverage_80', 'coverage_90', 'nll', 'crps']
macro = main.groupby(['label', 'method'])[cols].mean().reset_index()
macro.to_csv(dest/'macro.csv', index=False)
cutoff = [score(data, a, 'calibrated', fc) for a in pred if a['seed'] == 'ensemble'
for fc in p['metrics']['sensitivity_f_c_hz']]
pd.DataFrame(cutoff).to_csv(dest/'band_sensitivity.csv', index=False)
posterior_rows = []
reference_file = root/'diagnostics/evaluation_references.npz'
if reference_file.exists():
refs = load_bundle(reference_file)
for a in pred:
if a['seed'] != 'ensemble':
continue
vals = [point_metrics(100*y, 100*a['mu']) | band_metrics(100*y, 100*a['mu'], p['metrics']['f_c_hz'])
for y in refs[f'{a["test_well"]}/{a["label"]}']]
item = {k: v for k, v in a.items() if k not in ('mu', 'sigma')}
for metric in ('rmse', 'pcc', 'band_rmse', 'band_pcc'):
item |= {f'{metric}_q05': float(np.quantile([v[metric] for v in vals], .05)),
f'{metric}_q95': float(np.quantile([v[metric] for v in vals], .95))}
posterior_rows.append(item)
pd.DataFrame(posterior_rows).to_csv(dest/'posterior_reference_sensitivity.csv', index=False)
diag_shift = []
for a in pred:
if a['seed'] != 'ensemble':
continue
y, mu = data.y(a['test_well'], 'calibrated', a['label']), a['mu']
candidates = []
for shift in range(-16, 17):
start, stop = max(0, -shift), min(len(y), len(y)-shift)
candidates.append((point_metrics(y[start:stop], mu[start+shift:stop+shift])['pcc'], shift))
_, lag = max(candidates)
diag_shift.append({k: v for k, v in a.items() if k not in ('mu', 'sigma')} | {'best_shift_ms': lag*data.dt})
pd.DataFrame(diag_shift).to_csv(dest/'best_shift_DIAGNOSTIC_ONLY.csv', index=False)
saved = {}
for i, a in enumerate(pred):
saved[f'{i}/mu'] = a['mu']
if a['sigma'] is not None:
saved[f'{i}/sigma'] = a['sigma']
np.savez_compressed(dest/'predictions.npz', times_ms=data.t_main, **saved)
write_json(dest/'prediction_index.json', [{k: v for k, v in a.items() if k not in ('mu', 'sigma')} for a in pred])
write_json(dest/'gate_gc.json', gate)
text = ['# P3 F3 — nested LOWO', '', 'Smoke only; no scientific verdict.' if smoke else 'Registered protocol_f3; outer labels are scoring-only.', '',
'G-C: ' + json.dumps(gate, ensure_ascii=False), '', '## Macro over four wells (p.u.)', '', macro.to_markdown(index=False, floatfmt='.4f'), '',
'Per-well and per-seed results: metrics.csv. Epoch selection: selection.csv.',
'Registration-reference sensitivity and best-shift diagnostics never alter the primary scores.',
'LOAO is an anchor-only linear GP approximation; maps and four wells do not establish field-wide geological validity.']
(dest/'summary.md').write_text('\n'.join(text)+'\n', encoding='utf-8')
plot_results(data, p, pred, dest)
if not smoke:
diagnostics_done = reference_file.exists() and (root/'diagnostics/loao.csv').exists()
update(status='LOWO đã hoàn tất', message=f'G-C: {"ĐẠT" if gate.get("pass") else "KHÔNG ĐẠT"}; giữ nguyên mọi ngưỡng. Volume là bước riêng.',
gate=gate, completed=None, total=None, eta_seconds=None,
tasks={'p3-lowo': 'done', 'p3-abl': 'done' if diagnostics_done else 'doing'})
return gate
def plot_results(data: F3Data, p: dict, pred: list[dict], dest: Path) -> None:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 4, figsize=(15, 6), sharey=True, sharex=True, layout='constrained')
for ax, w in zip(axes, data.wells):
ax.plot(100*data.y(w, 'calibrated', p['data']['primary_label']), data.t_main, 'k', label='Reference')
for method, color, style in (('B3b', '#0072B2', '--'), ('B3d-Sa', '#8F5800', ':'), ('M2-Sa', '#CC3311', '-')):
rows = [a for a in pred if a['test_well'] == w and a['label'] == p['data']['primary_label']
and a['method'] == method and a['seed'] == 'ensemble' and a['sigma_a_ms'] == p['registration']['sigma_a_ms']]
if rows:
a = rows[0]
ax.plot(100*a['mu'], data.t_main, color=color, linestyle=style, label=method)
if method == 'M2-Sa':
ax.fill_betweenx(data.t_main, 100*(a['mu']-1.64485*a['sigma']), 100*(a['mu']+1.64485*a['sigma']), color=color, alpha=.18)
ax.set(title=w, xlabel='Sonic-derived porosity (p.u.)')
ax.grid(alpha=.2)
axes[0].set_ylabel('TWT (ms)')
axes[0].invert_yaxis()
axes[0].legend(fontsize=8)
fig.savefig(dest/'wells.png', dpi=160)
fig.savefig(dest/'wells.pdf')
plt.close(fig)
write_json(dest/'figure_manifest.json', {'source': 'predictions.npz and prediction_index.json',
'reference': 'marker-calibrated sonic', 'uncertainty': 'nominal 90% moment-matched Gaussian predictive interval; calibration is evaluated separately',
'replication_unit': 'well (n=4); network seeds are computational repeats', 'transform': 'porosity fraction multiplied by 100',
'filters': 'See protocol_f3; no plotting smoothing', 'publisher_requirements': 'not yet verified',
'description': 'Four well panels show reference and blind predictions against downward-increasing two-way time; M2-Sa carries its nominal predictive interval.'})

View File

@@ -0,0 +1,31 @@
"""One parent writer publishes JSON and a local-file-compatible report.html sidecar."""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from ml_porosity.paths import outputs_dir
def write_json(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + f'.{os.getpid()}.tmp')
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False, default=str), encoding='utf-8')
tmp.replace(path)
def update(**values) -> dict:
root = outputs_dir() / 'p3'
path = root / 'progress.json'
old = json.loads(path.read_text(encoding='utf-8')) if path.exists() else {}
if 'tasks' in values:
values['tasks'] = old.get('tasks', {}) | values['tasks']
state = old | values | {'updated': datetime.now().astimezone().isoformat(timespec='seconds')}
write_json(path, state)
js = root / 'progress.js'
tmp = js.with_suffix('.js.tmp')
tmp.write_text('window.ML_POROSITY_P3 = ' + json.dumps(state, ensure_ascii=False, default=str) + ';\n', encoding='utf-8')
tmp.replace(js)
return state

View File

@@ -0,0 +1,99 @@
"""Portable protocol locking and resume fingerprints for P3."""
from __future__ import annotations
import hashlib
import importlib.metadata
import itertools
import json
import platform
from datetime import datetime, timezone
from pathlib import Path
import yaml
from ml_porosity.paths import REPO_ROOT, f3_root, f3_segy, outputs_dir
CONFIG = REPO_ROOT / 'configs/protocol_f3.yaml'
LOCK = REPO_ROOT / 'configs/protocol_f3.lock.json'
def digest(path: Path, text: bool = False) -> str:
h = hashlib.sha256()
if text:
h.update(path.read_bytes().replace(b'\r\n', b'\n'))
else:
with path.open('rb') as f:
for chunk in iter(lambda: f.read(8 * 1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def source_hash() -> str:
h = hashlib.sha256()
paths = sorted((REPO_ROOT / 'ml_porosity').rglob('*.py'))
paths += sorted((REPO_ROOT / 'scripts').glob('*.py'))
paths += [REPO_ROOT/'scripts/run_p3.ps1']
paths += [REPO_ROOT / 'pyproject.toml']
for p in paths:
h.update(p.relative_to(REPO_ROOT).as_posix().encode() + b'\0')
h.update(p.read_bytes().replace(b'\r\n', b'\n') + b'\0')
return h.hexdigest()
def environment() -> dict:
packages = ('torch', 'numpy', 'scipy', 'pandas', 'matplotlib', 'segyio', 'lasio', 'pylops',
'numba', 'scikit-learn', 'PyYAML', 'tabulate', 'psutil')
return {'python': platform.python_version(), 'platform': platform.system(),
'packages': {name: importlib.metadata.version(name) for name in packages}}
def load_protocol() -> dict:
return yaml.safe_load(CONFIG.read_text(encoding='utf-8'))
def training_sets(wells: list[str], size: int = 2) -> list[tuple[str, ...]]:
return list(itertools.combinations(sorted(wells), size))
def inner_folds(wells: list[str], outer: str) -> list[tuple[str, tuple[str, ...]]]:
if outer not in wells:
raise ValueError(outer)
train = [w for w in wells if w != outer]
return [(v, tuple(sorted(w for w in train if w != v))) for v in train]
def freeze(check: bool = False) -> dict:
p = load_protocol()
data = outputs_dir() / 'f3_wells.npz'
files = [data, REPO_ROOT/'configs/d1_f3.yaml', REPO_ROOT/'configs/protocol.yaml', f3_root()/'.survey']
files += sorted(f3_root().glob('WellInfo/*.wlt'))
files += sorted((f3_root() / 'Rawdata/Well_data').rglob('*.las'))
files += sorted((f3_root() / 'Rawdata/Well_data').rglob('*_TD.txt'))
protected = [outputs_dir()/'wavelets.npz', outputs_dir()/'p2/warp_prior_f3.json']
stamp = {'protocol_sha256': digest(CONFIG, True), 'code_sha256': source_hash(), 'environment': environment(),
'protected_artifacts': {str(f.relative_to(REPO_ROOT)): digest(f) for f in protected},
'inputs': {str(f.relative_to(REPO_ROOT)): digest(f) for f in files}}
if LOCK.exists():
old = json.loads(LOCK.read_text(encoding='utf-8'))
for k, v in stamp.items():
if old[k] != v:
raise RuntimeError(f'P3 lock mismatch: {k}. Preserve results and create a new protocol version.')
return old
if check:
raise RuntimeError('P3 is not locked. Run the lock stage before registration/training.')
if any((outputs_dir() / 'p3' / d).exists() for d in ('registration', 'train', 'summary')):
raise RuntimeError('Refusing a first lock after P3 results already exist.')
manifest = json.loads((REPO_ROOT / 'data_manifest/f3_demo_2023.json').read_text(encoding='utf-8'))
expected = manifest['files']['Rawdata/F3_entire.segy']['sha256']
if digest(f3_segy()) != expected:
raise RuntimeError('F3 cube differs from the audited source.')
stamp |= {'locked_utc': datetime.now(timezone.utc).isoformat(), 'segy_sha256': expected,
'canonical_text': 'UTF-8, CRLF normalized to LF for code and protocol; binary inputs exact',
'wells': p['data']['wells']}
LOCK.write_text(json.dumps(stamp, indent=2), encoding='utf-8')
CONFIG.with_suffix('.sha256').write_text(stamp['protocol_sha256'] + ' configs/protocol_f3.yaml\n', encoding='utf-8')
return stamp
def fingerprint(stamp: dict, **settings) -> str:
return hashlib.sha256(json.dumps({'lock': stamp, **settings}, sort_keys=True).encode()).hexdigest()

View File

@@ -0,0 +1,164 @@
"""Training-set-only F3 registration. No held-out well is passed to this module."""
from __future__ import annotations
import gc
import time
from types import SimpleNamespace
import numpy as np
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet
from ml_porosity.f3.data import F3Data
from ml_porosity.losses.rml import effective_lambda
from ml_porosity.registration.labels import antialias, invert_warps, labels_for_warps
from ml_porosity.registration.pipeline import PHASES, fit_cell_hyper
from ml_porosity.registration.sampler import sample_warps, temper
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet
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, warp_mean
from ml_porosity.registration.warp_prior import WarpHyper
def valid_label_warps(data, observation, warps, labels) -> np.ndarray:
tau_at = invert_warps(warps, data.tau, data.t_main)
valid = np.isfinite(tau_at).all(axis=1)
for label in labels:
support = np.interp(tau_at, data.tau, observation['label_valid'][label].astype(float), left=0, right=0)
valid &= (support >= 1-1e-9).all(axis=1)
return valid
def register_set(data: F3Data, names: tuple[str, ...], p: dict, device: str, sigma_a: float = 7.0,
no_anchors: bool = False) -> tuple[dict, dict]:
import torch
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
started = time.perf_counter()
r = p['registration'] | {'sigma_a_ms': sigma_a}
obs = data.training_observations(names)
if set(o['name'] for o in obs) != set(names):
raise RuntimeError('Unexpected training-well payload')
if no_anchors:
h = WarpHyper(0, r['hyperprior']['sigma_g'][0], r['hyperprior']['ell_ms'][0],
r['sigma_b_ms'], sigma_a, r['kernel'])
hinfo = {'note': 'Fixed prior medians, no training anchors used for hyperparameter fitting'}
obs = [o | {'tau_k': np.array([]), 't_k': np.array([])} for o in obs]
else:
h, hinfo = fit_cell_hyper(SimpleNamespace(grid=data.grid), obs, r, r['smc_seed'])
f = r['fine_dt_ms']
fac = int(round(data.dt / f))
w0 = statistical_wavelet(np.stack([o['seis'] for o in obs]), data.dt, r['wavelet_ms'])
samples, Ts, Zs, LL, anchor_valid = [], [], [], [], []
B = phase_basis(w0, fac)
for i, o in enumerate(obs):
smp = sample_warps(data.grid, h, o['tau_k'], o['t_k'], r['particles'], r['g_max'],
np.random.default_rng([r['smc_seed'], i, 13]))
samples.append(smp)
tg = data.grid.t_of_tau(smp['b'][:r['S']], smp['g'][:r['S']], data.tau)
valid = valid_label_warps(data, o, tg, p['data']['labels'])
if not valid.any():
raise ValueError(f'No anchor sample covers measured labels in the complete main window: {o["name"]}')
anchor_valid.append(valid)
LL.append(phase_loglik(synth_for_warps(data.tau, o['ai_log'], tg, data.t_fine, data.t,
fine_wavelet(w0, fac)), o['seis'], PHASES))
phase0 = float(PHASES[fit_phase(LL, anchor_valid, PHASES)])
for o, smp in zip(obs, samples):
T = TiePosteriorTorch(TiePosterior(data.grid, h, o['tau_k'], o['t_k'], r['g_max'], data.tau,
o['ai_log'], data.t_fine, data.t, phase_wavelet(B, phase0), o['seis'],
(data.t_main[0], data.t_main[-1]), allow_no_anchors=no_anchors), device)
Zs.append(T.z(smp['u']))
Ts.append(T)
phase_r, ph = smc_fit_phase(Ts, Zs, B, phase0, [r['smc_seed'], 19], step=r['phase_step'],
half_width=r['phase_half_width'], max_extra=r['phase_max_extra'], n_moves=r['smc_moves'])
wf = phase_wavelet(B, phase_r)
post, diag = [], []
for i, (o, T0, z0) in enumerate(zip(obs, Ts, Zs)):
T = T0.with_wavelet(wf)
gamma = gamma_acf(T, z0, T.parts(z0)[1])
res = smc_tie_posterior(T, z0, [gamma], np.random.default_rng([r['smc_seed'], i, 17]), n_moves=r['smc_moves'])
u = T.u(res['Z'][gamma])
tg = data.grid.t_of_tau(u[:, 0], u[:, 1:], data.tau)
valid = valid_label_warps(data, o, tg, p['data']['labels'])
if valid.sum() < min(256, r['particles']):
raise ValueError(f'Insufficient posterior particles covering all measured labels: {o["name"]}, {valid.sum()} valid')
tg = tg[valid]
post.append(tg)
tau_at = invert_warps(tg, data.tau, data.t_main)
sd = float(np.mean(np.diff(np.quantile(tau_at, [0.05, 0.95], axis=0), axis=0)) / 3.29)
diag.append({'well': o['name'], 'sigma_post_ms': sd, 'gamma': gamma, 'n_stages': len(res['stages']),
'valid_label_particles': int(valid.sum()), 'particles_before_label_support_check': len(valid)})
bundle = {'wells': np.asarray(names), 'phase0': np.asarray(phase0), 'phase_R': np.asarray(phase_r)}
for label in p['data']['labels']:
banks = {m: [] for m in ('B2', 'B3a', 'B3b', 'B3c', 'B3c-R', 'B3d', 'B3d-Sa', 'B4', 'M1', 'M2-Sa', 'M2-S256', 'M2-bulk')}
lps = {'M1': [], 'M2-Sa': [], 'M2-S256': []}
filtered = [antialias(o['labels'][label], f, data.dt) for o in obs]
normsel = (data.tau >= data.t_main[0]) & (data.tau <= data.t_main[-1])
vals = np.concatenate([y[normsel & o['label_valid'][label]] for o, y in zip(obs, filtered)])
bundle[f'{label}/norm'] = np.array([vals.mean(), max(vals.std(), 1e-8)])
ref = []
for i, (o, smp, tg, y) in enumerate(zip(obs, samples, post, filtered)):
def lab(t, times=data.t_main):
tau_at = invert_warps(t, data.tau, times)
support = np.interp(tau_at, data.tau, o['label_valid'][label].astype(float), left=0, right=0)
return np.where(support >= 1-1e-9, labels_for_warps(data.tau, y, np.atleast_2d(t), times), np.nan)
anchor_t = data.grid.t_of_tau(smp['b'][:r['S']], smp['g'][:r['S']], data.tau)
ya = lab(anchor_t)
valid = anchor_valid[i]
ya[~valid] = ya[valid][0]
likelihood = LL[i][int(np.flatnonzero(PHASES == phase0)[0])][valid]
weights = np.full(r['S'], -np.inf)
weights[valid], _, _ = temper(likelihood, r['ess_min_frac'])
b3b = tie_b3b(o['tau_k'], o['t_k'], data.tau)
ref.append(lab(b3b)[0])
bank_ties = {'B3b': b3b, 'B3d': warp_mean(anchor_t, weights), 'B3d-Sa': tg.mean(axis=0)}
for name, phase in (('B3c', phase0), ('B3c-R', phase_r)):
syn = synth_for_warps(data.tau, o['ai_log'], b3b, data.t_fine, data.t,
fine_wavelet(rotate_phase(w0, phase), fac))[0]
bank_ties[name] = tie_b3c(b3b, data.tau, syn, o['seis'], data.t, data.dt)
for method, tie in bank_ties.items():
banks[method].append(lab(tie))
banks['B2'].append(lab(b3b))
banks['B3a'].append(data.y(o['name'], 'legacy', label)[None])
banks['M1'].append(ya)
lps['M1'].append(np.where(valid, -np.log(valid.sum()), -np.inf))
for method, size in (('M2-Sa', r['S']), ('M2-S256', min(256, len(tg)))):
sub = np.random.default_rng([r['smc_seed'], i, 29]).choice(len(tg), size, replace=False)
banks[method].append(lab(tg[sub]))
lps[method].append(np.full(size, -np.log(size)))
K = r['shift_K']
times = np.arange(data.t_main[0] - K * data.dt, data.t_main[-1] + (K + 0.5) * data.dt, data.dt)
wide = lab(b3b, times)[0]
banks['B4'].append(np.stack([wide[K+j:K+j+len(data.t_main)] for j in range(-K, K+1)]))
prec = 1 / h.sigma_b_ms**2 + len(o['tau_k']) / sigma_a**2
bm = np.sum(o['t_k'] - o['tau_k']) / sigma_a**2 / prec
b = np.random.default_rng([r['smc_seed'], i, 37]).normal(bm, 1 / np.sqrt(prec), r['particles'])
bulk_t = data.tau[None] + b[:, None]
good_bulk = valid_label_warps(data, o, bulk_t, p['data']['labels'])
if not good_bulk.any():
raise ValueError(f'No bulk-only sample covers measured labels: {o["name"]}')
syn = synth_for_warps(data.tau, o['ai_log'], bulk_t, data.t_fine, data.t, wf)
from ml_porosity.registration.tie_likelihood import profile_loglik
ll = np.where(good_bulk, profile_loglik(syn, o['seis']) * diag[i]['gamma'], -np.inf)
prob = np.exp(ll - np.logaddexp.reduce(ll))
sub = np.random.default_rng([r['smc_seed'], i, 41]).choice(len(b), r['S'], replace=True, p=prob)
banks['M2-bulk'].append(lab(bulk_t[sub]))
for method, ys in banks.items():
a = np.stack(ys).astype(np.float32)
if not np.isfinite(a).all():
raise ValueError(f'Non-finite label bank {label}/{method}')
bundle[f'{label}/{method}'] = a
for method, vals in lps.items():
bundle[f'{label}/{method}/logpi'] = np.stack(vals).astype(np.float32)
bundle[f'{label}/lambda'] = np.asarray(effective_lambda(ref, p['metrics']['f_c_hz'], data.dt)[0])
from ml_porosity.eval.metrics import split_bands
bundle[f'{label}/lfm'] = split_bands(np.mean(ref, axis=0), p['metrics']['f_c_hz'], data.dt)[0]
for o, tg in zip(obs, post):
bundle[f'posterior/{o["name"]}/tau_at_main'] = invert_warps(tg, data.tau, data.t_main)
meta = {'training_wells': list(names), 'sigma_a_ms': sigma_a, 'no_anchors': no_anchors,
'phase0': phase0, 'phase_R': phase_r, 'phase_info': ph, 'hyper': h.as_dict(),
'hyper_info': hinfo, 'diagnostics': diag, 'wall_seconds': time.perf_counter() - started}
del Ts, Zs, T, T0
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return bundle, meta

336
ml_porosity/f3/runner.py Normal file
View File

@@ -0,0 +1,336 @@
"""Resumable P3 stages. Worker processes never write report.html or select checkpoints."""
from __future__ import annotations
import copy
import itertools
import json
import os
import subprocess
import sys
import time
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
from multiprocessing import get_context
from pathlib import Path
import numpy as np
from ml_porosity.f3.data import F3Data
from ml_porosity.f3.progress import update, write_json
from ml_porosity.f3.protocol import digest, fingerprint, freeze, training_sets
from ml_porosity.paths import REPO_ROOT, outputs_dir
def set_name(names) -> str:
return '__'.join(sorted(names))
def reg_path(root: Path, names, sigma_a: float = 7, no_anchors: bool = False) -> Path:
return root / 'registration' / f'{set_name(names)}_sa{sigma_a:g}{"_noanchors" if no_anchors else ""}.npz'
def job_path(root: Path, names, method: str, label: str, seed: int, sigma_a: float = 7) -> Path:
return root / 'train' / f'{set_name(names)}__{method}__{label}__s{seed}__sa{sigma_a:g}.npz'
def load_bundle(path: Path) -> dict:
with np.load(path) as z:
return {k: z[k] for k in z.files}
def reusable(path: Path, key: str) -> bool:
meta = path.with_suffix('.json')
if not path.exists() or not meta.exists():
return False
stored = json.loads(meta.read_text(encoding='utf-8'))
if stored.get('fingerprint') != key:
raise RuntimeError(f'Resume fingerprint mismatch: {path}. Use a new output directory.')
expected = stored.get('artifact_sha256')
if expected is None or digest(path) != expected:
raise RuntimeError(f'Missing or mismatched completed-artifact checksum: {path}')
if path.parent.name == 'train':
checkpoint = path.with_suffix('.pt')
if not checkpoint.exists() or digest(checkpoint) != stored.get('checkpoint_sha256'):
raise RuntimeError(f'Missing or mismatched model checkpoint: {checkpoint}')
with np.load(path) as z:
if not z.files:
raise RuntimeError(f'Empty completed artifact: {path}')
for k in z.files:
a = z[k]
if np.issubdtype(a.dtype, np.number):
valid = (not np.isnan(a).any() and not np.isposinf(a).any() and np.isfinite(a).any(axis=-1).all()) if k.endswith('/logpi') else np.isfinite(a).all()
if not valid:
raise RuntimeError(f'Corrupt/non-finite artifact: {path}/{k}')
return True
def registration_worker(job: dict) -> dict:
import torch
from ml_porosity.f3.registration import register_set
torch.set_num_threads(job['p']['runtime']['cpu_threads_per_worker'])
data = F3Data(job['p'], training_wells=tuple(job['names']))
path = reg_path(Path(job['root']), job['names'], job['sa'], job['no_anchors'])
if reusable(path, job['key']):
return {'cached': True, 'path': str(path)}
bundle, meta = register_set(data, tuple(job['names']), job['p'], job['device'], job['sa'], job['no_anchors'])
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix('.tmp.npz')
np.savez_compressed(tmp, **bundle)
tmp.replace(path)
write_json(path.with_suffix('.json'), meta | {'fingerprint': job['key'], 'artifact_sha256': digest(path)})
return {'cached': False, 'path': str(path), **meta}
def training_worker(job: dict) -> dict:
from ml_porosity.f3.training import method_spec, train_trajectory
root, p = Path(job['root']), job['p']
path = job_path(root, job['names'], job['method'], job['label'], job['seed'], job['sa'])
if reusable(path, job['key']):
return {'cached': True, 'path': str(path)}
data = F3Data(p, training_wells=tuple(job['names']))
bundle = load_bundle(reg_path(root, job['names'], job['sa'], job['method'] == 'M2-no-anchors'))
if tuple(bundle['wells']) != tuple(sorted(job['names'])):
raise RuntimeError('Training cache contains different wells')
all_names = list(p['data']['wells'])
Xall = np.stack([data.X(w) for w in all_names])
if job['method'] == 'M2-LFM':
m, s = bundle[f'{job["label"]}/norm']
lfm = (bundle[f'{job["label"]}/lfm'] - m) / s
Xall = np.concatenate([Xall, np.broadcast_to(lfm, (len(Xall), 1, len(lfm)))], axis=1)
X = Xall[[all_names.index(w) for w in job['names']]]
spec = method_spec(bundle, job['label'], job['method'], p)
path.parent.mkdir(parents=True, exist_ok=True)
ckpt = path.with_suffix('.pt')
pred, meta = train_trajectory(X, Xall, spec, job['method'], p['training'] | {'fixed_sigma': p['methods']['fixed_sigma']},
job['seed'], p['training']['budgets'], job['device'], ckpt)
mean, sd = bundle[f'{job["label"]}/norm']
for k in pred:
pred[k] = pred[k] * sd + (mean if k.endswith('/mu') else 0)
pred['wells'] = np.asarray(all_names)
pred['norm'] = bundle[f'{job["label"]}/norm']
tmp = path.with_suffix('.tmp.npz')
np.savez_compressed(tmp, **pred)
tmp.replace(path)
write_json(path.with_suffix('.json'), meta | {'fingerprint': job['key'], 'artifact_sha256': digest(path),
'checkpoint_sha256': digest(ckpt), 'training_wells': job['names'],
'label': job['label'], 'method': job['method'], 'seed': job['seed'], 'sigma_a_ms': job['sa']})
return {'cached': False, 'path': str(path), **meta}
def run_jobs(jobs: list[dict], fn, workers: int, stage: str) -> list[dict]:
started = time.perf_counter()
results = []
smoke = bool(jobs and Path(jobs[0]['root']).name == 'smoke')
task = 'p3-review' if smoke else 'p3-vol' if stage.startswith('volume-') else 'p3-lowo'
update(status=f'{"Smoke test — " if smoke else ""}Đang chạy {stage}', message='Mỗi job chỉ nhận đúng tập giếng train; smoke không phải kết quả chính.',
completed=0, total=len(jobs), eta_seconds=None, error=None, tasks={task: 'doing'})
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context('spawn')) as pool:
futures = {pool.submit(fn, job): job for job in jobs}
pending = set(futures)
while pending:
done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED)
if not done:
update(elapsed_seconds=time.perf_counter()-started,
message=f'{stage}: {len(results)}/{len(jobs)} job; scheduler đang chờ {min(workers, len(pending))} worker. Chưa có job mới hoàn tất.')
continue
for fut in done:
try:
result = fut.result()
except Exception as exc:
for future in pending:
future.cancel()
update(status='Job failed; pending jobs cancelled', error=str(exc),
message='Completed artifacts are preserved. Running workers finish before the scheduler exits.')
raise
results.append(result)
fresh = sum(not r.get('cached') for r in results)
elapsed = time.perf_counter() - started
remain = len(jobs) - len(results)
eta = elapsed/fresh*remain if fresh else None
update(completed=len(results), total=len(jobs), eta_seconds=eta, elapsed_seconds=elapsed,
message=f'{stage}: xong {len(results)}/{len(jobs)} job; cache {len(results)-fresh}. Các job được kiểm tra fingerprint khi chạy lại.')
print(f'{stage} {len(results)}/{len(jobs)} {result["path"]}', flush=True)
return results
def registration_jobs(p: dict, stamp: dict, root: Path, device: str, deployment: bool = False) -> list[dict]:
jobs = []
sets = training_sets(p['data']['wells'], 3 if deployment else 2)
for names in sets:
arms = [(p['registration']['sigma_a_ms'], False)]
if not deployment:
arms += [(s, False) for s in p['registration']['sigma_a_sensitivity_ms']]
if 'M2-no-anchors' in p['methods']['ablations']:
arms += [(p['registration']['sigma_a_ms'], True)]
for sa, no in arms:
settings = dict(names=list(names), sa=sa, no_anchors=no)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage='registration', **settings)))
return jobs
def training_jobs(p: dict, stamp: dict, root: Path, device: str) -> list[dict]:
jobs = []
for names in training_sets(p['data']['wells']):
arms = [(p['registration']['sigma_a_ms'], lab, m) for lab in p['data']['labels'] for m in p['methods']['main']]
arms += [(p['registration']['sigma_a_ms'], lab, m) for lab in p['methods']['ablation_labels'] for m in p['methods']['ablations']]
arms += [(sa, lab, m) for sa in p['registration']['sigma_a_sensitivity_ms']
for lab in p['registration']['sensitivity_labels'] for m in p['registration']['sensitivity_methods']]
for (sa, label, method), seed in itertools.product(arms, p['split']['seeds']):
settings = dict(names=list(names), method=method, label=label, seed=seed, sa=sa)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage='train', **settings)))
return jobs
def prepare() -> None:
update(status='Chuẩn bị dữ liệu', message='Dựng patch đúng vị trí giếng và nhãn chống alias; chưa huấn luyện.', tasks={'p3-env': 'doing'})
subprocess.run([sys.executable, str(REPO_ROOT / 'scripts/01_build_wells.py')], cwd=REPO_ROOT, check=True)
import torch
if not torch.cuda.is_available():
raise RuntimeError('CUDA is unavailable; CPU execution must be requested explicitly for tests.')
update(status='Dữ liệu và CUDA sẵn sàng', message=f'{torch.cuda.get_device_name(0)}; đã dựng f3_wells.npz.', tasks={'p3-env': 'done'})
def benchmark_worker(job: dict) -> dict:
from ml_porosity.f3.training import train_trajectory
rng = np.random.default_rng(job['seed'])
X = rng.normal(size=(2, 9, 126))
Y = rng.normal(size=(2, 64, 126))
if job['method'] == 'M2-S256':
Y = rng.normal(size=(2, 256, 126))
if job['method'] == 'B3b':
Y = Y[:, :1]
if job['method'] in ('B4c', 'B4d'):
spec = dict(kind='softdtw' if job['method'] == 'B4c' else 'dilate', Y=Y[:, 0], gamma=0.1, band=8)
if job['method'] == 'B4d':
spec['alpha'] = 0.5
else:
spec = dict(kind='bank', Y=Y, logpi=np.full(Y.shape[:2], -np.log(Y.shape[1])), lam=0.37)
train_trajectory(X, X, spec, job['method'], job['p']['training'], job['seed'], [10], job['device'])
measurement_start = time.time()
_, meta = train_trajectory(X, X, spec, job['method'], job['p']['training'], job['seed'],
[job['steps']], job['device'])
return meta | {'method': job['method'], 'measurement_start': measurement_start, 'measurement_end': time.time()}
def benchmark(p: dict, device: str, steps: int, worker_counts: list[int]) -> dict:
import torch
update(status='Đo tốc độ RTX 3060', message='Dùng dữ liệu giả cùng kích thước; không xem nhãn test F3.', tasks={'p3-bench': 'doing'})
previous_file = outputs_dir()/'p3/benchmark.json'
previous = json.loads(previous_file.read_text(encoding='utf-8')) if previous_file.exists() else {}
same = previous.get('torch') == torch.__version__ and previous.get('device') == device
trials = [t for t in previous.get('trials', []) if same and t.get('jobs')
and all(j['steps'] == steps for j in t['jobs']) and t['workers'] not in worker_counts]
for workers in worker_counts:
start = time.perf_counter()
jobs = [dict(p=p, device=device, steps=steps, method=m, seed=i) for i, m in
enumerate(['B3b', 'M2-Sa', 'B4c', 'B4d', 'B2', 'M2-S256', 'M2-TCN'] * 2)]
try:
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context('spawn')) as pool:
result = list(pool.map(benchmark_worker, jobs))
elapsed = time.perf_counter()-start
steady = max(j['measurement_end'] for j in result)-min(j['measurement_start'] for j in result)
trials.append({'workers': workers, 'wall_seconds': elapsed, 'steady_wall_seconds': steady, 'steps_total': len(jobs)*steps,
'throughput_steps_per_second': len(jobs)*steps/steady, 'jobs': result})
except Exception as exc:
trials.append({'workers': workers, 'error': str(exc)})
valid = [v for v in trials if 'error' not in v]
if not valid:
raise RuntimeError(f'All benchmark configurations failed: {trials}')
best = max(valid, key=lambda v: v['throughput_steps_per_second'])
planned = training_jobs(p, {}, Path('.'), device)
n_jobs = len(planned)
timing = {method: float(np.mean([j['seconds_per_step'] for j in best['jobs'] if j['method'] == method]))
for method in {j['method'] for j in best['jobs']}}
def category(method):
if method.endswith('-TCN'):
return 'M2-TCN'
if method in timing:
return method
if method.startswith('B3'):
return 'B3b'
return 'M2-Sa'
# Individual timings include contention. Calibrate their sum to measured wall time.
scheduling_factor = min(1.0, best['steady_wall_seconds']/sum(j['wall_seconds'] for j in best['jobs']))
nominal = sum(timing[category(j['method'])]*max(p['training']['budgets']) for j in planned)*scheduling_factor
out = {'device': device, 'gpu': torch.cuda.get_device_name(0) if device.startswith('cuda') else 'CPU',
'torch': torch.__version__, 'python': sys.version, 'trials': trials, 'recommended_workers': best['workers'],
'training_jobs': n_jobs, 'max_steps_per_job': max(p['training']['budgets']),
'training_seconds': nominal, 'training_range_seconds': [nominal*0.8, nominal*1.6],
'posterior_seconds': None, 'volume_seconds': None,
'note': 'Measured synthetic-input training benchmark. Registration and full-volume ETA require their own pilot; not included in training_seconds.'}
from ml_porosity.f3.volume import volume_benchmark
out['volume'] = volume_benchmark(p, device)
out['volume_seconds'] = out['volume']['inference_seconds']
write_json(outputs_dir()/'p3/benchmark.json', out)
update(status='Đã đo tốc độ huấn luyện', message=f'{n_jobs} trajectory; ước lượng train {nominal/3600:.1f} giờ, chưa gồm posterior và volume.',
benchmark=out, eta_seconds=None, tasks={'p3-bench': 'doing'})
return out
def benchmark_registration(p: dict, device: str) -> dict:
"""One training-only registration pilot, isolated from the scientific output tree."""
from ml_porosity.f3.protocol import CONFIG, source_hash
root = outputs_dir()/'p3/benchmark_registration'
names = training_sets(p['data']['wells'])[0]
stamp = {'protocol_sha256': digest(CONFIG, True), 'code_sha256': source_hash(), 'benchmark_only': True}
jobs = registration_jobs(p, stamp, root, device)
pilots = [jobs[0]]
no_anchor_jobs = [job for job in jobs if tuple(job['names']) == names and job['no_anchors']]
if no_anchor_jobs:
pilots.append(no_anchor_jobs[0])
update(status='Đo thời gian registration', message=f'Pilot chỉ dùng hai giếng train {names}; không huấn luyện hoặc xem nhãn test P3.')
timings = []
for job in pilots:
result = registration_worker(job)
if result.get('cached'):
result = json.loads(reg_path(root, names, job['sa'], job['no_anchors']).with_suffix('.json').read_text(encoding='utf-8'))
timings.append({'no_anchors': job['no_anchors'], 'seconds': result['wall_seconds']})
seconds = timings[0]['seconds']
# Four 3-well deployment sets cost roughly six 2-well sets; sharing one GPU limits parallel speedup.
pair_equivalents = len(registration_jobs(p, stamp, root, device)) + 6
no_anchor_count = sum(job['no_anchors'] for job in jobs)
anchor_equivalents = len(jobs)-no_anchor_count+6
workload = seconds*anchor_equivalents+timings[-1]['seconds']*no_anchor_count
out = {'training_wells': names, 'seconds_per_two_well_set': seconds, 'pair_equivalents': pair_equivalents,
'pilots': timings, 'range_seconds': [workload/2, workload*2],
'note': 'One real-data training pair measured with and without anchors. Range is an extrapolation, not a confidence interval; other sigma arms and shared-GPU scheduling can differ.'}
write_json(outputs_dir()/'p3/registration_benchmark.json', out)
benchfile = outputs_dir()/'p3/benchmark.json'
values = {'registration_benchmark': out}
if benchfile.exists():
bench = json.loads(benchfile.read_text(encoding='utf-8'))
train_range = bench['training_range_seconds']
vol_range = bench['volume']['range_seconds_with_io']
# Extra deployment training and scoring are allowed 15% of the measured training budget.
values['full_runtime_range_seconds'] = [train_range[i]*1.15+out['range_seconds'][i]+vol_range[i] for i in (0, 1)]
update(status='Đã đo và ước lượng P3', message='Đã có benchmark train, registration và volume. Chưa chạy lưới P3 chính.',
**values, tasks={'p3-bench': 'done'})
return out
def run(stage: str, p: dict, device: str, workers: int, smoke: bool = False) -> None:
stamp = freeze(check=True)
root = outputs_dir()/'p3'
if smoke:
p = copy.deepcopy(p)
p['split']['seeds'] = [0]
p['data']['labels'] = [p['data']['primary_label']]
p['methods']['main'] = ['B3b', 'B3d-Sa', 'M2-Sa']
p['methods']['ablations'] = []
p['registration'].update(particles=16, S=8, hyper_starts=1, smc_moves=1, phase_half_width=0, phase_max_extra=0,
sigma_a_sensitivity_ms=[])
p['training']['budgets'] = [2, 4]
root = root/'smoke'
stamp = stamp | {'smoke': p}
if stage == 'register':
run_jobs(registration_jobs(p, stamp, root, device), registration_worker, workers, stage)
elif stage == 'train':
run_jobs(training_jobs(p, stamp, root, device), training_worker, workers, stage)
elif stage in ('diagnostics', 'summarize'):
from ml_porosity.f3.evaluation import diagnostics, summarize
(diagnostics if stage == 'diagnostics' else summarize)(p, root)
else:
raise ValueError(stage)

152
ml_porosity/f3/training.py Normal file
View File

@@ -0,0 +1,152 @@
"""P3 trajectories: checkpoint all registered budgets without looking at target labels."""
from __future__ import annotations
import time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
from ml_porosity.losses.rml import bank_loss, gather_windows
from ml_porosity.losses.softdtw import dilate_loss_fast, softdtw_loss_fast
from ml_porosity.models.bank_train import window_starts_fixed
from ml_porosity.models.cnn_gru import CNNGRU
from ml_porosity.models.train import CNNGRUHetero, predict
class TCNHetero(nn.Module):
def __init__(self, channels: int, d: int, dropout: float):
super().__init__()
layers = []
for dilation in (1, 2, 4, 8):
layers.extend([nn.Conv1d(channels, d, 5, padding=2*dilation, dilation=dilation), nn.ReLU(), nn.Dropout(dropout)])
channels = d
self.net = nn.Sequential(*layers, nn.Conv1d(d, 2, 1))
def forward(self, x):
out = self.net(x)
return out[:, :1], torch.nn.functional.softplus(out[:, 1:]) + 1e-3
class FixedSigmaHetero(CNNGRUHetero):
def __init__(self, channels: int, d: int, dropout: float, fixed_sigma: float):
super().__init__(channels, d, dropout)
self.fixed_sigma = fixed_sigma
def forward(self, x):
mean, _ = super().forward(x)
return mean, torch.full_like(mean, self.fixed_sigma)
def make_model(method: str, channels: int, cfg: dict):
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
if method == 'M2-fixed-sigma':
return FixedSigmaHetero(channels, cfg['d_channels'], cfg['p_dropout'], cfg.get('fixed_sigma', 1.0))
cls = TCNHetero if method.endswith('-TCN') else CNNGRU if method == 'B2' else CNNGRUHetero
return cls(channels, cfg['d_channels'], cfg['p_dropout'])
def method_spec(bundle: dict, label: str, method: str, p: dict) -> dict:
m0, s0 = bundle[f'{label}/norm']
lam = float(bundle[f'{label}/lambda'])
base = method
if base in ('M2-anchor-only',):
base = 'M1'
elif base.startswith('M2-') and base not in ('M2-S256', 'M2-bulk'):
base = 'M2-Sa'
elif base == 'B3d-Sa-TCN':
base = 'B3d-Sa'
if method in ('B4a', 'B4b'):
Y = bundle[f'{label}/B4']
lp = np.full(Y.shape[:2], -np.log(Y.shape[1]))
return dict(kind='bank', Y=(Y-m0)/s0, logpi=lp, lam=None if method == 'B4a' else lam)
if method in ('B4c', 'B4d'):
return dict(kind='softdtw' if method == 'B4c' else 'dilate', Y=(bundle[f'{label}/B3b'][:, 0]-m0)/s0,
**p['training']['softdtw' if method == 'B4c' else 'dilate'])
Y = bundle[f'{label}/{base}']
if method in ('M2-S1', 'M2-S8'):
Y = Y[:, :int(method[4:])]
lp = bundle.get(f'{label}/{base}/logpi', np.full(Y.shape[:2], -np.log(Y.shape[1])))
if lp.shape != Y.shape[:2]:
lp = np.full(Y.shape[:2], -np.log(Y.shape[1]))
return dict(kind='legacy' if method == 'B2' else 'bank', Y=(Y-m0)/s0, logpi=lp,
lam=1.0 if method == 'M2-lambda1' else lam)
def ensemble(means: np.ndarray, sigmas: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]:
means = np.asarray(means, float)
within = 0.0 if sigmas is None else np.mean(np.asarray(sigmas, float)**2, axis=0)
return means.mean(axis=0), np.sqrt(np.maximum(within + means.var(axis=0), 0))
def train_trajectory(X, X_targets, spec: dict, method: str, cfg: dict, seed: int, budgets: list[int],
device: str, checkpoint: Path | None = None) -> tuple[dict, dict]:
torch.set_num_threads(2)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.default_generator.manual_seed(seed)
if torch.device(device).type == 'cuda':
torch.cuda.set_device(device)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
tensor = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
x, y = tensor(X), tensor(spec['Y'])
N, _, L = X.shape
starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device)
logpi = tensor(spec.get('logpi', np.zeros(y.shape[:2])))
model = make_model(method, X.shape[1], cfg).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg['lr'])
legacy = LegacyV2Loss()
outputs, states = {}, {}
if torch.device(device).type == 'cuda':
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
begin = time.perf_counter()
for step in range(1, max(budgets)+1):
model.train()
opt.zero_grad(set_to_none=True)
if method == 'B2':
mu = model(x)
if step <= 50:
mu = mu + 0.01 * torch.randn_like(mu)
loss = legacy(mu, y[:, 0, None])
else:
mu, sigma = model(x)
if method == 'M2-fixed-sigma':
sigma = torch.full_like(sigma, cfg.get('fixed_sigma', 1.0))
if spec['kind'] == 'bank':
loss = bank_loss(mu[:, 0], sigma[:, 0], y, logpi, starts, 64, spec['lam'])
else:
f = softdtw_loss_fast if spec['kind'] == 'softdtw' else dilate_loss_fast
kw = {k: spec[k] for k in ('gamma', 'band', 'alpha') if k in spec}
loss = f(gather_windows(mu[:, 0], starts, 64).reshape(-1, 64),
gather_windows(sigma[:, 0], starts, 64).reshape(-1, 64),
gather_windows(y, starts, 64).reshape(-1, 64), **kw)
if method == 'M2-legacy-loss':
loss = loss + legacy(mu, y.mean(axis=1)[:, None])
if not torch.isfinite(loss):
raise FloatingPointError(f'Non-finite loss in {method}, step {step}')
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg['grad_clip'])
opt.step()
if step in budgets:
m, s = predict(model, X_targets, device)
if method == 'M2-fixed-sigma':
s = np.full_like(m, cfg.get('fixed_sigma', 1.0))
outputs[f'{step}/mu'] = m
outputs[f'{step}/sigma'] = np.zeros_like(m) if s is None else s
if checkpoint is not None:
states[step] = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
if torch.device(device).type == 'cuda':
torch.cuda.synchronize()
elapsed = time.perf_counter() - begin
if checkpoint is not None:
tmp = checkpoint.with_suffix('.pt.tmp')
torch.save({'states': states, 'method': method, 'channels': X.shape[1], 'config': cfg}, tmp)
tmp.replace(checkpoint)
return outputs, {'wall_seconds': elapsed, 'steps': max(budgets), 'seconds_per_step': elapsed/max(budgets),
'parameters': sum(v.numel() for v in model.parameters()),
'peak_vram_bytes': torch.cuda.max_memory_allocated() if torch.device(device).type == 'cuda' else 0}

237
ml_porosity/f3/volume.py Normal file
View File

@@ -0,0 +1,237 @@
"""Descriptive F3 volume from a frozen 20-member deployment ensemble, streamed by inline."""
from __future__ import annotations
import json
import time
from pathlib import Path
import numpy as np
from ml_porosity.f3.progress import update, write_json
from ml_porosity.f3.protocol import digest, fingerprint, freeze, training_sets
from ml_porosity.f3.runner import job_path, load_bundle, registration_jobs, registration_worker, reusable, run_jobs, training_worker
from ml_porosity.paths import outputs_dir
def deployment_budget(values, candidates) -> int:
median = float(np.median(values))
return min(candidates, key=lambda x: (abs(x-median), x))
def fit_deployment(p: dict, device: str, workers: int) -> dict:
import pandas as pd
root, stamp = outputs_dir()/'p3', freeze(check=True)
selection = pd.read_csv(root/'summary/selection.csv')
cfg = p['volume']
method, label = cfg['method'], cfg['label']
run_jobs(registration_jobs(p, stamp, root, device, deployment=True), registration_worker, workers, 'volume-register')
jobs, members = [], []
for names in training_sets(p['data']['wells'], 3):
for seed in p['split']['seeds']:
scores = selection[(selection.method == method) & (selection.label == label) & (selection.seed == seed)
& (selection.sigma_a_ms == p['registration']['sigma_a_ms'])]
if len(scores) != 4:
raise RuntimeError('Need all four outer selections before deployment fitting')
budget = deployment_budget(scores.budget.to_numpy(), p['training']['budgets'])
import copy
q = copy.deepcopy(p)
q['training']['budgets'] = [budget]
settings = dict(names=list(names), method=method, label=label, seed=seed, sa=p['registration']['sigma_a_ms'])
jobs.append(dict(p=q, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage='deployment-train', budget=budget, **settings)))
path = job_path(root, names, method, label, seed, p['registration']['sigma_a_ms'])
members.append({'checkpoint': str(path.with_suffix('.pt').relative_to(root)), 'prediction': str(path.relative_to(root)),
'budget': budget, 'training_wells': names, 'seed': seed})
run_jobs(jobs, training_worker, workers, 'volume-fit')
meta = {'members': members, 'method': method, 'label': label, 'protocol_sha256': stamp['protocol_sha256'],
'note': '20-member ensemble for descriptive volume only; LOWO scores use separate 15-member blind ensembles.'}
write_json(root/'deployment.json', meta)
return meta
def load_models(p: dict, device: str):
import torch
from ml_porosity.f3.training import make_model
root = outputs_dir()/'p3'
stamp = freeze(check=True)
meta = json.loads((root/'deployment.json').read_text(encoding='utf-8'))
if len(meta['members']) != 4*len(p['split']['seeds']) or meta['protocol_sha256'] != stamp['protocol_sha256']:
raise RuntimeError('Incomplete or mismatched deployment ensemble')
models = []
for item in meta['members']:
key = fingerprint(stamp, stage='deployment-train', budget=item['budget'], names=list(item['training_wells']),
method=meta['method'], label=meta['label'], seed=item['seed'], sa=p['registration']['sigma_a_ms'])
if not reusable(root/item['prediction'], key):
raise RuntimeError('Deployment prediction/checkpoint pair is incomplete')
saved = torch.load(root/item['checkpoint'], map_location='cpu', weights_only=True)
model = make_model(saved['method'], saved['channels'], saved['config'])
model.load_state_dict(saved['states'][item['budget']])
model.to(device).eval()
norm = load_bundle(root/item['prediction'])['norm']
models.append((model, float(norm[0]), float(norm[1])))
return models
def predict_batch(models, patches: np.ndarray, device: str) -> tuple[np.ndarray, np.ndarray]:
import torch
x = torch.as_tensor(patches, dtype=torch.float32, device=device)
running_mean, m2, sum_aleatoric = None, None, None
with torch.inference_mode():
for n, (model, mean, sd) in enumerate(models, 1):
mu, sigma = model(x)
mu, sigma = mu[:, 0]*sd+mean, sigma[:, 0]*sd
if running_mean is None:
running_mean, m2, sum_aleatoric = mu.clone(), torch.zeros_like(mu), sigma**2
else:
delta = mu-running_mean
running_mean = running_mean+delta/n
m2 = m2+delta*(mu-running_mean)
sum_aleatoric = sum_aleatoric+sigma**2
std = torch.sqrt(torch.clamp((sum_aleatoric+m2)/len(models), min=0))
return running_mean.cpu().numpy(), std.cpu().numpy()
def volume_benchmark(p: dict, device: str, batches: int = 4) -> dict:
"""Architecture-only pilot; no production checkpoint or F3 labels are required."""
import torch
from ml_porosity.f3.training import make_model
n = 4*len(p['split']['seeds'])
models = [(make_model(p['volume']['method'], 9, p['training']).to(device).eval(), 0.25, 0.03) for _ in range(n)]
rng = np.random.default_rng(73)
x = rng.normal(size=(p['volume']['batch_size'], 9, 126)).astype(np.float32)
predict_batch(models, x, device)
if device.startswith('cuda'):
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(batches):
predict_batch(models, x, device)
if device.startswith('cuda'):
torch.cuda.synchronize()
elapsed = time.perf_counter()-start
from ml_porosity.data.seismic_io import SeismicCube
with SeismicCube() as cube:
traces = (len(cube.ilines)-2)*(len(cube.xlines)-2)
estimate = traces/(batches*len(x)/elapsed)
del models
if device.startswith('cuda'):
torch.cuda.empty_cache()
return {'members': n, 'batch_size': len(x), 'measured_batches': batches, 'seconds': elapsed,
'traces_per_second': batches*len(x)/elapsed, 'full_interior_traces': traces,
'inference_seconds': estimate, 'range_seconds_with_io': [estimate*1.1, estimate*1.8],
'note': 'Measured with 20 random-weight models of the deployment architecture; range adds SEG-Y reading, normalization and disk writing. Not a production prediction.'}
def predict_volume(p: dict, device: str, sections: bool = False, limit_inlines: int | None = None) -> dict:
from ml_porosity.data.seismic_io import SeismicCube
from ml_porosity.f3.data import F3Data
stamp = freeze(check=True)
from ml_porosity.paths import f3_segy
if digest(f3_segy()) != stamp['segy_sha256']:
raise RuntimeError('F3 cube changed after protocol locking; refusing volume prediction')
root = outputs_dir()/'p3'
models = load_models(p, device)
data = F3Data(p)
dest = root/('volume_sections' if sections else 'volume_pilot' if limit_inlines else 'volume')
dest.mkdir(parents=True, exist_ok=True)
state_file = dest/'state.json'
key = fingerprint(stamp, stage='volume', deployment=json.loads((root/'deployment.json').read_text(encoding='utf-8')),
sections=sections, limit_inlines=limit_inlines)
state = json.loads(state_file.read_text(encoding='utf-8')) if state_file.exists() else {'fingerprint': key, 'completed_ilines': []}
if state['fingerprint'] != key:
raise RuntimeError('Volume resume fingerprint mismatch')
if state['completed_ilines'] and any(not (dest/n).exists() for n in ('mean.npy', 'sigma.npy')):
raise RuntimeError('Volume state lists completed rows but an output file is missing; refusing to skip missing predictions')
start = time.perf_counter()
with SeismicCube() as cube:
time_mask = cube.window(*p['data']['window_ms'])
times = cube.times_ms[time_mask]
if not np.array_equal(times, data.t_main):
raise ValueError('Cube and training time axes differ')
shape = (len(cube.ilines), len(cube.xlines), len(times))
outputs = []
for name in ('mean.npy', 'sigma.npy'):
path = dest/name
new = not path.exists()
arr = np.lib.format.open_memmap(path, mode='w+' if new else 'r+', dtype='float32', shape=shape)
if new:
arr[:] = np.nan
arr.flush()
elif arr.shape != shape:
raise ValueError('Existing volume shape differs')
outputs.append(arr)
selected_i = {int(data.ext(w, 'il')) for w in data.wells}
selected_j = {int(np.flatnonzero(cube.xlines == int(data.ext(w, 'xl')))[0]) for w in data.wells}
line_cache = {}
def line(i):
if i not in line_cache:
il = int(cube.ilines[i])
a = np.asarray(cube._f.iline[il], dtype=np.float32)[:, time_mask]
line_cache[i] = a
return line_cache[i]
total = len(cube.ilines)-2
if limit_inlines:
total = min(total, limit_inlines)
completed_now = 0
for i in range(1, total+1):
if i in state['completed_ilines']:
continue
il = int(cube.ilines[i])
columns = np.arange(1, len(cube.xlines)-1)
if sections and il not in selected_i:
columns = np.array(sorted(j for j in selected_j if 0 < j < len(cube.xlines)-1))
block = np.stack([line(i-1), line(i), line(i+1)])
view = np.lib.stride_tricks.sliding_window_view(block, 3, axis=1).transpose(1, 0, 3, 2)
for j0 in range(0, len(columns), p['volume']['batch_size']):
cols = columns[j0:j0+p['volume']['batch_size']]
x = np.ascontiguousarray(view[cols-1].reshape(len(cols), 9, len(times)), dtype=np.float64)
x = (x-x.mean(axis=2, keepdims=True))/(x.std(axis=2, keepdims=True)+1e-8)
mu, sigma = predict_batch(models, x, device)
outputs[0][i, cols] = mu
outputs[1][i, cols] = sigma
for arr in outputs:
arr.flush()
state['completed_ilines'].append(i)
write_json(state_file, state)
completed_now += 1
elapsed = time.perf_counter()-start
update(status='Đang suy luận volume', message=f'Đã ghi inline {il}; phần biên không có đủ patch được giữ NaN.',
completed=len(state['completed_ilines']), total=total,
eta_seconds=elapsed/completed_now*(total-len(state['completed_ilines'])), tasks={'p3-vol': 'doing'})
for old in list(line_cache):
if old < i:
del line_cache[old]
meta = {'shape': shape, 'ilines': cube.ilines.tolist(), 'xlines': cube.xlines.tolist(), 'times_ms': times.tolist(),
'members': len(models), 'units': 'porosity fraction', 'sections_only': sections, 'pilot': bool(limit_inlines),
'wall_seconds': time.perf_counter()-start, 'edge_policy': p['volume']['edge'],
'interpretation': p['volume']['interpretation'], 'fingerprint': key}
write_json(dest/'metadata.json', meta)
plot_sections(outputs[0], outputs[1], data, cube.ilines, cube.xlines, times, dest)
update(status='Volume đã hoàn tất' if not limit_inlines else 'Pilot volume đã hoàn tất',
message='Đầu ra sonic-derived porosity và σ; không dùng volume để chấm G-C.', completed=None, total=None,
eta_seconds=None, tasks={'p3-vol': 'todo' if limit_inlines else 'done'})
return meta
def plot_sections(mean, sigma, data, ilines, xlines, times, dest):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
limits = [(float(np.nanmin(mean))*100, float(np.nanmax(mean))*100), (0., float(np.nanmax(sigma))*100)]
for w in data.wells:
i = int(np.flatnonzero(ilines == int(data.ext(w, 'il')))[0])
j = int(np.flatnonzero(xlines == int(data.ext(w, 'xl')))[0])
for name, a, b, axis in (('inline', mean[i], sigma[i], xlines), ('crossline', mean[:, j], sigma[:, j], ilines)):
if not np.isfinite(a).any():
continue
fig, axs = plt.subplots(1, 2, figsize=(12, 5), sharey=True, layout='constrained')
for ax, values, title, clim, cmap_name in zip(axs, (a, b), ('Mean (p.u.)', 'Predictive sigma (p.u.)'), limits, ('viridis', 'magma')):
cmap = matplotlib.colormaps[cmap_name].with_extremes(bad='#bdbdbd')
dt = float(times[1]-times[0])
img = ax.imshow(100*values.T, origin='upper', aspect='auto', interpolation='nearest', cmap=cmap,
vmin=clim[0], vmax=clim[1], extent=[axis[0]-.5, axis[-1]+.5, times[-1]+dt/2, times[0]-dt/2])
ax.set(title=title, xlabel=name)
fig.colorbar(img, ax=ax)
axs[0].set_ylabel('TWT (ms)')
fig.suptitle(f'{w} — descriptive sonic-derived porosity; gray = unavailable')
fig.savefig(dest/f'{w}_{name}.png', dpi=140)
plt.close(fig)

View File

@@ -1,4 +1,4 @@
"""Losses from the thesis (`test 2/train_open_patch_v2.py`), ported verbatim to build baseline B0. """Losses from the thesis (`code_thesis/train_open_patch_v2.py`), ported verbatim to build baseline B0.
Note (plan §1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L, so there are only 5 independent constraints. Note (plan §1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L, so there are only 5 independent constraints.
""" """

View File

@@ -1,6 +1,6 @@
"""Dilated CNN + 2-layer bidirectional GRU + 1×1 skip head. """Dilated CNN + 2-layer bidirectional GRU + 1×1 skip head.
Ported verbatim from `test 2/train_open_patch_v2.py` (class CNNGRU); the architecture is unchanged. Ported verbatim from `code_thesis/train_open_patch_v2.py` (class CNNGRU); the architecture is unchanged.
""" """
from __future__ import annotations from __future__ import annotations

View File

@@ -35,7 +35,7 @@ from scipy.linalg import solve_triangular
from ml_porosity.data.wavelet import rotate_phase from ml_porosity.data.wavelet import rotate_phase
from ml_porosity.registration.sampler import ess from ml_porosity.registration.sampler import ess
from ml_porosity.registration.tie_likelihood import fine_wavelet, forward_fine, profile_loglik 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 from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, interp_matrix, laplace_posterior, prior_moments
def residual_kappa(syn: np.ndarray, seis: np.ndarray, max_lag: int = 16) -> float: def residual_kappa(syn: np.ndarray, seis: np.ndarray, max_lag: int = 16) -> float:
@@ -61,12 +61,16 @@ class TiePosterior:
def __init__(self, grid: WarpGrid, h: WarpHyper, tau_k, t_k, g_max: float, tau_fine: np.ndarray, 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, 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): t_cover: tuple[float, float] | None = None, allow_no_anchors: bool = False):
tau_k = np.asarray(tau_k, dtype=float) tau_k = np.asarray(tau_k, dtype=float)
if tau_k.size == 0: if tau_k.size == 0 and not allow_no_anchors:
raise ValueError("anchors required") raise ValueError("anchors required")
self.d_k = np.asarray(t_k, dtype=float) - tau_k 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) if tau_k.size:
self.mu, cov, self.A, self.off = laplace_posterior(grid, h, tau_k, self.d_k)
else:
self.mu, cov = prior_moments(grid, h)
self.A, self.off = np.zeros((0, grid.n+1)), np.zeros(0)
jit = 1e-9 * max(np.trace(cov) / len(self.mu), 1e-12) # as in sampler.elliptical_slice 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.Lc = np.linalg.cholesky(cov + jit * np.eye(len(self.mu)))
self.P = interp_matrix(tau_k, grid.tau) @ grid.Q self.P = interp_matrix(tau_k, grid.tau) @ grid.Q

View File

@@ -18,13 +18,11 @@ from __future__ import annotations
import argparse import argparse
import csv import csv
import datetime as dt import datetime as dt
import fcntl
import hashlib import hashlib
import json import json
import os import os
import platform import platform
import re import re
import resource
import shlex import shlex
import signal import signal
import socket import socket
@@ -34,6 +32,12 @@ import threading
import time import time
from pathlib import Path from pathlib import Path
try:
import fcntl
import resource
except ImportError: # Native Windows: neither module exists.
fcntl = resource = None
from .paths import REPO_ROOT from .paths import REPO_ROOT
FIELDS = ["run_id", "parent", "name", "status", "exit_code", "start", "end", "wall_s", "wall", FIELDS = ["run_id", "parent", "name", "status", "exit_code", "start", "end", "wall_s", "wall",
@@ -96,6 +100,13 @@ def gpu_state() -> list[dict]:
def _group_pids(pgid: int) -> set[int]: def _group_pids(pgid: int) -> set[int]:
if os.name == 'nt':
import psutil
try:
parent = psutil.Process(pgid)
return {pgid, *(p.pid for p in parent.children(recursive=True))}
except (psutil.NoSuchProcess, psutil.AccessDenied):
return set()
pids = set() pids = set()
for d in Path("/proc").iterdir(): for d in Path("/proc").iterdir():
if d.name.isdigit(): if d.name.isdigit():
@@ -112,7 +123,7 @@ class GpuSampler(threading.Thread):
def __init__(self, pgid: int): def __init__(self, pgid: int):
super().__init__(daemon=True) super().__init__(daemon=True)
self.pgid, self.peak, self.stop = pgid, 0, threading.Event() self.pgid, self.peak, self.stop = pgid, None, threading.Event()
def run(self) -> None: def run(self) -> None:
wait = 2.0 # early first sample so that short jobs still get a reading wait = 2.0 # early first sample so that short jobs still get a reading
@@ -123,13 +134,16 @@ class GpuSampler(threading.Thread):
continue continue
pids = _group_pids(self.pgid) pids = _group_pids(self.pgid)
tot = 0 tot = 0
measured = False
for r in rows.splitlines(): for r in rows.splitlines():
try: try:
pid, mem = (int(x) for x in r.split(",")) pid, mem = (int(x) for x in r.split(","))
except ValueError: except ValueError:
continue continue
measured = True
tot += mem if pid in pids else 0 tot += mem if pid in pids else 0
self.peak = max(self.peak, tot) if measured:
self.peak = max(self.peak or 0, tot)
def default_name(cmd: list[str]) -> str: def default_name(cmd: list[str]) -> str:
@@ -153,22 +167,41 @@ def device_of(cmd: list[str]) -> str:
def write_json(path: Path, obj: dict) -> None: def write_json(path: Path, obj: dict) -> None:
tmp = path.with_suffix(".tmp") tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str)) tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str), encoding='utf-8')
tmp.replace(path) tmp.replace(path)
def append_index(row: dict, root: Path | None = None) -> None: def append_index(row: dict, root: Path | None = None) -> None:
root = root or logs_dir() root = root or logs_dir()
root.mkdir(parents=True, exist_ok=True) root.mkdir(parents=True, exist_ok=True)
with open(root / "index.csv", "a+", newline="") as f: with open(root / "index.csv", "a+", newline="", encoding='utf-8') as f:
fcntl.flock(f, fcntl.LOCK_EX) # several concurrent runs may write to the index lock = None
f.seek(0) if fcntl is not None:
new = not f.read(1) fcntl.flock(f, fcntl.LOCK_EX)
w = csv.DictWriter(f, FIELDS, extrasaction="ignore") else:
if new: import msvcrt
w.writeheader() lock = open(root / '.index.lock', 'a+b')
w.writerow(row) lock.seek(0, 2)
fcntl.flock(f, fcntl.LOCK_UN) if lock.tell() == 0:
lock.write(b'0')
lock.flush()
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
try:
f.seek(0)
new = not f.read(1)
w = csv.DictWriter(f, FIELDS, extrasaction="ignore", lineterminator='\n')
if new:
w.writeheader()
w.writerow(row)
f.flush()
finally:
if fcntl is not None:
fcntl.flock(f, fcntl.LOCK_UN)
elif lock is not None:
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
lock.close()
def index_row(meta: dict) -> dict: def index_row(meta: dict) -> dict:
@@ -248,9 +281,10 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
tee = Tee(rdir / "log.txt", t0, stamp) tee = Tee(rdir / "log.txt", t0, stamp)
tee.note(f"{run_id} {meta['start']} {meta['cmd']}") tee.note(f"{run_id} {meta['start']} {meta['cmd']}")
env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1"} env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1", "PYTHONUTF8": "1"}
try: try:
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, process_group=0) group = {'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == 'nt' else {'process_group': 0}
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, **group)
except OSError as e: except OSError as e:
tee.note(f"failed to launch: {e}") tee.note(f"failed to launch: {e}")
child = None child = None
@@ -260,11 +294,16 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
got.append(signal.Signals(sig).name) got.append(signal.Signals(sig).name)
if child is not None: if child is not None:
try: try:
os.killpg(child.pid, sig) if os.name == 'nt':
child.send_signal(signal.CTRL_BREAK_EVENT) if sig in (signal.SIGINT, signal.SIGBREAK) else child.terminate()
else:
os.killpg(child.pid, sig)
except OSError: except OSError:
pass pass
for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signals = [signal.SIGINT, signal.SIGTERM]
signals += [getattr(signal, name) for name in ('SIGHUP', 'SIGBREAK') if hasattr(signal, name)]
for s in signals:
signal.signal(s, forward) signal.signal(s, forward)
sampler = None sampler = None
if child is not None: if child is not None:
@@ -283,12 +322,12 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
sampler.stop.set() sampler.stop.set()
else: else:
code = 127 code = 127
ru = resource.getrusage(resource.RUSAGE_CHILDREN) ru = resource.getrusage(resource.RUSAGE_CHILDREN) if resource is not None else None
wall = time.time() - t0 wall = time.time() - t0
status = "ok" if code == 0 else ("interrupted" if got or code < 0 else "failed") 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"), 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), "wall_s": round(wall, 2), "wall": fmt_wall(wall), "cpu_user_s": round(ru.ru_utime, 1) if ru else None,
"cpu_sys_s": round(ru.ru_stime, 1), "max_rss_mib": round(ru.ru_maxrss / 1024), "cpu_sys_s": round(ru.ru_stime, 1) if ru else None, "max_rss_mib": round(ru.ru_maxrss / 1024) if ru else None,
"gpu_peak_mib": sampler.peak if sampler else None, "gpu_end": gpu_state()} "gpu_peak_mib": sampler.peak if sampler else None, "gpu_end": gpu_state()}
write_json(rdir / "meta.json", meta) write_json(rdir / "meta.json", meta)
tee.note(f"{status} exit {code} wall {fmt_wall(wall)} ({wall:.1f} s)") tee.note(f"{status} exit {code} wall {fmt_wall(wall)} ({wall:.1f} s)")
@@ -298,7 +337,7 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
def all_metas(root: Path) -> list[dict]: 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")]] metas = [json.loads(m.read_text(encoding='utf-8')) 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"])) return sorted(metas, key=lambda m: (m.get("start") or m.get("end") or "", m["run_id"]))
@@ -313,12 +352,16 @@ def reindex() -> None:
def ls(k: int) -> None: def ls(k: int) -> None:
root = logs_dir() root = logs_dir()
rows = list(csv.DictReader(open(root / "index.csv"))) if (root / "index.csv").exists() else [] rows = list(csv.DictReader(open(root / "index.csv", encoding='utf-8'))) if (root / "index.csv").exists() else []
done = {r["run_id"] for r in rows} done = {r["run_id"] for r in rows}
for meta in all_metas(root): for meta in all_metas(root):
if meta["run_id"] in done or meta.get("status") != "running": if meta["run_id"] in done or meta.get("status") != "running":
continue continue
alive = Path(f"/proc/{meta.get('launcher_pid')}").exists() if os.name == 'nt':
import psutil
alive = psutil.pid_exists(meta.get('launcher_pid', -1))
else:
alive = Path(f"/proc/{meta.get('launcher_pid')}").exists()
meta["status"] = "running" if alive else "lost" # launcher killed with -9 / machine rebooted meta["status"] = "running" if alive else "lost" # launcher killed with -9 / machine rebooted
start = dt.datetime.fromisoformat(meta["start"]) start = dt.datetime.fromisoformat(meta["start"])
meta["wall_s"] = (now() - start).total_seconds() if alive else None meta["wall_s"] = (now() - start).total_seconds() if alive else None

View File

@@ -0,0 +1 @@
"""P4: blind-well Volve experiments with partial labels, separate from the frozen P3 (F3) modules."""

144
ml_porosity/volve/data.py Normal file
View File

@@ -0,0 +1,144 @@
"""P4 data views (plan §5.2): private arrays of the training wells, seismic-only blind inputs of every other well.
A restricted view (training_wells given) keeps, for a well outside the training set, only
times_ms, main_mask, kb_msl, survey/* the well path, known without its logs or picks
blind/<K>/{seismic_patch, md, il, xl, beyond} only for K ⊇ training_wells, well ∉ K
so its logs, picks, TDRs, reference path and the label-centred bin (il, xl, x, y: placed at the middle of the
label interval) are never loaded. Labels, the reference input and registration observations of such a well
raise RuntimeError. The full view (training_wells None) is for scoring only.
"""
from __future__ import annotations
import numpy as np
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import TDR
from ml_porosity.models.bank_train import zscore_patch
from ml_porosity.paths import outputs_dir
from ml_porosity.registration.warp_prior import WarpGrid
PUBLIC = frozenset({"times_ms", "main_mask", "kb_msl"})
PUBLIC_PREFIXES = ("survey/",)
def npz_path():
return outputs_dir() / "volve" / "volve_wells.npz"
def load_arrays(path=None) -> dict[str, np.ndarray]:
with np.load(npz_path() if path is None else path) as z:
return {k: z[k] for k in z.files}
def blind_members(key: str) -> frozenset[str]:
return frozenset(key.split("+"))
def visible(key: str, training_wells: frozenset[str] | None) -> bool:
"""Whether the flat npz key "<well>/<item>" belongs to a view on `training_wells`."""
well, item = key.split("/", 1)
if training_wells is None or well in training_wells:
return True
if item in PUBLIC or item.startswith(PUBLIC_PREFIXES):
return True
if item.startswith("blind/"):
members = blind_members(item.split("/")[1])
return well not in members and training_wells <= members
return False
class VolveData:
def __init__(self, protocol: dict, training_wells: tuple[str, ...] | None = None,
arrays: dict[str, np.ndarray] | None = None):
self.protocol = protocol
self.wells = list(protocol["data"]["wells"])
self.label = protocol["data"]["label"]
self.training_wells = None if training_wells is None else frozenset(training_wells)
if self.training_wells is not None and not self.training_wells <= set(self.wells):
raise ValueError("Unknown training well")
source = load_arrays() if arrays is None else arrays
self.arrays = {k: v for k, v in source.items()
if k.split("/", 1)[0] in self.wells and visible(k, self.training_wells)}
self.t = self.ext(self.wells[0], "times_ms")
self.main = self.ext(self.wells[0], "main_mask").astype(bool)
self.t_main = self.t[self.main]
self.dt = float(np.diff(self.t)[0])
for w in self.wells:
if not (np.array_equal(self.ext(w, "times_ms"), self.t)
and np.array_equal(self.ext(w, "main_mask").astype(bool), self.main)):
raise ValueError(f"Volve time axes differ: {w}")
r = protocol["registration"]
f = r["fine_dt_ms"]
self.grid = WarpGrid(*r["tau_range_ms"], r["warp_dtau_ms"])
self.tau = np.arange(r["tau_range_ms"][0], r["tau_range_ms"][1] + f / 2, f)
self.t_fine = np.arange(self.t[0] - 300, self.t[-1] + 300 + f / 2, f)
def is_training(self, well: str) -> bool:
return self.training_wells is None or well in self.training_wells
def ext(self, well: str, key: str) -> np.ndarray:
try:
return self.arrays[f"{well}/{key}"]
except KeyError:
raise KeyError(f"{well}/{key} is not in this data view") from None
def blind_keys(self, well: str) -> list[str]:
head = f"{well}/blind/"
return sorted({k[len(head):].split("/")[0] for k in self.arrays if k.startswith(head)})
def patch(self, well: str, key: str) -> np.ndarray:
"""(C, n_ext) seismic patch: key 'reference' (calibrated path, training wells only) or a blind key."""
if key == "reference":
if not self.is_training(well):
raise RuntimeError("The reference path of a held-out well uses its own picks and DT")
return self.ext(well, "reference/seismic_patch")
if well in blind_members(key):
raise RuntimeError(f"Blind key {key!r} contains its own well {well!r}")
return self.ext(well, f"blind/{key}/seismic_patch")
def X(self, well: str, key: str) -> np.ndarray:
"""Network input (C, L) on the main window."""
return zscore_patch(self.patch(well, key), self.main)
def y(self, well: str, reference: str, label: str | None = None) -> np.ndarray:
"""Label on the main window under TDR `reference`; NaN outside its support."""
if not self.is_training(well):
raise RuntimeError("Held-out labels are unavailable in a training data view")
return self.ext(well, f"{reference}/{label or self.label}")[self.main]
def training_observations(self, names: tuple[str, ...]) -> list[dict]:
"""Registration inputs of training wells on the sonic time axis τ (vertical sonic through the first anchor
in the DT range). Anchors: in the DT range and inside the ext window. `lik`: ext samples from the first to
the last finite calibrated AI sample (the tie likelihood is evaluated there only)."""
if self.training_wells is not None and not set(names) <= self.training_wells:
raise RuntimeError("Held-out logs and anchors are unavailable in a training data view")
r = self.protocol["registration"]
obs = []
for name in names:
sonic = TDR(self.ext(name, "tdr/sonic/md"), self.ext(name, "tdr/sonic/twt_ms"), "sonic")
md = self.ext(name, "log/md")
amd, att = self.ext(name, "anchors_md"), self.ext(name, "anchors_twt_ms")
keep = self.ext(name, "anchors_in_dt").astype(bool) & (att >= self.t[0]) & (att <= self.t[-1])
if keep.sum() < 1:
raise ValueError(f"No anchor in the DT range: {name}")
resampled, valid = {}, {}
for curve in ("AI", self.label):
v = log_to_time(md, self.ext(name, f"log/{curve}"), sonic, self.tau,
fine_dt_ms=r["log_fine_dt_ms"], cutoff_frac=r["log_cutoff_frac"])
good = np.isfinite(v)
if good.sum() < 2:
raise ValueError(f"No sonic-domain log: {name}/{curve}")
resampled[curve] = np.interp(self.tau, self.tau[good], v[good])
valid[curve] = good
ok = np.flatnonzero(np.isfinite(self.ext(name, "calibrated/AI")))
lik = np.zeros(self.t.size, bool)
lik[ok[0]: ok[-1] + 1] = True
seis = self.ext(name, "reference/seismic_patch")
obs.append({"name": name, "tau_k": sonic.time_at(amd[keep]), "t_k": att[keep].astype(float),
"ai_log": resampled["AI"], "labels": {self.label: resampled[self.label]},
"label_valid": {self.label: valid[self.label]}, "lik": lik,
"seis": seis[len(seis) // 2].astype(float)})
return obs

View File

@@ -0,0 +1,287 @@
"""P4 nested selection, scoring and the descriptive G-D report.
Selection (the budget of each trajectory, the point competitor of each outer fold) reads validation labels through
the data view of the outer training wells, VolveData(training_wells=T_out), which holds no label, log or pick of the
outer test well. Outer-test labels are read only by `score`, after every prediction is fixed.
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pandas as pd
from ml_porosity.data.volve_wells import blind_key
from ml_porosity.eval.metrics import gaussian_metrics, point_metrics
from ml_porosity.f3.evaluation import choose_budget
from ml_porosity.f3.progress import write_json
from ml_porosity.f3.training import ensemble
from ml_porosity.volve.data import VolveData, load_arrays
from ml_porosity.volve.folds import inner_folds, outer_folds, target_name
from ml_porosity.volve.losses import finite_runs, highpass_segment
from ml_porosity.volve.protocol import source_config
from ml_porosity.volve.runner import arm_methods, fold_sets, job_path, load_bundle, reg_path
Z90 = 1.6448536269514722
COLUMNS = ["rmse", "mae", "pcc", "r2", "std_ratio", "coverage_80", "coverage_90", "nll", "crps", "mean_sigma",
"band_rmse", "band_pcc"]
def neural_predictions(p: dict, root: Path, arrays: dict, sigmas: list[float]) -> tuple[list[dict], list[dict]]:
"""Per scheme, outer fold, σ_a arm, method and seed: the budget with the lowest mean validation MSE over the
inner wells (original scale, labelled samples; earliest tie), the inner models ensembled at that budget on the
outer test input (key T_out), then the seeds ensembled."""
p4 = source_config(p)["p4"]
label, ref, budgets = p["data"]["label"], p["data"]["primary_reference"], p["training"]["budgets"]
cache, predictions, selections = {}, [], []
for scheme in p["split"]["schemes"]:
for test, outer_train in outer_folds(p["data"]["wells"], scheme, p4):
view = VolveData(p, training_wells=outer_train, arrays=arrays)
folds = inner_folds(outer_train)
labels = {v: view.y(v, ref) for v, _ in folds}
test_key = blind_key(outer_train)
for sa in sigmas:
for method in arm_methods(p, sa):
fold = dict(scheme=scheme, test_well=test, method=method, label=label, sigma_a_ms=sa)
per_seed = []
for seed in p["split"]["seeds"]:
curves, members = [], []
for v, t_in in folds:
path = job_path(root, t_in, method, label, seed, sa)
if path not in cache:
cache[path] = load_bundle(path)
z = cache[path]
if tuple(z["wells"]) != tuple(sorted(t_in)):
raise RuntimeError(f"Trajectory trained on other wells: {path}")
names = list(z["targets"])
y = labels[v]
ok = np.isfinite(y)
i = names.index(target_name(v, blind_key(t_in)))
curves.append([np.mean((z[f"{b}/mu"][i][ok] - y[ok]) ** 2) for b in budgets])
members.append((z, names.index(target_name(test, test_key))))
budget = choose_budget(np.array(curves), budgets)
mu, sigma = ensemble(np.stack([z[f"{budget}/mu"][i] for z, i in members]),
np.stack([z[f"{budget}/sigma"][i] for z, i in members]))
entry = fold | dict(seed=seed, members=len(folds), test_key=test_key, mu=mu, sigma=sigma)
predictions.append(entry)
per_seed.append(entry)
selections.append(fold | dict(
seed=seed, budget=budget,
validation_mse=float(np.mean(np.asarray(curves)[:, budgets.index(budget)])),
validation_wells=";".join(v for v, _ in folds),
validation_keys=";".join(blind_key(t) for _, t in folds),
training_sets=";".join(",".join(t) for _, t in folds)))
mu, sigma = ensemble(np.stack([e["mu"] for e in per_seed]), np.stack([e["sigma"] for e in per_seed]))
predictions.append(fold | dict(seed="ensemble", members=sum(e["members"] for e in per_seed),
test_key=test_key, mu=mu, sigma=sigma))
return predictions, selections
def references(full: VolveData, well: str, p: dict) -> list[str]:
"""The scoring references that exist for a well (NIVSP and OPTIMIZED only at F-11 T2)."""
return [r for r in p["data"]["references"] if f"{well}/{r}/{full.label}" in full.arrays]
def desc_band(y: np.ndarray, mu: np.ndarray, f_c: float, dt: float, min_samples: int) -> dict:
"""High-passed (< f_c removed) reference and prediction on each finite reference run of ≥ min_samples, pooled.
Runs are shorter than one period at f_c: descriptive only."""
runs = [(a, b) for a, b in finite_runs(y) if b - a >= min_samples]
if not runs:
return {"band_samples": 0, "band_rmse": np.nan, "band_pcc": np.nan, "band_std_ratio": np.nan}
t = np.concatenate([highpass_segment(y[a:b], f_c, dt) for a, b in runs])
q = np.concatenate([highpass_segment(mu[a:b], f_c, dt) for a, b in runs])
m = point_metrics(t, q)
return {"band_samples": int(t.size)} | {f"band_{k}": m[k] for k in ("rmse", "pcc", "std_ratio")}
def score(full: VolveData, pred: dict, reference: str, p: dict) -> dict:
"""Metrics in porosity units on the samples where the reference exists; references with fewer than
min_label_samples samples are listed but not scored."""
y = 100 * full.y(pred["test_well"], reference)
mu, sigma = 100 * pred["mu"], np.maximum(100 * pred["sigma"], 1e-6)
ok = np.isfinite(y)
row = {k: v for k, v in pred.items() if k not in ("mu", "sigma")} | dict(reference=reference,
n_reference=int(ok.sum()))
if ok.sum() < p["data"]["min_label_samples"]:
return row | dict(scored=False)
m = p["metrics"]
return (row | dict(scored=True) | point_metrics(y, mu) | gaussian_metrics(y[ok], mu[ok], sigma[ok])
| desc_band(y, mu, m["f_c_hz"], full.dt, m["desc_band_min_samples"]))
def best_shift(full: VolveData, pred: dict, reference: str, max_shift: int) -> dict:
"""Lag (samples, positive = prediction later) maximising PCC with the reference; diagnostic only, smallest |lag|
on ties. Never alters a score."""
y = full.y(pred["test_well"], reference)
idx = np.flatnonzero(np.isfinite(y))
best = (-np.inf, 0)
for s in sorted(range(-max_shift, max_shift + 1), key=abs):
j = idx + s
if j[0] < 0 or j[-1] >= pred["mu"].size:
continue
r = point_metrics(y[idx], pred["mu"][j])["pcc"]
if np.isfinite(r) and r > best[0]:
best = (r, s)
return {"best_shift_samples": best[1], "best_shift_ms": best[1] * full.dt, "best_shift_pcc": best[0]}
def gate_gd(metrics: pd.DataFrame, selection: pd.DataFrame, p: dict) -> dict:
"""G-D: report every well in either direction; claim wording follows protocol_volve gate.claim_rules."""
g, sa = p["gate"], p["registration"]["sigma_a_ms"]
rules = g["claim_rules"]
primary = metrics[(metrics.reference == p["data"]["primary_reference"]) & (metrics.seed.astype(str) == "ensemble")
& (metrics.sigma_a_ms == sa)]
within = lambda c, band: band[0] - 1e-12 <= c <= band[1] + 1e-12
schemes = {}
for scheme in p["split"]["schemes"]:
rows = []
for well in p["data"]["wells"]:
sel = selection[(selection.scheme == scheme) & (selection.test_well == well)
& (selection.sigma_a_ms == sa) & selection.method.isin(g["point_competitors"])]
scores = sel.groupby("method").validation_mse.mean()
if len(scores) != len(g["point_competitors"]):
return {"evaluated": False, "reason": "Incomplete point competitors"}
competitor = str(scores.idxmin())
pick = {}
for role, method in (("candidate", g["candidate"]), ("competitor", competitor),
("same_posterior", g["same_posterior_method"])):
hit = primary[(primary.scheme == scheme) & (primary.test_well == well) & (primary.method == method)]
if len(hit) != 1 or not bool(hit.iloc[0].scored):
raise ValueError(f"Incomplete G-D predictions: {scheme}/{well}/{method}")
pick[role] = hit.iloc[0]
a, b, d = pick["candidate"], pick["competitor"], pick["same_posterior"]
rows.append(dict(well=well, competitor=competitor, competitor_validation_mse=float(scores[competitor]),
n=int(a.n), rmse=float(a.rmse), competitor_rmse=float(b.rmse),
ratio=float(a.rmse / b.rmse), improved=bool(a.rmse < b.rmse),
same_posterior_rmse=float(d.rmse), improved_vs_same_posterior=bool(a.rmse < d.rmse),
coverage_80=float(a.coverage_80), coverage_90=float(a.coverage_90)))
frame = pd.DataFrame(rows)
c80, c90 = float(frame.coverage_80.mean()), float(frame.coverage_90.mean())
wins = int(frame.improved.sum())
schemes[scheme] = dict(
improved_wells=wins, n_wells=len(rows), macro_rmse=float(frame.rmse.mean()),
macro_competitor_rmse=float(frame.competitor_rmse.mean()),
macro_same_posterior_rmse=float(frame.same_posterior_rmse.mean()),
improved_vs_same_posterior_wells=int(frame.improved_vs_same_posterior.sum()),
coverage_80=c80, coverage_90=c90,
consistent_improvement=wins >= rules["min_improved_wells"],
coverage_in_band=within(c80, rules["coverage_80"]) and within(c90, rules["coverage_90"]),
per_well=rows)
claims = {"consistent_improvement": all(s["consistent_improvement"] for s in schemes.values()),
"calibrated": all(s["coverage_in_band"] for s in schemes.values())}
return dict(evaluated=True, descriptive=True, schemes=schemes, claims=claims, note=g["note"])
def registration_table(p: dict, root: Path, sigmas: list[float]) -> pd.DataFrame:
"""Per training set and well: γ, particles, posterior spread and label support per method (fewest and most
samples over the members; training wells only)."""
rows = []
for names in fold_sets(p):
for sa in sigmas:
meta = json.loads(reg_path(root, names, sa).with_suffix(".json").read_text(encoding="utf-8"))
for d in meta["diagnostics"]:
rows.append(dict(training_wells=";".join(names), sigma_a_ms=sa, phase0=meta["phase0"],
phase_R=meta["phase_R"], lam=meta["lambda"], tau_c=meta["tau_c"],
wall_seconds=meta["wall_seconds"], lik_start_ms=d["lik_ms"][0],
lik_stop_ms=d["lik_ms"][1],
**{k: v for k, v in d.items() if not isinstance(v, (list, dict))},
**{f"label_samples_{m}": n for m, n in d["label_samples"].items()},
**{f"label_samples_max_{m}": n for m, n in d["label_samples_max"].items()}))
return pd.DataFrame(rows)
def summarize(p: dict, root: Path, sigmas: list[float], arrays: dict | None = None) -> dict:
arrays = load_arrays() if arrays is None else arrays
pred, sel = neural_predictions(p, root, arrays, sigmas)
full = VolveData(p, arrays=arrays)
frame = pd.DataFrame([score(full, a, ref, p) for a in pred for ref in references(full, a["test_well"], p)])
selections = pd.DataFrame(sel)
gate = gate_gd(frame, selections, p)
smoke = root.name == "smoke"
if smoke:
gate = {"evaluated": False, "reason": "Smoke run; not the registered P4 experiment", "pipeline_check": gate}
dest = root / "summary"
dest.mkdir(parents=True, exist_ok=True)
frame.to_csv(dest / "metrics.csv", index=False)
selections.to_csv(dest / "selection.csv", index=False)
registration_table(p, root, sigmas).to_csv(dest / "registration.csv", index=False)
ens = frame[(frame.seed.astype(str) == "ensemble") & frame.scored.astype(bool)]
groups = ens.groupby(["scheme", "sigma_a_ms", "reference", "method"])
macro = groups[COLUMNS].mean().join(groups.size().rename("n_wells")).reset_index()
macro.to_csv(dest / "macro.csv", index=False)
shifts = [{k: v for k, v in a.items() if k not in ("mu", "sigma")}
| best_shift(full, a, p["data"]["primary_reference"], p["metrics"]["best_shift_max_samples"])
for a in pred if a["seed"] == "ensemble"]
pd.DataFrame(shifts).to_csv(dest / "best_shift_DIAGNOSTIC_ONLY.csv", index=False)
saved = {}
for i, a in enumerate(pred):
saved[f"{i}/mu"], saved[f"{i}/sigma"] = a["mu"], a["sigma"]
np.savez_compressed(dest / "predictions.npz", times_ms=full.t_main, **saved)
write_json(dest / "prediction_index.json", [{k: v for k, v in a.items() if k not in ("mu", "sigma")} for a in pred])
write_json(dest / "gate_gd.json", gate)
main = macro[(macro.reference == p["data"]["primary_reference"])
& (macro.sigma_a_ms == p["registration"]["sigma_a_ms"])]
text = ["# P4 Volve — nested blind folds (" + ", ".join(p["split"]["schemes"]) + ")", "",
"Smoke only; no scientific result." if smoke else
"Registered protocol_volve; outer-test labels are scoring-only.", "",
"G-D (descriptive): " + json.dumps(gate, ensure_ascii=False, default=str), "",
f"## Macro over wells, {p['data']['primary_reference']} reference, "
f"σ_a = {p['registration']['sigma_a_ms']:g} ms (p.u.)", "",
main.to_markdown(index=False, floatfmt=".4f"), "",
"Per-well, per-seed and reference-sensitivity results: metrics.csv and macro.csv. Budgets: selection.csv. "
"Registration diagnostics (training wells only): registration.csv.",
f"band_* is a high-pass of reference runs of at least {p['metrics']['desc_band_min_samples']} samples, "
"shorter than one period at f_c: descriptive only. Best-shift is diagnostic only and never alters a score.",
"Six wells in three slots: per-well results are the replication unit; no p-values."]
(dest / "summary.md").write_text("\n".join(text) + "\n", encoding="utf-8")
plot_results(full, p, pred, gate.get("pipeline_check", gate), dest)
return gate
def plot_results(full: VolveData, p: dict, pred: list[dict], gate: dict, dest: Path) -> None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
sa, ref, wells = p["registration"]["sigma_a_ms"], p["data"]["primary_reference"], p["data"]["wells"]
files = []
for scheme in p["split"]["schemes"]:
chosen = {r["well"]: r["competitor"] for r in gate.get("schemes", {}).get(scheme, {}).get("per_well", [])}
fig, axes = plt.subplots(1, len(wells), figsize=(2.5 * len(wells), 6), sharey=True, sharex=True,
layout="constrained")
for ax, w in zip(axes, wells):
ax.plot(100 * full.y(w, ref), full.t_main, "k", label="Reference")
competitor = chosen.get(w, "B3b")
for method, color, style, name in ((competitor, "#0072B2", "--", "Selected B3"),
("B3d-Sa", "#8F5800", ":", "B3d-Sa"), ("M2-Sa", "#CC3311", "-", "M2-Sa")):
rows = [a for a in pred if a["scheme"] == scheme and a["test_well"] == w and a["method"] == method
and a["seed"] == "ensemble" and a["sigma_a_ms"] == sa]
if not rows:
continue
a = rows[0]
ax.plot(100 * a["mu"], full.t_main, color=color, linestyle=style, label=name)
if method == "M2-Sa":
ax.fill_betweenx(full.t_main, 100 * (a["mu"] - Z90 * a["sigma"]),
100 * (a["mu"] + Z90 * a["sigma"]), color=color, alpha=0.18)
ax.set(title=f"{w}\n(B3: {competitor})", xlabel="PHIF (p.u.)")
ax.grid(alpha=0.2)
axes[0].set_ylabel("TWT (ms)")
axes[0].invert_yaxis()
axes[0].legend(fontsize=8)
for ext in ("png", "pdf"):
fig.savefig(dest / f"wells_{scheme}.{ext}", dpi=160)
files.append(f"wells_{scheme}.{ext}")
plt.close(fig)
write_json(dest / "figure_manifest.json", {
"files": files, "source": "predictions.npz and prediction_index.json",
"reference": "marker-calibrated vertical sonic (TVD-integrated DT) of the held-out well",
"uncertainty": "nominal 90% moment-matched Gaussian predictive interval of M2-Sa; calibration is evaluated "
"separately",
"replication_unit": "well (n=6, three slots); network seeds are computational repeats",
"transform": "porosity fraction multiplied by 100", "filters": "none for plotting",
"publisher_requirements": "not yet verified",
"description": "One panel per held-out well and blind scheme: reference over its support and blind "
"predictions over the main window against downward-increasing two-way time; the B3 line is the "
"point competitor selected by inner validation."})

View File

@@ -0,0 +1,74 @@
"""Nested blind folds for P4 (plan §5.2).
Outer fold: test well u, training wells T_out = blind_training_wells(u, scheme) (`lowo`: every other well; `slot`:
every well outside the slot group of u). Inner folds: leave one well of T_out out, under both schemes — under
`slot` an inner validation well may share a slot with inner training wells, so inner validation can be optimistic
there (recorded deviation in protocol_volve).
Every model sees seismic only through blind keys: the input of a non-training well u under key K is placed in time
by the TD model of the wells K, with T_in ⊆ K ⊆ W∖{u} (never u's own picks or DT). Validation of v in T_out uses
K = T_in; the outer test of u uses K = T_out. Training wells use their calibrated reference path.
"""
from __future__ import annotations
import itertools
from ml_porosity.data.volve_wells import blind_key, blind_training_wells
def outer_folds(wells: list[str], scheme: str, p4: dict) -> list[tuple[str, tuple[str, ...]]]:
"""[(test well u, T_out)] in `wells` order; T_out sorted."""
out = []
for u in wells:
train = tuple(sorted(blind_training_wells(u, scheme, p4)))
if u in train or not train:
raise RuntimeError(f"invalid outer fold for {u}: {train}")
out.append((u, train))
return out
def inner_folds(outer_train: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]:
"""[(validation well v, T_in = T_out ∖ {v})], leave-one-well-out within the outer training set."""
train = tuple(sorted(outer_train))
if len(train) < 2:
raise ValueError("inner LOWO needs at least two outer training wells")
return [(v, tuple(w for w in train if w != v)) for v in train]
def nested_folds(wells: list[str], schemes: list[str], p4: dict) -> list[dict]:
"""Every (scheme, test well, validation well, T_out, T_in), with the blind key of each role."""
rows = []
for scheme in schemes:
for u, t_out in outer_folds(wells, scheme, p4):
for v, t_in in inner_folds(t_out):
if u in t_in or v in t_in:
raise RuntimeError("held-out well entered an inner training set")
rows.append(dict(scheme=scheme, test=u, validation=v, outer_train=t_out, inner_train=t_in,
validation_key=blind_key(t_in), test_key=blind_key(t_out)))
return rows
def training_sets(wells: list[str], schemes: list[str], p4: dict) -> list[tuple[str, ...]]:
"""Distinct inner training sets over all schemes (one trajectory per set, method, seed and σ_a arm)."""
return sorted({f["inner_train"] for f in nested_folds(wells, schemes, p4)}, key=lambda s: (-len(s), s))
def prediction_targets(wells: list[str], train: tuple[str, ...]) -> list[tuple[str, str]]:
"""(well, key) inputs predicted by a model trained on `train`: training wells on their reference path
(key 'reference'), every other well u on every blind key K with train ⊆ K ⊆ W∖{u}. Covers the validation
(K = T_in) and outer-test (K = T_out ⊋ T_in) inputs of every fold that trains on `train`."""
train = tuple(sorted(train))
out = [(w, "reference") for w in train]
for u in wells:
if u in train:
continue
rest = [w for w in wells if w != u and w not in train]
for k in range(len(rest) + 1):
for extra in itertools.combinations(rest, k):
out.append((u, blind_key(train + extra)))
return out
def target_name(well: str, key: str) -> str:
return f"{well}|{key}"

View File

@@ -0,0 +1,93 @@
"""Bank losses with label masks (P4: Volve labels cover 16–37 of the 126 main-window samples).
Member s of the bank of training well b places the same label run at its own times, so it has its own support
mask M_bs (L); a (B, L) mask is shared by all members. For window j, n_bjs = Σ_{i ∈ j} M_bsi and n̄_bj = mean_s n_bjs:
ℓ_bjs = (n̄_bj / n_bjs) Σ_{i ∈ j} M_bsi log N(y_bs,i; μ_i, σ_i²) (members compared at a common count)
RML: L_b = −Σ_j (1/λ) log Σ_s π_bs exp(λ ℓ_bjs) / Σ_j n̄_bj
hard-min: L_b = −Σ_j max_s ℓ_bjs / Σ_j n̄_bj
and the loss is the mean of L_b over wells. A window where some member has no valid sample contributes nothing.
With a shared mask the count factor is 1; with every sample valid the loss equals losses.rml.bank_loss.
"""
from __future__ import annotations
import numpy as np
import torch
from scipy import signal
from ml_porosity.losses.rml import LOG_2PI, gather_windows
def masked_window_loglik(mu, sigma, Y, mask, starts, win: int) -> tuple[torch.Tensor, torch.Tensor]:
"""mu, sigma (B, L); Y (B, S, L), any value where the mask is False; mask (B, L) or (B, S, L)
→ summed ℓ (B, J, S) and valid counts n (B, J, S)."""
if mask.dim() == 2:
mask = mask[:, None, :].expand(Y.shape)
if mask.shape != Y.shape:
raise ValueError("mask must be (B, L) or match the bank (B, S, L)")
y = torch.where(mask, Y, torch.zeros((), dtype=Y.dtype, device=Y.device))
m = gather_windows(mu, starts, win)[:, :, None, :]
s = gather_windows(sigma, starts, win)[:, :, None, :]
w = gather_windows(mask.to(mu.dtype), starts, win)
term = -torch.log(s) - 0.5 * ((gather_windows(y, starts, win) - m) / s) ** 2 - 0.5 * LOG_2PI
return (term * w).sum(-1), w.sum(-1)
def masked_bank_loss(mu, sigma, Y, logpi, mask, starts, win: int, lam: float | None) -> torch.Tensor:
"""lam = None → hard-min (max ℓ); otherwise RML with power λ. Every well needs a window in which every member
has a valid sample."""
ll, n = masked_window_loglik(mu, sigma, Y, mask, starts, win)
use = (n > 0).all(-1)
nbar = n.mean(-1)
ll = torch.where(use[..., None], ll * nbar[..., None] / n.clamp(min=1), torch.zeros((), dtype=ll.dtype,
device=ll.device))
total = (nbar * use).sum(1)
if not bool((total > 0).all()):
raise ValueError("a training well has no labelled sample in any window")
v = ll.max(-1).values if lam is None else torch.logsumexp(logpi[:, None, :] + lam * ll, dim=-1) / lam
v = torch.where(use, v, torch.zeros((), dtype=v.dtype, device=v.device))
return -(v.sum(1) / total).mean()
def highpass_segment(y: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) -> np.ndarray:
"""y minus its zero-phase Butterworth low band below f_c, as eval.metrics.split_bands (identical for ≥ 16
samples at order 4); shorter segments use the longest even padding scipy accepts."""
y = np.asarray(y, dtype=float)
sos = signal.butter(order, f_c_hz, fs=1000.0 / dt_ms, output="sos")
pad = min(3 * (2 * len(sos) + 1), y.size - 1)
return y - signal.sosfiltfilt(sos, y, padtype="even", padlen=pad)
def segment_lambda(segments: list[np.ndarray], f_c_hz: float = 6.0, dt_ms: float = 4.0,
max_lag: int = 32) -> tuple[float, float]:
"""losses.rml.effective_lambda for label segments of any length ≥ 2: λ = 1/τ_c, τ_c = 1 + 2 Σ_k ρ(k)², with ρ
the ACF of the high-passed segments pooled as lagged products (a lag longer than a segment adds nothing). Σ runs
up to the first lag with ρ ≤ 0. Equals effective_lambda when every segment has more than max_lag samples."""
acc = np.zeros(max_lag + 1)
for y in segments:
y = np.asarray(y, dtype=float)
if y.size < 2 or not np.isfinite(y).all():
raise ValueError("segments must be finite with at least two samples")
hi = highpass_segment(y, f_c_hz, dt_ms)
hi = hi - hi.mean()
a = np.correlate(hi, hi, "full")[hi.size - 1: hi.size + max_lag]
acc[: a.size] += 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
def finite_runs(y: np.ndarray) -> list[tuple[int, int]]:
"""[start, stop) of the maximal runs of finite samples of a series (NaN separates runs)."""
ok = np.isfinite(np.asarray(y, dtype=float))
edges = np.flatnonzero(np.diff(np.r_[0, ok.astype(int), 0]))
return [(int(a), int(b)) for a, b in zip(edges[::2], edges[1::2])]
def label_segments(y: np.ndarray) -> list[np.ndarray]:
"""Maximal runs of finite samples of a series."""
y = np.asarray(y, dtype=float)
return [y[a:b] for a, b in finite_runs(y)]

View File

@@ -0,0 +1,123 @@
"""Protocol locking and resume fingerprints for P4 (Volve), separate from the frozen P3 lock.
Paths in the stamp are relative to their root (repo, outputs or Volve data directory), so a lock is portable between
checkouts; it is still bound to one environment, as in P3. Before the lock exists, `current_stamp` gives the same
stamp without writing it (smoke runs only).
"""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
import yaml
from ml_porosity.f3.protocol import digest, environment, fingerprint
from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root
__all__ = ["CONFIG", "LOCK", "current_stamp", "fingerprint", "freeze", "load_protocol", "source_config"]
CONFIG = REPO_ROOT / "configs/protocol_volve.yaml"
LOCK = REPO_ROOT / "configs/protocol_volve.lock.json"
SCRIPTS = ("scripts/23_build_volve_wells.py", "scripts/24_run_volve.py", "scripts/run_p4.ps1", "scripts/run_p4.sh")
PROTECTED = ("wavelets.npz", "p2/warp_prior_f3.json")
RESULTS = ("registration", "train", "summary")
def load_protocol() -> dict:
return yaml.safe_load(CONFIG.read_text(encoding="utf-8"))
def source_config(p: dict) -> dict:
"""configs/d3_volve.yaml, which built the dataset; its p4 section holds the slot groups of the blind folds."""
cfg = yaml.safe_load((REPO_ROOT / p["data"]["source_config"]).read_text(encoding="utf-8"))
if list(cfg["p4"]["wells"]) != list(p["data"]["wells"]) or cfg["p4"]["label"] != p["data"]["label"]:
raise RuntimeError("protocol_volve and its source configuration disagree on wells or label")
if not set(p["split"]["schemes"]) <= set(cfg["p4"]["blind_schemes"]):
raise RuntimeError("Unknown blind scheme in protocol_volve")
return cfg
def code_files() -> list[Path]:
paths = sorted((REPO_ROOT / "ml_porosity").rglob("*.py"))
paths += [REPO_ROOT / s for s in SCRIPTS if (REPO_ROOT / s).exists()]
return paths + [REPO_ROOT / "pyproject.toml"]
def source_hash() -> str:
import hashlib
h = hashlib.sha256()
for f in code_files():
h.update(f.relative_to(REPO_ROOT).as_posix().encode() + b"\0")
h.update(f.read_bytes().replace(b"\r\n", b"\n") + b"\0")
return h.hexdigest()
def input_files(p: dict) -> list[Path]:
"""Derived dataset, its configuration and every raw file the build reads, except the cube (checked against the
data manifest at the first lock)."""
cfg = source_config(p)
root, p4 = volve_root(), cfg["p4"]
files = [outputs_dir() / "volve/volve_wells.npz", outputs_dir() / "volve/volve_wells_summary.json",
root / cfg["picks"], root / cfg["horizons_twt"] / cfg["grid_horizon"]]
for spec in p4["wells"].values():
files.append(root / p4["survey_dir"] / spec["survey"])
logs = root / cfg["well_logs_dir"] / spec["logs"] / p4["log_subdir"]
files += [logs / p4["las_input"], logs / p4["las_output"]]
files += [root / cfg["well_logs_dir"] / cfg["checkshots"][spec["picks"]][kind]
for kind in spec.get("checkshots", [])]
return files
def portable_name(path: Path) -> str:
"""Portable name: 'repo:', 'outputs:' or 'volve:' plus the POSIX path relative to that root."""
path = path.resolve()
for prefix, base in (("volve", volve_root()), ("outputs", outputs_dir()), ("repo", REPO_ROOT)):
try:
return f"{prefix}:{path.relative_to(base.resolve()).as_posix()}"
except ValueError:
continue
raise ValueError(f"Input outside the repository, outputs and Volve roots: {path}")
def current_stamp(p: dict | None = None) -> dict:
p = load_protocol() if p is None else p
missing = [f for f in input_files(p) + [outputs_dir() / a for a in PROTECTED] if not f.exists()]
if missing:
raise FileNotFoundError(f"P4 inputs missing (sync data/ and outputs/ first): {[str(f) for f in missing]}")
config = REPO_ROOT / p["data"]["source_config"]
return {"protocol_sha256": digest(CONFIG, True), "code_sha256": source_hash(), "environment": environment(),
"protected_artifacts": {portable_name(outputs_dir() / a): digest(outputs_dir() / a) for a in PROTECTED},
"inputs": {portable_name(f): digest(f, f == config) for f in [config] + input_files(p)}}
def freeze(check: bool = False) -> dict:
"""Return the lock; create it if absent and check is False. Any difference from an existing lock is an error."""
p = load_protocol()
stamp = current_stamp(p)
if LOCK.exists():
old = json.loads(LOCK.read_text(encoding="utf-8"))
for k, v in stamp.items():
if old[k] != v:
raise RuntimeError(f"P4 lock mismatch: {k}. Preserve results and create a new protocol version.")
return old
if check:
raise RuntimeError("P4 is not locked. Run the lock stage before registration/training.")
if any((outputs_dir() / "p4" / d).exists() for d in RESULTS):
raise RuntimeError("Refusing a first lock after P4 results already exist.")
cfg = source_config(p)
manifest = json.loads((REPO_ROOT / "data_manifest/volve.json").read_text(encoding="utf-8"))
expected = manifest["files"][cfg["cube"]]["sha256"]
cube = volve_root() / cfg["cube"]
if not cube.exists() or digest(cube) != expected:
raise RuntimeError(f"Volve cube missing or different from the audited source: {cube}")
stamp |= {"locked_utc": datetime.now(timezone.utc).isoformat(), "segy_sha256": expected,
"canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and source configuration; "
"binary inputs exact",
"wells": p["data"]["wells"]}
LOCK.write_text(json.dumps(stamp, indent=2), encoding="utf-8")
CONFIG.with_suffix(".sha256").write_text(stamp["protocol_sha256"] + " configs/protocol_volve.yaml\n",
encoding="utf-8")
return stamp

View File

@@ -0,0 +1,171 @@
"""Training-set-only P4 registration and label banks. No held-out well is passed to this module.
Follows ml_porosity.f3.registration.register_set with three recorded deviations (protocol_volve):
- Likelihood window: AI exists only over the logged interval (45–151 of the 301 ext samples), so the tie
likelihood of a well (phase grid, SMC, γ) is evaluated on `lik`, the ext samples from the first to the last
finite calibrated AI sample of that well; outside it the constant AI extension gives a zero synthetic that would
only fit noise. B3c/B3c-R keep the F3 full-window local shifts: windows without synthetic energy have r = NaN and
are dropped by r_min.
- Particle validity: labels cover 16–37 of the 126 main samples, so a particle only has to invert over the main
window (F3 also required full label support there).
- Member support: every member keeps the samples where its own warp places the label run (NaN elsewhere), so
no label is extrapolated and the run is not trimmed to the intersection of all members (which loses both ends
of a 16-sample run under the posterior spread). A member with fewer than `min_label_samples` is an error. The
intersection over members and methods is recorded as a diagnostic only.
"""
from __future__ import annotations
import gc
import time
from types import SimpleNamespace
import numpy as np
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet
from ml_porosity.registration.labels import antialias, invert_warps, labels_for_warps
from ml_porosity.registration.pipeline import PHASES, fit_cell_hyper
from ml_porosity.registration.sampler import sample_warps
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, profile_loglik, synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c
from ml_porosity.volve.data import VolveData
from ml_porosity.volve.losses import label_segments, segment_lambda
METHODS = ("B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa")
def valid_warps(data: VolveData, warps: np.ndarray) -> np.ndarray:
"""Warps whose inverse τ(t) exists over the whole main window."""
return np.isfinite(invert_warps(warps, data.tau, data.t_main)).all(axis=1)
def window_phase_loglik(syn0: np.ndarray, seis: np.ndarray, lik: np.ndarray, phases=PHASES) -> np.ndarray:
"""(P, S) as tie_likelihood.phase_loglik, with the phase rotated on the full ext synthetic and the profile
likelihood taken over the samples `lik` only."""
syn0 = np.atleast_2d(syn0)
return np.stack([profile_loglik(rotate_phase(syn0, p)[:, lik], seis[lik]) for p in phases])
def label_fn(data: VolveData, obs: dict, y_filtered: np.ndarray):
"""t(τ) warps (S, n_tau) → labels (S, L) on the main window, NaN where the label is not supported."""
valid = obs["label_valid"][data.label].astype(float)
def lab(warps):
warps = np.atleast_2d(warps)
tau_at = invert_warps(warps, data.tau, data.t_main)
support = np.interp(np.nan_to_num(tau_at, nan=data.tau[0] - 1.0), data.tau, valid, left=0, right=0)
out = labels_for_warps(data.tau, y_filtered, warps, data.t_main)
return np.where(np.isfinite(tau_at) & (support >= 1 - 1e-9), out, np.nan)
return lab
def register_set(data: VolveData, names: tuple[str, ...], p: dict, device: str,
sigma_a: float = 7.0) -> tuple[dict, dict]:
import torch
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
started = time.perf_counter()
names = tuple(sorted(names))
r = p["registration"] | {"sigma_a_ms": sigma_a}
label = data.label
obs = data.training_observations(names)
if tuple(o["name"] for o in obs) != names:
raise RuntimeError("Unexpected training-well payload")
h, hinfo = fit_cell_hyper(SimpleNamespace(grid=data.grid), obs, r, r["smc_seed"])
f = r["fine_dt_ms"]
fac = int(round(data.dt / f))
w0 = statistical_wavelet(np.stack([o["seis"] for o in obs]), data.dt, r["wavelet_ms"])
B = phase_basis(w0, fac)
cover = (data.t_main[0], data.t_main[-1])
samples, Ts, Zs, LL, anchor_valid = [], [], [], [], []
for i, o in enumerate(obs):
smp = sample_warps(data.grid, h, o["tau_k"], o["t_k"], r["particles"], r["g_max"],
np.random.default_rng([r["smc_seed"], i, 13]))
samples.append(smp)
tg = data.grid.t_of_tau(smp["b"][:r["S"]], smp["g"][:r["S"]], data.tau)
valid = valid_warps(data, tg)
if not valid.any():
raise ValueError(f"No anchor sample covers the main window: {o['name']}")
anchor_valid.append(valid)
syn = synth_for_warps(data.tau, o["ai_log"], tg, data.t_fine, data.t, fine_wavelet(w0, fac))
LL.append(window_phase_loglik(syn, o["seis"], o["lik"]))
phase0 = float(PHASES[fit_phase(LL, anchor_valid, PHASES)])
for o, smp in zip(obs, samples):
T = TiePosteriorTorch(TiePosterior(data.grid, h, o["tau_k"], o["t_k"], r["g_max"], data.tau, o["ai_log"],
data.t_fine, data.t[o["lik"]], phase_wavelet(B, phase0),
o["seis"][o["lik"]], cover), device)
Zs.append(T.z(smp["u"]))
Ts.append(T)
phase_r, ph = smc_fit_phase(Ts, Zs, B, phase0, [r["smc_seed"], 19], step=r["phase_step"],
half_width=r["phase_half_width"], max_extra=r["phase_max_extra"],
n_moves=r["smc_moves"])
wf = phase_wavelet(B, phase_r)
post, diag = [], []
for i, (o, T0, z0) in enumerate(zip(obs, Ts, Zs)):
T = T0.with_wavelet(wf)
gamma = gamma_acf(T, z0, T.parts(z0)[1])
res = smc_tie_posterior(T, z0, [gamma], np.random.default_rng([r["smc_seed"], i, 17]),
n_moves=r["smc_moves"])
u = T.u(res["Z"][gamma])
tg = data.grid.t_of_tau(u[:, 0], u[:, 1:], data.tau)
valid = valid_warps(data, tg)
if valid.sum() < min(256, r["particles"]):
raise ValueError(f"Insufficient posterior particles covering the main window: {o['name']}, "
f"{valid.sum()} valid")
post.append(tg[valid])
diag.append({"well": o["name"], "gamma": gamma, "n_stages": len(res["stages"]),
"valid_particles": int(valid.sum()), "particles": len(valid),
"n_anchors": len(o["tau_k"]), "lik_samples": int(o["lik"].sum()),
"lik_ms": [float(data.t[o["lik"]][0]), float(data.t[o["lik"]][-1])]})
bundle = {"wells": np.asarray(names), "phase0": np.asarray(phase0), "phase_R": np.asarray(phase_r)}
banks = {m: [] for m in METHODS}
logpi = []
filtered = [antialias(o["labels"][label], f, data.dt) for o in obs]
normsel = (data.tau >= data.t_main[0]) & (data.tau <= data.t_main[-1])
vals = np.concatenate([y[normsel & o["label_valid"][label]] for o, y in zip(obs, filtered)])
bundle[f"{label}/norm"] = np.array([vals.mean(), max(vals.std(), 1e-8)])
for i, (o, tg, y) in enumerate(zip(obs, post, filtered)):
lab = label_fn(data, o, y)
b3b = tie_b3b(o["tau_k"], o["t_k"], data.tau)
ties = {"B3b": b3b, "B3d-Sa": tg.mean(axis=0)}
for name, phase in (("B3c", phase0), ("B3c-R", phase_r)):
syn = synth_for_warps(data.tau, o["ai_log"], b3b, data.t_fine, data.t,
fine_wavelet(rotate_phase(w0, phase), fac))[0]
ties[name] = tie_b3c(b3b, data.tau, syn, o["seis"], data.t, data.dt)
per = {m: lab(t) for m, t in ties.items()}
sub = np.random.default_rng([r["smc_seed"], i, 29]).choice(len(tg), r["S"], replace=False)
per["M2-Sa"] = lab(tg[sub])
counts = {m: np.isfinite(a).sum(axis=1) for m, a in per.items()}
short = {m: int(c.min()) for m, c in counts.items() if c.min() < p["data"]["min_label_samples"]}
if short:
raise ValueError(f"Label support too short: {o['name']}, fewest samples per member {short}")
for m in METHODS:
banks[m].append(per[m])
common = np.logical_and.reduce([np.isfinite(a).all(axis=0) for a in per.values()])
union = np.isfinite(per["M2-Sa"]).any(axis=0)
logpi.append(np.full(r["S"], -np.log(r["S"])))
tau_at = invert_warps(tg, data.tau, data.t_main)
q = np.diff(np.quantile(tau_at, [0.05, 0.95], axis=0), axis=0)[0] / 3.29
diag[i] |= {"sigma_post_ms": float(np.mean(q)), "sigma_post_label_ms": float(np.mean(q[union])),
"common_samples": int(common.sum()),
"label_samples": {m: int(c.min()) for m, c in counts.items()},
"label_samples_max": {m: int(c.max()) for m, c in counts.items()}}
for m in METHODS:
bundle[f"{label}/{m}"] = np.stack(banks[m]).astype(np.float32)
bundle[f"{label}/M2-Sa/logpi"] = np.stack(logpi).astype(np.float32)
segments = [s for y in bundle[f"{label}/B3b"][:, 0] for s in label_segments(y) if s.size >= 2]
lam, tau_c = segment_lambda(segments, p["metrics"]["f_c_hz"], data.dt)
bundle[f"{label}/lambda"], bundle[f"{label}/tau_c"] = np.asarray(lam), np.asarray(tau_c)
for o, tg in zip(obs, post):
bundle[f"posterior/{o['name']}/tau_at_main"] = invert_warps(tg, data.tau, data.t_main)
meta = {"training_wells": list(names), "sigma_a_ms": sigma_a, "phase0": phase0, "phase_R": phase_r,
"phase_info": ph, "hyper": h.as_dict(), "hyper_info": hinfo, "diagnostics": diag,
"lambda": lam, "tau_c": tau_c, "wall_seconds": time.perf_counter() - started}
del Ts, Zs, T, T0
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return bundle, meta

283
ml_porosity/volve/runner.py Normal file
View File

@@ -0,0 +1,283 @@
"""Resumable P4 stages. A worker only ever loads the data view of its own training wells and selects nothing.
Progress goes to outputs/p4/<root>/progress.json (retried when Windows locks the file, and never fatal), not to the
P3 dashboard.
"""
from __future__ import annotations
import copy
import itertools
import json
import time
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
from datetime import datetime
from multiprocessing import get_context
from pathlib import Path
import numpy as np
from ml_porosity.f3.progress import write_json
from ml_porosity.paths import outputs_dir
from ml_porosity.volve.data import VolveData
from ml_porosity.volve.folds import prediction_targets, target_name, training_sets
from ml_porosity.volve.protocol import current_stamp, digest, fingerprint, freeze, source_config
from ml_porosity.volve.registration import METHODS
def set_name(names) -> str:
"""'F-1A__F-1B__F-11A__F-12': sorted well names without spaces."""
return "__".join(sorted(n.replace(" ", "") for n in names))
def reg_path(root: Path, names, sigma_a: float = 7) -> Path:
return root / "registration" / f"{set_name(names)}_sa{sigma_a:g}.npz"
def job_path(root: Path, names, method: str, label: str, seed: int, sigma_a: float = 7) -> Path:
return root / "train" / f"{set_name(names)}__{method}__{label}__s{seed}__sa{sigma_a:g}.npz"
def load_bundle(path: Path) -> dict:
with np.load(path) as z:
return {k: z[k] for k in z.files}
def nan_allowed(key: str) -> bool:
"""Label banks are NaN outside each member's label support; every other numeric array must be finite."""
parts = key.split("/")
return len(parts) == 2 and parts[1] in METHODS
def check_arrays(path: Path, arrays: dict) -> None:
if not arrays:
raise RuntimeError(f"Empty completed artifact: {path}")
for k, a in arrays.items():
if not np.issubdtype(a.dtype, np.number):
continue
if np.isinf(a).any() or (np.isnan(a).any() and not nan_allowed(k)) or np.isnan(a).all():
raise RuntimeError(f"Corrupt/non-finite artifact: {path}/{k}")
def reusable(path: Path, key: str) -> bool:
meta = path.with_suffix(".json")
if not path.exists() or not meta.exists():
return False
stored = json.loads(meta.read_text(encoding="utf-8"))
if stored.get("fingerprint") != key:
raise RuntimeError(f"Resume fingerprint mismatch: {path}. Use a new output directory.")
if stored.get("artifact_sha256") is None or digest(path) != stored["artifact_sha256"]:
raise RuntimeError(f"Missing or mismatched completed-artifact checksum: {path}")
if path.parent.name == "train":
ckpt = path.with_suffix(".pt")
if not ckpt.exists() or digest(ckpt) != stored.get("checkpoint_sha256"):
raise RuntimeError(f"Missing or mismatched model checkpoint: {ckpt}")
check_arrays(path, load_bundle(path))
return True
def save_npz(path: Path, arrays: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp.npz")
np.savez_compressed(tmp, **arrays)
tmp.replace(path)
def registration_worker(job: dict) -> dict:
import torch
from ml_porosity.volve.registration import register_set
torch.set_num_threads(job["p"]["runtime"]["cpu_threads_per_worker"])
path = reg_path(Path(job["root"]), job["names"], job["sa"])
if reusable(path, job["key"]):
return {"cached": True, "path": str(path)}
data = VolveData(job["p"], training_wells=tuple(job["names"]))
bundle, meta = register_set(data, tuple(job["names"]), job["p"], job["device"], job["sa"])
check_arrays(path, bundle)
save_npz(path, bundle)
write_json(path.with_suffix(".json"), meta | {"fingerprint": job["key"], "artifact_sha256": digest(path)})
return {"cached": False, "path": str(path), **meta}
def training_worker(job: dict) -> dict:
from ml_porosity.volve.training import method_spec, train_trajectory
root, p = Path(job["root"]), job["p"]
label, names = p["data"]["label"], tuple(sorted(job["names"]))
path = job_path(root, names, job["method"], label, job["seed"], job["sa"])
if reusable(path, job["key"]):
return {"cached": True, "path": str(path)}
data = VolveData(p, training_wells=names)
bundle = load_bundle(reg_path(root, names, job["sa"]))
if tuple(bundle["wells"]) != names:
raise RuntimeError("Registration cache contains different wells")
targets = prediction_targets(data.wells, names)
X = np.stack([data.X(w, "reference") for w in names])
X_targets = np.stack([data.X(w, k) for w, k in targets])
spec = method_spec(bundle, label, job["method"])
ckpt = path.with_suffix(".pt")
ckpt.parent.mkdir(parents=True, exist_ok=True)
pred, meta = train_trajectory(X, X_targets, spec, job["method"], p["training"], job["seed"],
p["training"]["budgets"], job["device"], ckpt,
p["runtime"]["cpu_threads_per_worker"])
mean, sd = bundle[f"{label}/norm"]
pred = {k: v * sd + (mean if k.endswith("/mu") else 0) for k, v in pred.items()}
pred |= {"targets": np.asarray([target_name(w, k) for w, k in targets]), "wells": np.asarray(names),
"norm": bundle[f"{label}/norm"]}
check_arrays(path, pred)
save_npz(path, pred)
write_json(path.with_suffix(".json"), meta | {
"fingerprint": job["key"], "artifact_sha256": digest(path), "checkpoint_sha256": digest(ckpt),
"training_wells": list(names), "label": label, "method": job["method"], "seed": job["seed"],
"sigma_a_ms": job["sa"], "n_targets": len(targets)})
return {"cached": False, "path": str(path), **meta}
def progress(root: Path, **values) -> None:
path = root / "progress.json"
for attempt in range(20):
try:
old = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
write_json(path, old | values | {"updated": datetime.now().astimezone().isoformat(timespec="seconds")})
return
except (PermissionError, json.JSONDecodeError):
time.sleep(0.25 * (attempt + 1))
print(f"warning: progress file not updated: {path}", flush=True)
def run_jobs(jobs: list[dict], fn, workers: int, stage: str) -> list[dict]:
if not jobs:
return []
root = Path(jobs[0]["root"])
started, results = time.perf_counter(), []
progress(root, stage=stage, status="running", completed=0, total=len(jobs), error=None)
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context("spawn")) as pool:
futures = {pool.submit(fn, job): job for job in jobs}
pending = set(futures)
while pending:
done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED)
for fut in done:
try:
result = fut.result()
except Exception as exc:
for other in pending:
other.cancel()
progress(root, status="failed; pending jobs cancelled", error=f"{futures[fut]['key'][:12]}: {exc}")
raise
results.append(result)
fresh = sum(not r.get("cached") for r in results)
elapsed = time.perf_counter() - started
eta = elapsed / fresh * (len(jobs) - len(results)) if fresh else None
progress(root, completed=len(results), cached=len(results) - fresh, elapsed_seconds=elapsed,
eta_seconds=eta)
print(f"{stage} {len(results)}/{len(jobs)} {'cached ' if result.get('cached') else ''}"
f"{result['path']}", flush=True)
progress(root, status="done", eta_seconds=0)
return results
def sigma_arms(p: dict, arms: str) -> list[float]:
"""'primary' → [σ_a], 'sensitivity' → the misspecification arms, 'all' → both."""
primary, extra = [p["registration"]["sigma_a_ms"]], list(p["registration"]["sigma_a_sensitivity_ms"])
return {"primary": primary, "sensitivity": extra, "all": primary + extra}[arms]
def fold_sets(p: dict) -> list[tuple[str, ...]]:
return training_sets(p["data"]["wells"], p["split"]["schemes"], source_config(p)["p4"])
def registration_jobs(p: dict, stamp: dict, root: Path, device: str, arms: str = "primary") -> list[dict]:
jobs = []
for names, sa in itertools.product(fold_sets(p), sigma_arms(p, arms)):
settings = dict(names=list(names), sa=sa)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage="registration", **settings)))
return jobs
def arm_methods(p: dict, sa: float) -> list[str]:
main = sa == p["registration"]["sigma_a_ms"]
return list(p["methods"]["main"] if main else p["registration"]["sensitivity_methods"])
def training_jobs(p: dict, stamp: dict, root: Path, device: str, arms: str = "primary") -> list[dict]:
jobs = []
for names, sa in itertools.product(fold_sets(p), sigma_arms(p, arms)):
for method, seed in itertools.product(arm_methods(p, sa), p["split"]["seeds"]):
settings = dict(names=list(names), method=method, label=p["data"]["label"], seed=seed, sa=sa)
jobs.append(dict(p=p, root=str(root), device=device, **settings,
key=fingerprint(stamp, stage="train", **settings)))
return jobs
def smoke_protocol(p: dict) -> dict:
"""Reduced settings for a pipeline check; outputs go to outputs/p4/smoke and are never results."""
p = copy.deepcopy(p)
p["split"]["seeds"] = [0]
p["registration"].update(particles=16, S=8, hyper_starts=1, smc_moves=1, phase_half_width=0,
phase_max_extra=0, sigma_a_sensitivity_ms=[])
p["training"]["budgets"] = [2, 4]
return p
def benchmark(p: dict, device: str, steps: int = 100) -> dict:
"""Runtime pilot outside the result tree: one registration of the first (largest) training set and `steps`
training steps of B3b and M2-Sa on it. Training wells only; no held-out label, nothing selected."""
from ml_porosity.volve.training import method_spec, train_trajectory
root, sa, label = outputs_dir() / "p4" / "benchmark", p["registration"]["sigma_a_ms"], p["data"]["label"]
sets = fold_sets(p)
names = sets[0]
stamp = current_stamp(p) | {"benchmark_only": True}
registration_worker(dict(p=p, root=str(root), device=device, names=list(names), sa=sa,
key=fingerprint(stamp, stage="registration", names=list(names), sa=sa)))
seconds = json.loads(reg_path(root, names, sa).with_suffix(".json").read_text(encoding="utf-8"))["wall_seconds"]
data = VolveData(p, training_wells=names)
bundle = load_bundle(reg_path(root, names, sa))
X = np.stack([data.X(w, "reference") for w in names])
X_targets = np.stack([data.X(w, k) for w, k in prediction_targets(data.wells, names)])
per_step = {m: train_trajectory(X, X_targets, method_spec(bundle, label, m), m, p["training"], 0, [steps], device,
None, p["runtime"]["cpu_threads_per_worker"])[1]["seconds_per_step"]
for m in ("B3b", "M2-Sa")}
# Registration cost grows with the number of wells; the largest set gives the training-step upper bound.
reg_primary = seconds * sum(len(s) for s in sets) / len(names)
n_sens = len(p["registration"]["sigma_a_sensitivity_ms"])
steps_per_job = max(p["training"]["budgets"]) * max(per_step.values())
jobs = {"primary": len(sets) * len(p["methods"]["main"]) * len(p["split"]["seeds"]),
"sensitivity": len(sets) * len(p["registration"]["sensitivity_methods"]) * len(p["split"]["seeds"]) * n_sens}
out = {"device": device, "training_wells": list(names), "registration_seconds_largest_set": seconds,
"seconds_per_step": per_step, "registration_jobs": {"primary": len(sets), "sensitivity": len(sets) * n_sens},
"training_jobs": jobs,
"sequential_seconds": {"registration_primary": reg_primary, "registration_sensitivity": reg_primary * n_sens,
"training_primary": jobs["primary"] * steps_per_job,
"training_sensitivity": jobs["sensitivity"] * steps_per_job},
"note": "One-worker extrapolation from one real training set; parallel workers on one GPU speed this up "
"sublinearly. Not a confidence interval."}
write_json(outputs_dir() / "p4" / "benchmark.json", out)
return out
def run(stage: str, p: dict, device: str, workers: int, smoke: bool = False, arms: str = "primary") -> None:
root = outputs_dir() / "p4"
if smoke:
if arms != "primary":
raise ValueError("Smoke runs use the primary σ_a arm only")
p = smoke_protocol(p)
root = root / "smoke"
if stage == "summarize":
# Scores held-out PHIF: only once the design is frozen.
stamp = freeze(check=True) | {"smoke": p}
else:
stamp = current_stamp() | {"smoke": p, "unlocked_draft": True}
else:
stamp = freeze(check=True)
if stage == "register":
run_jobs(registration_jobs(p, stamp, root, device, arms), registration_worker, workers, stage)
elif stage == "train":
run_jobs(training_jobs(p, stamp, root, device, arms), training_worker, workers, stage)
elif stage == "summarize":
from ml_porosity.volve.evaluation import summarize
# The G-D report always needs the primary arm.
summarize(p, root, sigma_arms(p, "primary" if arms == "primary" else "all"))
else:
raise ValueError(stage)

View File

@@ -0,0 +1,87 @@
"""P4 trajectories: masked bank losses, a checkpoint at every registered budget, no held-out label.
Mirrors ml_porosity.f3.training.train_trajectory for the bank methods (same model, optimiser, seeding and
checkpoints); the loss is volve.losses.masked_bank_loss on the label support of each bank member (finite samples).
"""
from __future__ import annotations
import time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from ml_porosity.f3.training import ensemble, make_model
from ml_porosity.models.bank_train import window_starts_fixed
from ml_porosity.models.train import predict
from ml_porosity.volve.losses import masked_bank_loss
__all__ = ["ensemble", "method_spec", "train_trajectory"]
def method_spec(bundle: dict, label: str, method: str) -> dict:
"""Normalised bank (NaN outside each member's label support), log prior weights, the member support masks
(B, S, L) and λ. Single-member banks reduce to the masked Gaussian NLL for any λ."""
m0, s0 = bundle[f"{label}/norm"]
Y = bundle[f"{label}/{method}"]
lp = bundle.get(f"{label}/{method}/logpi", np.full(Y.shape[:2], -np.log(Y.shape[1])))
if lp.shape != Y.shape[:2]:
raise ValueError(f"Bank weights do not match the bank: {label}/{method}")
if np.isinf(Y).any():
raise ValueError(f"Label bank is not finite on its support: {label}/{method}")
mask = np.isfinite(Y)
if not mask.any(axis=2).all():
raise ValueError(f"A bank member has no label support: {label}/{method}")
return dict(Y=(Y - m0) / s0, logpi=lp, mask=mask, lam=float(bundle[f"{label}/lambda"]))
def train_trajectory(X, X_targets, spec: dict, method: str, cfg: dict, seed: int, budgets: list[int],
device: str, checkpoint: Path | None = None, threads: int = 2) -> tuple[dict, dict]:
torch.set_num_threads(threads)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.default_generator.manual_seed(seed)
if torch.device(device).type == "cuda":
torch.cuda.set_device(device)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
tensor = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
x, y, logpi = tensor(X), tensor(spec["Y"]), tensor(spec["logpi"])
mask = torch.as_tensor(np.asarray(spec["mask"], bool), device=device)
N, _, L = X.shape
win = cfg["window_samples"]
starts = torch.as_tensor(np.tile(window_starts_fixed(L, win, cfg["window_step"]), (N, 1)), device=device)
model = make_model(method, X.shape[1], cfg).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
outputs, states = {}, {}
if torch.device(device).type == "cuda":
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
begin = time.perf_counter()
for step in range(1, max(budgets) + 1):
model.train()
opt.zero_grad(set_to_none=True)
mu, sigma = model(x)
loss = masked_bank_loss(mu[:, 0], sigma[:, 0], y, logpi, mask, starts, win, spec["lam"])
if not torch.isfinite(loss):
raise FloatingPointError(f"Non-finite loss in {method}, step {step}")
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
opt.step()
if step in budgets:
m, s = predict(model, X_targets, device)
outputs[f"{step}/mu"], outputs[f"{step}/sigma"] = m, s
if checkpoint is not None:
states[step] = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
if torch.device(device).type == "cuda":
torch.cuda.synchronize()
elapsed = time.perf_counter() - begin
if checkpoint is not None:
tmp = checkpoint.with_suffix(".pt.tmp")
torch.save({"states": states, "method": method, "channels": X.shape[1], "config": cfg}, tmp)
tmp.replace(checkpoint)
return outputs, {"wall_seconds": elapsed, "steps": max(budgets), "seconds_per_step": elapsed / max(budgets),
"parameters": sum(v.numel() for v in model.parameters()),
"peak_vram_bytes": torch.cuda.max_memory_allocated() if torch.device(device).type == "cuda" else 0}

View File

@@ -0,0 +1,61 @@
"""Audit P3 completion and data integrity without changing scientific outputs."""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
from ml_porosity.f3.progress import write_json
from ml_porosity.f3.protocol import freeze, load_protocol
from ml_porosity.f3.runner import job_path, reg_path, registration_jobs, reusable, training_jobs
from ml_porosity.paths import outputs_dir
def main():
stamp, p = freeze(check=True), load_protocol()
root = outputs_dir()/'p3'
jobs = training_jobs(p, stamp, root, 'cuda:0')
assert len(jobs) == 1320
for job in jobs:
path = job_path(root, job['names'], job['method'], job['label'], job['seed'], job['sa'])
assert reusable(path, job['key']), str(path)
registrations = registration_jobs(p, stamp, root, 'cuda:0')
registrations += registration_jobs(p, stamp, root, 'cuda:0', deployment=True)
for job in registrations:
path = reg_path(root, job['names'], job['sa'], job['no_anchors'])
assert reusable(path, job['key']), str(path)
meta = json.loads((root/'volume/metadata.json').read_text(encoding='utf-8'))
assert meta['shape'] == [651, 951, 126]
assert meta['members'] == 20 and not meta['sections_only'] and not meta['pilot']
state = json.loads((root/'volume/state.json').read_text(encoding='utf-8'))
assert sorted(state['completed_ilines']) == list(range(1, 650))
stats = {}
for name in ('mean', 'sigma'):
arr = np.load(root/f'volume/{name}.npy', mmap_mode='r')
assert list(arr.shape) == meta['shape'] and arr.dtype == np.float32
assert all(np.isnan(edge).all() for edge in (arr[0], arr[-1], arr[:, 0], arr[:, -1]))
low, high = float('inf'), float('-inf')
for i in range(1, len(arr)-1):
values = arr[i, 1:-1]
assert np.isfinite(values).all(), f'{name}: nonfinite interior row {i}'
low, high = min(low, float(values.min())), max(high, float(values.max()))
if name == 'sigma':
assert low >= 0
stats[name] = {'shape': list(arr.shape), 'interior_finite_values': 649*949*126,
'minimum_fraction': low, 'maximum_fraction': high,
'one_trace_border_all_nan': True}
recovery = json.loads((root/'volume_recovery.json').read_text(encoding='utf-8'))
assert recovery['status'] == 'complete' and recovery['completed_rows_preserved'] and recovery['gate_preserved']
result = {'status': 'passed', 'protocol_sha256': stamp['protocol_sha256'],
'frozen_code_data_environment_and_protected_artifacts': 'match',
'verified_lowo_prediction_checkpoint_pairs': len(jobs),
'verified_registration_bundles': len(registrations),
'completed_volume_inlines': 649, 'volume': stats,
'gate': json.loads((root/'summary/gate_gc.json').read_text(encoding='utf-8'))}
write_json(root/'completion_checks.json', result)
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,108 @@
"""Resume frozen P3 inference, tolerating transient locks on dashboard files only.
This post-run operational adapter changes no registered source, protocol,
checkpoint, prediction formula, or gate. The original WinError 5 is retained in
the failed run log. Completed volume rows are checked for bytewise preservation.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
import time
from datetime import datetime
from pathlib import Path
for key in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMBA_NUM_THREADS'):
os.environ.setdefault(key, '2')
os.environ.setdefault('PYTHONUTF8', '1')
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
def row_digest(root: Path, rows: list[int]) -> str:
import numpy as np
h = hashlib.sha256()
for name in ('mean.npy', 'sigma.npy'):
arr = np.load(root/name, mmap_mode='r')
for i in rows:
h.update(arr[i].tobytes())
return h.hexdigest()
def main() -> None:
from ml_porosity.f3 import progress
from ml_porosity.f3.protocol import digest, freeze, load_protocol
from ml_porosity.paths import outputs_dir
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--device', default='cuda:0')
args = parser.parse_args()
stamp = freeze(check=True)
root = outputs_dir()/'p3'
rows = json.loads((root/'volume/state.json').read_text(encoding='utf-8'))['completed_ilines']
before = row_digest(root/'volume', rows)
gate_digest = digest(root/'summary/gate_gc.json')
original_update = progress.update
retry_events = []
dashboard_targets = {(root/n).resolve() for n in ('progress.json', 'progress.js')}
def resilient_update(**values):
for attempt in range(8):
try:
return original_update(**values)
except PermissionError as exc:
destination = getattr(exc, 'filename2', None) or exc.filename
if destination is None or Path(destination).resolve() not in dashboard_targets:
raise
retry_events.append({'time': datetime.now().astimezone().isoformat(),
'attempt': attempt+1, 'error': str(exc)})
time.sleep(0.05*2**min(attempt, 4))
# The JSON is authoritative. An unavailable UI sidecar must not abort
# scientific inference; the next inline attempts publication again.
print('Dashboard file remains locked; defer UI publication to the next update.', file=sys.stderr, flush=True)
return json.loads((root/'progress.json').read_text(encoding='utf-8'))
progress.update = resilient_update
record = {'started_local': datetime.now().astimezone().isoformat(timespec='seconds'),
'original_failed_run': 'logs/runs/20261028-001548_p3_all',
'reason': 'Windows denied atomic replacement of progress.js after 132 inlines.',
'adapter_sha256': digest(Path(__file__)),
'registered_code_sha256': stamp['code_sha256'],
'protocol_sha256': stamp['protocol_sha256'],
'completed_rows_before': len(rows), 'completed_rows_digest_before': before,
'gate_sha256_before': gate_digest, 'dashboard_retry_events': retry_events,
'scientific_change': False, 'status': 'running'}
progress.write_json(root/'volume_recovery.json', record)
if os.name == 'nt':
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
try:
resilient_update(status='Đang tiếp tục volume', error=None, eta_seconds=None,
message='Giữ nguyên mô hình và protocol; retry lỗi khóa file dashboard trên Windows.',
tasks={'p3-vol': 'doing'})
# Import after installing the operational publisher, so the frozen
# inference function receives the wrapper without editing its source.
from ml_porosity.f3.volume import predict_volume
predict_volume(load_protocol(), args.device)
assert row_digest(root/'volume', rows) == before, 'Previously completed rows changed'
assert digest(root/'summary/gate_gc.json') == gate_digest, 'G-C verdict changed'
freeze(check=True)
record |= {'status': 'complete', 'completed_rows_preserved': True,
'gate_preserved': True, 'frozen_code_data_environment_match': True}
resilient_update(status='P3 đã hoàn tất', error=None, eta_seconds=None,
message='LOWO, ablation, diagnostics và volume đầy đủ đã xong. G-C không đạt; không đổi ngưỡng hoặc khoảng bất định.')
print('Full volume complete. Original rows, G-C and frozen code/data are preserved.', flush=True)
except Exception as exc:
record |= {'status': 'failed', 'error': str(exc)}
raise
finally:
record['finished_local'] = datetime.now().astimezone().isoformat(timespec='seconds')
progress.write_json(root/'volume_recovery.json', record)
if os.name == 'nt':
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
if __name__ == '__main__':
main()

8
paper/.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
*.aux
*.bbl
*.blg
*.log
*.out
*.toc
*.synctex.gz
main.pdf

61
paper/README.md Normal file
View File

@@ -0,0 +1,61 @@
# Manuscript draft
Build (no latexmk on the server):
```
pdflatex main && bibtex main && pdflatex main && pdflatex main
```
Red text (`\todo`, `\todoblock`, `\figplaceholder`) marks parts that are not ready.
Search for them with `grep -n 'todo\|figplaceholder' sections/*.tex`.
All figures in `figures/` are produced by `python scripts/22_paper_figures.py` (from the repo root,
with the `.venv`); it reads only the locked summaries listed below.
## Where the numbers come from
| Paper element | Source |
|---|---|
| Abstract, Sec. 1 (findings paragraph), Sec. 8, `highlights.txt` | Rows below: H2a and σ_a from `tab:h2a`/`tab:sigmaa`; bank gain and bounds (registered (a), post hoc (b)) from `tab:h2b` and `outputs/p2r/posthoc/{bound.csv,meta.json}`; wells needed from `outputs/t3/nstar.csv`; field results from App. B; Teapot counts from Sec. 6.6 sources |
| Sec. 1 (F3 drift 14–66 ms, 46 ms, 36 ms; dominant period 17–20 ms) | `outputs/td_qc.csv`, `outputs/tie_qc.csv`, `docs/plan.md` §1.2 |
| Sec. 2 (label noise and errors in variables; Table `tab:positioning`) | `refs.bib` `annote` fields: Mnih & Hinton (2012) read in full on 2026-10-29 (Secs. 5, 6.1, 6.3); Balakrishnan (1962) metadata from Crossref only, cited for the general statement; abstract-only entries flagged in the table |
| Sec. 3, Table `tab:audit` (TD drift, label audit) | `outputs/td_qc.csv`, `outputs/tie_qc.csv`, `outputs/marker_vs_horizon.csv`, `docs/plan.md` |
| Sec. 3.3 (Volve data: licence, label check, deviated wells, cube, time–depth, anchors, labels) | `outputs/volve/volve_wells_summary.json`, `outputs/volve/{summary.json,anchors.csv,pick_vs_horizon.csv,pick_vs_checkshot.csv,horizon_lag.csv}`, `docs/research/volve-inventory.md`, `docs/plan.md` §12 items 7 and 18 |
| Sec. 4, Table `tab:h1`, Fig. `fig:h1` | `outputs/p2/summary/main/h1.csv`, `docs/theory.md` |
| Sec. 4.3–4.5 (Propositions 3–6, Corollaries 3–4, Remark 1, ρ*) | Analytic; proofs in App. A; Vietnamese statements in `docs/theory.md` §6. The factors 1.10 and 1.77 are e^{4π²σ²f²} at σ = 2 ms, f = 25 and 60 Hz (`meta.json` `transfer_ratio_exp_4pi2s2f2`); 71–73% coherent power below 25 Hz, the 67–72 Hz f⁴-weighted median and the (b)/(a) integral ratios 1.5–1.7, 2.1–2.6 and 3.3–4.6 are from `outputs/p2r/posthoc/meta.json` `n16_spectra` (coherent part: `coherent_share_below_25hz`, `f4_weighted_median_hz.coherent`; integral ratios span the Oracle and coherent spectra over the five regimes); 30–90 Hz uses the ~60 Hz F3 peak of Sec. 3.1 |
| Sec. 5 (prior fit on F3, LOAO, type-II σ_a) | `docs/plan.md` §12, `docs/theory.md` |
| Sec. 6.1, Table `tab:p2`, Fig. `fig:p2phase` | `outputs/p2/summary/main/{summary.md,methods.csv}` |
| Sec. 6.2 (diagnosis, deviation) | `docs/plan.md` §12 items 11–14 |
| Sec. 6.3, Tables `tab:h2a`, `tab:sigmaa`, `tab:h2b`; Figs. `fig:h2b`, `fig:p2rgrid` | `outputs/p2r/summary/{summary.md,verdict.json}`; σ_post and warp RMSE from `outputs/p2r/summary/sigma_post.csv` |
| Sec. 6.3, column 1/B_b of `tab:h2b` (Berkson bound at σ_post; bounds at the warp error; 60 Hz and cross-spectral variants; exact (a) bound 0.481 at σ_post for R10tb c = 2; Oracle/B3d-Sa ratios; share of the gap closed; 6 ms grid edge; post hoc) | `outputs/p2r/posthoc/{bound.csv,blur_ab.csv,meta.json}` (counts in `meta.json` `n16_wide`), written by `python scripts/31_p2r_posthoc.py` (about 6 min) from the registered summaries and the Oracle test predictions in `outputs/p2r/train/<regime>/cells/*.npz` |
| Sec. 6.3, Table `tab:t4` (dispersion ratio ξ, coverage, training length; post hoc) | `outputs/t4/{summary.csv,cells.csv,budget_dev.csv,meta.json}` (column `kappa` = ξ), written by `python scripts/30_t4_coverage.py` |
| Sec. 6.4 (mechanism) | Not run yet: T2, to be declared in `docs/research/t2-mechanism.md` |
| Sec. 6.5, Table `tab:t3` (detectability; exploratory) | `outputs/t3/{cells.csv,nstar.csv,power.csv,meta.json}`, written by `python scripts/27_t3_power.py`; declaration and Deviation 1 (σ_ref grid) in `docs/research/applicability-teapot.md` |
| Sec. 6.6 (gate results) | App. B sources below |
| Sec. 6.6 (conditions C1–C4) | `outputs/applicability/{verdict.json,c1_pairs.csv,c2_sigma_post.csv,d2_threshold_cells.csv}`, written by `python scripts/26_applicability.py`; `docs/research/applicability-results.md` |
| Sec. 6.6 (Teapot: 152 wells, time–depth tables, horizon–top reference, σ̂_knot 6.75 ms) | `outputs/teapot/inventory/` (`python -P scripts/28_teapot_inventory.py`), `outputs/teapot/pilot_pa/verdict.json` and `knots_dev.csv` (`python -P scripts/29_teapot_pilot.py`), `docs/research/applicability-results.md`, `docs/plan.md` §12 item 23 |
| Sec. 7 (F3 and Volve paragraphs, σ_a, limitations) | same sources as App. B |
| App. B.1, Table `tab:p1` | `outputs/p1/summary.md` |
| App. B.1, Table `tab:f3gc` (G-C), macro band RMSE | `outputs/p3/summary/gate_gc.json`, `docs/plan.md` §12 item 16 |
| App. B.1, Table `tab:f3gc` coverage, seed-by-seed spread | `outputs/p3/summary/{metrics.csv,selection.csv}` (rows with `seed` = ensemble and per seed) |
| App. B.1, Tables `tab:f3all`, `tab:f3abl` | `outputs/p3/summary/macro.csv` (label `PHIE_DT`, σ_a = 7 ms); ablation descriptions from `configs/protocol_f3.yaml` and `ml_porosity/f3/{training,registration,runner}.py` |
| App. B.1, `tab:f3all` last row ("No band content", post hoc) | RMS over each test well of the 6 Hz high-pass (`split_bands`) marker-calibrated `PHIE_DT` reference (via `F3Data`), macro over wells = 1.224 p.u.; computed after the run, scale only |
| App. B.1, Table `tab:f3sens` | `metrics.csv` (`M2-Sa` vs `B3d-Sa`; σ_a arms vs `B3c-R` at the same σ_a; reference `wlt`; label `PHIE`), `band_sensitivity.csv` (f_c = 5, 8 Hz), `posterior_reference_sensitivity.csv` (5–95 % range over 64 reference warps) |
| App. B.1 (posterior width, phase) | `outputs/p3/registration/*_sa{3.5,7,14}{,_noanchors}.json` (`diagnostics[].sigma_post_ms`, `phase_R`, `phase_info.logZ` summed over wells) |
| App. B.1 (leave-one-anchor-out) | `outputs/p3/diagnostics/loao.csv` |
| App. B.1 (volume statistics), Fig. `fig:f3vol` | `outputs/p3/volume/{metadata.json,mean.npy,sigma.npy}`; figure from `python scripts/22_paper_figures.py --only f3_volume` (inline 442 through F03-4) |
| App. B.2, Table `tab:volvegd` (G-D) | `outputs/p4/summary/gate_gd.json` (`schemes.<scheme>.per_well`: competitor, n, ratio, coverage; macro counts and coverage) |
| App. B.2, Table `tab:volveall` | `outputs/p4/summary/macro.csv` (reference calibrated, σ_a = 7 ms, ensemble); last row ("Constant", post hoc) from `outputs/p4/posthoc/macro.csv` (`const_rmse`), written by `python scripts/25_p4_posthoc.py` after G-D, scale only |
| App. B.2, Table `tab:volvesens` | `outputs/p4/summary/{metrics.csv,macro.csv}` (σ_a arms; `M2-Sa` vs `B3c-R` at the same σ_a) |
| App. B.2 (bias split, within-well SD, constant vs networks per well) | `outputs/p4/posthoc/wells.csv` (post hoc) |
| App. B.2 (best-shift diagnostic) | `outputs/p4/summary/best_shift_DIAGNOSTIC_ONLY.csv` (never alters a score; search limit `best_shift_max_samples` = 16 in the protocol) |
| App. B.2 (posterior width, phase) | `outputs/p4/summary/registration.csv` |
| App. B.2 (deviations), Sec. 7 (Volve paragraphs) | `configs/protocol_volve.yaml` (`deviations`), `configs/protocol_volve.lock.json`, `docs/plan.md` §12 items 19–21 |
| Pass rules, thresholds | `configs/protocol_p2.yaml`, `configs/protocol_p2r.yaml`, `configs/protocol_f3.yaml` (locked; tag `protocol-f3`), `configs/protocol_volve.yaml` (locked 2026-10-29 01:17:42 UTC; committed on 2026-10-29 after the run, tag `protocol-volve`) |
Do not copy numbers from `code_thesis/` (thesis archive) into the paper. P4x was dropped on 29/10/2026 (Pivot 1, `docs/plan.md` §12 item 22): nothing from `outputs/p4x/` or `docs/research/p4-exploratory.md` enters the paper.
Wording must respect `docs/plan.md` §10 (forbidden claims).
Length: Computers & Geosciences limits a Research Article to about 5,500 words excluding abstract, keywords, highlights,
references and captions (secondary source; the official Guide for Authors page could not be fetched on 2026-10-29).
The main text (Secs. 1–8) is about 14,750 words (crude count), and exceeds that limit. The length pass was dropped by the user on 2026-10-29 (`docs/plan.md` §12 item 25).

BIN
paper/figures/f3_volume.pdf Normal file

Binary file not shown.

BIN
paper/figures/p2_h1.pdf Normal file

Binary file not shown.

BIN
paper/figures/p2_phase.pdf Normal file

Binary file not shown.

BIN
paper/figures/p2r_grid.pdf Normal file

Binary file not shown.

BIN
paper/figures/p2r_h2b.pdf Normal file

Binary file not shown.

BIN
paper/figures/td_drift.pdf Normal file

Binary file not shown.

5
paper/highlights.txt Normal file
View File

@@ -0,0 +1,5 @@
Well-tie error in training labels is an error in the time index of the label
Misregistered labels blur the learned predictor; Berkson-type tie error sharpens it
A calibrated posterior bank recovers the oracle optimum; its gain is fourth order
Tie-posterior label gains on the benchmark fail if anchor error is misset twofold
Blind-well tests need references accurate to ~1 ms; tested public datasets lack them

84
paper/main.tex Normal file
View File

@@ -0,0 +1,84 @@
% Draft manuscript. Build: pdflatex main && bibtex main && pdflatex main && pdflatex main
% Red text marks parts that are not ready (results pending, figures missing, checks to do).
% Every number in this draft comes from outputs/*/summary* or docs/plan.md; see paper/README.md.
\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\IfFileExists{lmodern.sty}{\usepackage{lmodern}}{}
\usepackage[margin=2.5cm]{geometry}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{bm}
\usepackage{graphicx}
\usepackage{booktabs}
\usepackage{multirow}
\usepackage{array}
\usepackage{xcolor}
\usepackage{caption}
\usepackage[authoryear,round]{natbib}
\usepackage[colorlinks=true,linkcolor=blue!50!black,citecolor=blue!50!black,urlcolor=blue!50!black]{hyperref}
\usepackage{setspace}
\onehalfspacing
\graphicspath{{figures/}}
% ---------------------------------------------------------------------------
% Red notes for unfinished parts
\newcommand{\todo}[1]{\textcolor{red}{[TODO: #1]}}
\newcommand{\todoblock}[1]{%
\par\smallskip\noindent
\fcolorbox{red}{red!6}{\parbox{\dimexpr\linewidth-2\fboxsep-2\fboxrule}{\color{red}\textbf{TODO.} #1}}%
\par\smallskip}
\newcommand{\figplaceholder}[1]{%
\fcolorbox{red}{red!6}{\parbox[c][4.5cm][c]{0.9\linewidth}{\centering\color{red}\textbf{Figure not ready.}\\[2pt] #1}}}
% ---------------------------------------------------------------------------
% Notation
\newcommand{\E}{\mathbb{E}}
\newcommand{\Var}{\operatorname{Var}}
\newcommand{\Cov}{\operatorname{Cov}}
\newcommand{\sd}{\operatorname{sd}}
\newcommand{\PCC}{\operatorname{PCC}}
\newcommand{\RML}{\mathrm{RML}}
\newcommand{\N}{\mathcal{N}}
\newcommand{\dd}{\,\mathrm{d}}
\newcommand{\aaf}{\mathcal{A}} % anti-alias filter
\newcommand{\sigpost}{\sigma_{\mathrm{post}}}
% Method names (repository codes); change here to rename everywhere
\newcommand{\mPM}{B3d-Sa} % labels at the SMC posterior-mean warp
\newcommand{\mRML}{M2-Sa} % RML on the SMC particle bank
\theoremstyle{plain}
\newtheorem{proposition}{Proposition}
\newtheorem{lemma}{Lemma}
\newtheorem{corollary}{Corollary}
\theoremstyle{remark}
\newtheorem{remark}{Remark}
\title{Label registration error in sparse-well seismic property learning: theory, a registration-aware benchmark, and the limits of field validation\\[4pt]
\normalsize\todo{If S2 of \texttt{protocol\_bench} is not locked and run before submission, replace ``a registration-aware benchmark'' with ``a controlled synthetic study'' in the title, abstract and text.}}
\author{\todo{author list, affiliations, ORCID, corresponding author}}
\date{Draft, \today}
\begin{document}
\maketitle
\input{sections/00_abstract}
\input{sections/01_introduction}
\input{sections/02_related}
\input{sections/03_data}
\input{sections/04_theory}
\input{sections/05_method}
\input{sections/06_experiments}
\input{sections/07_discussion}
\input{sections/08_conclusion}
\bibliographystyle{plainnat}
\bibliography{refs}
\appendix
\input{sections/A_proofs}
\input{sections/B_field}
\end{document}

629
paper/refs.bib Normal file
View File

@@ -0,0 +1,629 @@
% Selective ML-Porosity survey; cutoff 2026-10-23.
% F = relevant full-text sections inspected; A = original abstract/metadata only.
% These entries are bibliographic records, not evidence of reproduced experiments.
@article{prabowo2025f3,
author = {Prabowo, Urip Nurwijayanto and Sudarmaji and Setyowiyoto, Jarot and Sismanto},
title = {{Comparison of Porosity Prediction from Seismic Data in the F3 Block, Netherlands using Machine Learning}},
journal = {Rudarsko-geološko-naftni zbornik},
year = {2025},
volume = {40},
number = {2},
pages = {15--26},
doi = {10.17794/rgn.2025.2.2},
url = {https://doi.org/10.17794/rgn.2025.2.2},
annote = {P01; survey evidence level F; accessed 2026-10-23}
}
@article{tao2025structural,
author = {Tao, Bo-Cheng and Zhou, Huai-Lai and Wu, Wen-Yue and Zhang, Gan and Liu, Bing and Liu, Xing-Ye},
title = {{Porosity prediction based on improved structural modeling deep learning method guided by petrophysical information}},
journal = {Petroleum Science},
year = {2025},
volume = {22},
pages = {2325--2338},
doi = {10.1016/j.petsci.2025.03.035},
url = {https://doi.org/10.1016/j.petsci.2025.03.035},
annote = {P02; survey evidence level F; accessed 2026-10-23}
}
@article{xu2024sts,
author = {Xu, Minghui and Zhao, Luanxiao and Liu, Jingyu and Geng, Jianhua},
title = {{Enhancing seismic porosity estimation through 3D sequence-to-sequence deep learning with data augmentation, spatial constraints, and geologic constraints}},
journal = {Geophysics},
year = {2024},
volume = {89},
number = {4},
pages = {M93--M108},
doi = {10.1190/geo2023-0614.1},
url = {https://doi.org/10.1190/geo2023-0614.1},
annote = {P03; survey evidence level A; full text added 2026-10-26 (refs/xu2024sts.pdf): labels matched to seismic with time-depth from well-to-seismic ties taken as given; carbonate reservoir, 48 wells}
}
@article{chen2024multidimensional,
author = {Chen, Hongling and Wu, Baohai and Sacchi, Mauricio D. and Wang, Zhiqiang and Gao, Jinghuai},
title = {{Multidimensional Petrophysical Seismic Inversion Based on Knowledge-Driven Semi-Supervised Deep Learning}},
journal = {IEEE Transactions on Geoscience and Remote Sensing},
year = {2024},
volume = {62},
pages = {1--15},
doi = {10.1109/TGRS.2024.3460184},
url = {https://doi.org/10.1109/TGRS.2024.3460184},
annote = {P04; survey evidence level A; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
}
@article{li2024bpinn,
author = {Li, Peng and Grana, Dario and Liu, Mingliang},
title = {{Bayesian neural network and Bayesian physics-informed neural network via variational inference for seismic petrophysical inversion}},
journal = {Geophysics},
year = {2024},
volume = {89},
number = {6},
pages = {M185--M196},
doi = {10.1190/geo2023-0737.1},
url = {https://doi.org/10.1190/geo2023-0737.1},
annote = {P05; survey evidence level A; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
}
@article{ntibahanana2024ensemble,
author = {Ntibahanana, M. and Jianguo, S. and Luemba, M. and Tondozi, K. and Imani, G. and Mohamed, B.},
title = {{Ensemble of Neural Networks Utilizing Seismic Attributes for Rock‐Property Inversion With Uncertainty Estimation}},
journal = {Earth and Space Science},
year = {2024},
volume = {11},
number = {6},
eid = {e2023EA003101},
doi = {10.1029/2023EA003101},
url = {https://doi.org/10.1029/2023EA003101},
annote = {P06; survey evidence level F; accessed 2026-10-23}
}
@article{di2023welltie,
author = {Di, Haibin and Abubakar, Aria},
title = {{Automating seismic‐well tie via self‐supervised learning}},
journal = {Geophysical Prospecting},
year = {2023},
volume = {71},
number = {4},
pages = {698--712},
doi = {10.1111/1365-2478.13333},
url = {https://doi.org/10.1111/1365-2478.13333},
annote = {P07; survey evidence level F; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
}
@article{li2025cascadedtie,
author = {Li, Mengcheng and Huang, Xuri and Cao, Weiping and Wo, Yukai and Xu, Minghua and Ren, Mengyu and Lu, Shunkang},
title = {{Automatic seismic-well tie based on cascaded matching optimization method}},
journal = {Frontiers in Earth Science},
year = {2025},
volume = {13},
eid = {1547087},
doi = {10.3389/feart.2025.1547087},
url = {https://doi.org/10.3389/feart.2025.1547087},
annote = {P08; survey evidence level F; accessed 2026-10-23}
}
@article{dou2024seismae,
author = {Dou, Yimin and Li, Kewen},
title = {{3D seismic mask auto encoder: Seismic inversion using transformer-based reconstruction representation learning}},
journal = {Computers and Geotechnics},
year = {2024},
volume = {169},
pages = {106194},
eid = {106194},
doi = {10.1016/j.compgeo.2024.106194},
url = {https://doi.org/10.1016/j.compgeo.2024.106194},
annote = {P09; survey evidence level A; accessed 2026-10-23; full text not obtainable (confirmed 2026-10-28): cite as abstract-only}
}
@article{li2026leakage,
author = {Li, Zhibin and Liu, Jingxian and Li, Xuece and He, Tongtong and Li, Kangning and Zhang, Yuanning and Pan, Zhongkui and Lei, Xiangjun and Wang, Shuheng and Zhang, Zhaojia},
title = {{Leakage-aware full-section evaluation and label-efficient semi-supervised seismic facies segmentation for subsurface geological modeling}},
journal = {Frontiers in Earth Science},
year = {2026},
volume = {14},
eid = {1910345},
doi = {10.3389/feart.2026.1910345},
url = {https://doi.org/10.3389/feart.2026.1910345},
annote = {P10; survey evidence level F; accessed 2026-10-23}
}
@article{rezaei2026krigingrf,
author = {Rezaei, Mohammadali and La Croix, Andrew D. and Emami Niri, Mohammad and Asghari, Omid},
title = {{Seismic Porosity Estimation Using Geologically-Informed Seismic Attributes and a Kriging-Enhanced Random Forest: Application to a Shallow-Marine Carbonate Reservoir}},
journal = {Natural Resources Research},
year = {2026},
doi = {10.1007/s11053-026-10694-z},
url = {https://doi.org/10.1007/s11053-026-10694-z},
annote = {P11; survey evidence level F; accessed 2026-10-23}
}
@article{sukar2026uncertainty,
author = {Sukar, Boshara and Côrte, Gustavo and MacBeth, Colin},
title = {{Dynamic Reservoir Property Estimation With Uncertainty Quantification From 4D Seismic Data Using Bayesian Neural Networks}},
journal = {Geophysical Prospecting},
year = {2026},
volume = {74},
number = {6},
eid = {e70228},
doi = {10.1111/1365-2478.70228},
url = {https://doi.org/10.1111/1365-2478.70228},
annote = {P12; survey evidence level F; accessed 2026-10-23}
}
@article{liu2023lowfrequency,
author = {Liu, Jingyu and Zhao, Luanxiao and Xu, Minghui and Zhao, Xiangyuan and You, Yuchun and Geng, Jianhua},
title = {{Porosity prediction from prestack seismic data via deep learning: incorporating a low-frequency porosity model}},
journal = {Journal of Geophysics and Engineering},
year = {2023},
volume = {20},
number = {5},
pages = {1016--1029},
doi = {10.1093/jge/gxad063},
url = {https://doi.org/10.1093/jge/gxad063},
annote = {P13; survey evidence level A; accessed 2026-10-23}
}
@article{corrales2024seis2rock,
author = {Corrales, M. and Hoteit, H. and Ravasi, M.},
title = {{Seis2Rock: A Data-Driven Approach to Direct Petrophysical Inversion of Pre-Stack Seismic Data}},
journal = {Earth and Space Science},
year = {2024},
volume = {11},
number = {2},
eid = {e2023EA003301},
doi = {10.1029/2023EA003301},
url = {https://doi.org/10.1029/2023EA003301},
annote = {P14; survey evidence level F; accessed 2026-10-23}
}
@misc{vashisth2022rwpinn,
author = {Vashisth, Divakar and Mukerji, Tapan},
title = {{Direct Estimation of Porosity from Seismic Data using Rock and Wave Physics Informed Neural Networks (RW-PINN)}},
year = {2022},
eprint = {2210.00042},
archivePrefix = {arXiv},
primaryClass = {physics.geo-ph},
url = {https://arxiv.org/abs/2210.00042},
annote = {P15; survey uses this arXiv version as a background paper; relevant full-text sections inspected; accessed 2026-10-23}
}
% --- Added 2026-10-26 from docs/plan.md section 11. Full text is in refs/ for every entry below.
% DOI, volume and pages from Crossref (journal articles) or the arXiv/PMLR record (ML papers).
% Not included (no full text, or no verifiable record): White & Simm 2003,
% Herrera & van der Baan 2014 (journal version), Munoz & Hale 2015, RING 2025, EAGE 2023 (skipped: not found or not obtainable).
@article{buland2003bayesianwavelet,
author = {Buland, Arild and Omre, Henning},
title = {{Bayesian wavelet estimation from seismic and well data}},
journal = {Geophysics},
year = {2003},
volume = {68},
number = {6},
pages = {2000--2009},
doi = {10.1190/1.1635053},
url = {https://doi.org/10.1190/1.1635053},
annote = {Full text read; marker mistie modeled as latent time shifts with a triangular prior, estimated jointly with the wavelet by MCMC; refs/buland2003bayesianwavelet.pdf}
}
@article{gunning2006waveletextractor,
author = {Gunning, James and Glinsky, Michael E.},
title = {{Wavelet extractor: A Bayesian well-tie and wavelet extraction program}},
journal = {Computers \& Geosciences},
year = {2006},
volume = {32},
pages = {681--695},
doi = {10.1016/j.cageo.2005.10.001},
url = {https://doi.org/10.1016/j.cageo.2005.10.001},
annote = {Full text read (added 2026-10-26); MAP estimate of wavelet jointly with checkshot/marker times (Gaussian prior), registration shift and lateral positioning error per well, Laplace posterior, wavelet span by marginal likelihood; refs/gunning2006waveletextractor.pdf}
}
@article{wu2017multiwelltie,
author = {Wu, Xinming and Caumon, Guillaume},
title = {{Simultaneous multiple well-seismic ties using flattened synthetic and real seismograms}},
journal = {Geophysics},
year = {2017},
volume = {82},
number = {1},
pages = {IM13--IM20},
doi = {10.1190/geo2016-0295.1},
url = {https://doi.org/10.1190/geo2016-0295.1},
annote = {Full text read (HAL version, refs/wu2017multiwelltie.pdf); first published online 2016-11-09}
}
@article{tschannen2022partialtie,
author = {Tschannen, Valentin and Ghanim, Ammar and Ettrich, Norman},
title = {{Partial automation of the seismic to well tie with deep learning and Bayesian optimization}},
journal = {Computers \& Geosciences},
year = {2022},
volume = {164},
pages = {105120},
doi = {10.1016/j.cageo.2022.105120},
url = {https://doi.org/10.1016/j.cageo.2022.105120},
annote = {Full text read; variational CNN for wavelet (phase uncertainty), Bayesian optimization of bulk shift within user bounds; refs/tschannen2022partialtie.pdf}
}
@article{ali2025syntheticpseudowells,
author = {Ali, Muhammad and Changxingyue, He and Wei, Ning and Jiang, Ren and Zhu, Peimin and Hao, Zhang and Hussain, Wakeel and Ashraf, Umar},
title = {{Optimizing seismic-based reservoir property prediction: a synthetic data-driven approach using convolutional neural networks and transfer learning with real data integration}},
journal = {Artificial Intelligence Review},
year = {2025},
volume = {58},
number = {1},
eid = {31},
doi = {10.1007/s10462-024-11030-8},
url = {https://doi.org/10.1007/s10462-024-11030-8},
annote = {Full text read; target is P-impedance from prestack gathers, not porosity; published online 2024-11-30; refs/ali2025syntheticpseudowells.pdf}
}
@misc{herrera2012automatedtie,
author = {Herrera, Roberto Henry and van der Baan, Mirko},
title = {{Automated seismic-to-well ties?}},
year = {2012},
eprint = {1209.0201},
archivePrefix = {arXiv},
primaryClass = {physics.geo-ph},
url = {https://arxiv.org/abs/1209.0201},
annote = {Early preprint of the DTW well-tie method; the Geophysics 2014 paper (79(3), V47--V54, 10.1190/GEO2013-0248.1) was not available, cite the version actually read}
}
@inproceedings{cuturi2017softdtw,
author = {Cuturi, Marco and Blondel, Mathieu},
title = {{Soft-DTW: a Differentiable Loss Function for Time-Series}},
booktitle = {Proceedings of the 34th International Conference on Machine Learning},
series = {Proceedings of Machine Learning Research},
volume = {70},
pages = {894--903},
year = {2017},
eprint = {1703.01541},
archivePrefix = {arXiv},
url = {https://proceedings.mlr.press/v70/cuturi17a.html},
annote = {refs/cuturi2017softdtw.pdf}
}
@inproceedings{leguen2019dilate,
author = {Le Guen, Vincent and Thome, Nicolas},
title = {{Shape and Time Distortion Loss for Training Deep Time Series Forecasting Models}},
booktitle = {Advances in Neural Information Processing Systems 32},
year = {2019},
eprint = {1909.09020},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1909.09020},
annote = {DILATE; refs/leguen2019dilate.pdf}
}
@inproceedings{lakshminarayanan2017deepensembles,
author = {Lakshminarayanan, Balaji and Pritzel, Alexander and Blundell, Charles},
title = {{Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles}},
booktitle = {Advances in Neural Information Processing Systems 30},
year = {2017},
eprint = {1612.01474},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1612.01474},
annote = {refs/lakshminarayanan2017deepensembles.pdf}
}
@inproceedings{kendall2017uncertainties,
author = {Kendall, Alex and Gal, Yarin},
title = {{What Uncertainties Do We Need in Bayesian Deep Learning for Computer Vision?}},
booktitle = {Advances in Neural Information Processing Systems 30},
year = {2017},
eprint = {1703.04977},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1703.04977},
annote = {refs/kendall2017uncertainties.pdf}
}
@article{gneiting2007scoringrules,
author = {Gneiting, Tilmann and Raftery, Adrian E.},
title = {{Strictly Proper Scoring Rules, Prediction, and Estimation}},
journal = {Journal of the American Statistical Association},
year = {2007},
volume = {102},
number = {477},
pages = {359--378},
doi = {10.1198/016214506000001437},
url = {https://doi.org/10.1198/016214506000001437},
annote = {Proper scoring rules and CRPS; refs/gneiting2007scoringrules.pdf}
}
@inproceedings{murray2010ess,
author = {Murray, Iain and Adams, Ryan Prescott and MacKay, David J. C.},
title = {{Elliptical slice sampling}},
booktitle = {Proceedings of the 13th International Conference on Artificial Intelligence and Statistics},
series = {Proceedings of Machine Learning Research},
volume = {9},
pages = {541--548},
year = {2010},
eprint = {1001.0175},
archivePrefix = {arXiv},
url = {https://proceedings.mlr.press/v9/murray10a.html},
annote = {refs/murray2010ess.pdf}
}
@article{ravasi2020pylops,
author = {Ravasi, Matteo and Vasconcelos, Ivan},
title = {{PyLops---A linear-operator Python library for scalable algebra and optimization}},
journal = {SoftwareX},
year = {2020},
volume = {11},
pages = {100361},
doi = {10.1016/j.softx.2019.100361},
url = {https://doi.org/10.1016/j.softx.2019.100361},
annote = {Local copy is the arXiv version (1907.12349); refs/ravasi2020pylops.pdf}
}
@inproceedings{alfarraj2019semisupervised,
author = {Alfarraj, Motaz and AlRegib, Ghassan},
title = {{Semi-supervised learning for acoustic impedance inversion}},
booktitle = {SEG Technical Program Expanded Abstracts 2019},
pages = {2298--2302},
year = {2019},
doi = {10.1190/segam2019-3215902.1},
url = {https://doi.org/10.1190/segam2019-3215902.1},
annote = {Local copy is the arXiv version (1905.13412); refs/alfarraj2019semisupervised.pdf}
}
% --- Added 2026-10-28 for the manuscript (metadata from docs/theory.md, OpenAlex lookup of 2026-10-26).
% Pauli et al. 2011 and Ribatet et al. 2012 have not been read in full: verify before submission.
@inproceedings{mensch2018diffdp,
author = {Mensch, Arthur and Blondel, Mathieu},
title = {{Differentiable Dynamic Programming for Structured Prediction and Attention}},
booktitle = {Proceedings of the 35th International Conference on Machine Learning},
series = {Proceedings of Machine Learning Research},
volume = {80},
year = {2018},
eprint = {1802.03676},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1802.03676}
}
@article{pauli2011composite,
author = {Pauli, Francesco and Racugno, Walter and Ventura, Laura},
title = {{Bayesian composite marginal likelihoods}},
journal = {Statistica Sinica},
year = {2011},
volume = {21},
pages = {149--164},
annote = {not read in full}
}
@article{ribatet2012composite,
author = {Ribatet, Mathieu and Cooley, Daniel and Davison, Anthony C.},
title = {{Bayesian inference from composite likelihoods, with an application to spatial extremes}},
journal = {Statistica Sinica},
year = {2012},
volume = {22},
pages = {813--845},
eprint = {0911.5357},
archivePrefix = {arXiv},
annote = {not read in full}
}
@article{sakoe1978dp,
author = {Sakoe, Hiroaki and Chiba, Seibi},
title = {{Dynamic programming algorithm optimization for spoken word recognition}},
journal = {IEEE Transactions on Acoustics, Speech, and Signal Processing},
year = {1978},
volume = {26},
number = {1},
pages = {43--49},
doi = {10.1109/TASSP.1978.1163055}
}
% --- Added 2026-10-28: SEG/EAGE expanded-abstract scan 2024--2026 (plan section 2.4, item 4).
% Metadata checked against Crossref on 2026-10-28; abstracts read via OpenAlex (EarthDoc and the
% SEG Library block automated access). No full text for any of these: cite as abstract-only.
% IMAGE 2025 proceedings were issued online 2026-02-10; the conference year is used.
@inproceedings{lim2025awsm,
author = {Lim, Un Young and Van Wagoner, Tom and Cardona, Reynaldo},
title = {{Automated Well-tie SysteM (AWSM) for seismic depth calibration and wavelet estimation using parallel tempering MCMC (PT-MCMC): A Midland Basin case study}},
booktitle = {Fifth International Meeting for Applied Geoscience \& Energy Expanded Abstracts},
publisher = {Society of Exploration Geophysicists},
year = {2025},
pages = {16--20},
doi = {10.1190/image2025-4304877.1},
url = {https://doi.org/10.1190/image2025-4304877.1},
annote = {Abstract only (OpenAlex). Joint Bayesian inversion of time-depth transform parameters and wavelet(s) by PT-MCMC with uncertainty estimates; pre-stack wavelets for AVO/AVA. No learned property prediction mentioned}
}
@inproceedings{lim2025bootnet,
author = {Lim, Un Young and Cardona, Reynaldo},
title = {{Enhancing AVA inversion accuracy through deep neural network bootstrapping (BootNet): A novel approach for quantifying data uncertainty}},
booktitle = {Fifth International Meeting for Applied Geoscience \& Energy Expanded Abstracts},
publisher = {Society of Exploration Geophysicists},
year = {2025},
pages = {56--60},
doi = {10.1190/image2025-4304887.1},
url = {https://doi.org/10.1190/image2025-4304887.1},
annote = {Abstract only (OpenAlex). Bootstrapped ensemble of DNNs trained on Zoeppritz synthetics; impedance, velocity ratio and density with an uncertainty map; Midland Basin}
}
@inproceedings{quesada2024faultlabels,
author = {Quesada, Jorge and Prabhushankar, Mohit and AlRegib, Ghassan},
title = {{Uncertainty-aware seismic fault annotations can reveal insights into label expertise and confidence}},
booktitle = {Fourth International Meeting for Applied Geoscience \& Energy Expanded Abstracts},
publisher = {Society of Exploration Geophysicists},
year = {2024},
url = {https://alregib.ece.gatech.edu/image-2024-papers/jorge-image-2024/},
annote = {Abstract only (authors' lab page). DOI and pages not found in Crossref/OpenAlex on 2026-10-28: add before submission. 400 F3 images, 38 annotators (29 novices, 8 practitioners, 1 expert), three confidence levels}
}
@inproceedings{huff2024anglestack,
author = {Huff, O. and Evensen, A. and Lie, J. E. and Bugge, A. J. and Sablon, R. and Thorkildsen, V.},
title = {{Efficient angle stack conditioning using a convolutional neural network}},
booktitle = {85th EAGE Annual Conference \& Exhibition},
publisher = {European Association of Geoscientists \& Engineers},
year = {2024},
pages = {1--5},
doi = {10.3997/2214-4609.202410580},
url = {https://doi.org/10.3997/2214-4609.202410580},
annote = {Abstract only (OpenAlex). 1-D CNN trained on synthetic angle stacks moveout-corrected with true vs perturbed velocities; North Sea field test}
}
@inproceedings{thiebaud2024lfc,
author = {Thiebaud, J. and Aker, E. and Kj{\o}nsberg, H.},
title = {{Consistent porosity prediction using a probabilistic litho-facies inversion}},
booktitle = {85th EAGE Annual Conference \& Exhibition},
publisher = {European Association of Geoscientists \& Engineers},
year = {2024},
pages = {1--5},
doi = {10.3997/2214-4609.202410490},
url = {https://doi.org/10.3997/2214-4609.202410490},
annote = {Abstract only (OpenAlex). Bayesian inversion for posterior lithology-fluid classes and porosity distributions; northern North Sea}
}
@inproceedings{rizzuti2024waveletflows,
author = {Rizzuti, G. and Vasconcelos, I.},
title = {{Multiscale uncertainty quantification for post-stack seismic inversion with wavelet flows}},
booktitle = {85th EAGE Annual Conference \& Exhibition},
publisher = {European Association of Geoscientists \& Engineers},
year = {2024},
pages = {1--5},
doi = {10.3997/2214-4609.202410525},
url = {https://doi.org/10.3997/2214-4609.202410525},
annote = {Abstract only (OpenAlex). Variational inference with a multiscale (wavelet-based) normalizing flow for the post-stack inversion posterior}
}
@inproceedings{cordoba2025porosity,
author = {Cordoba, N. and Goyes, P. and Castro, L.},
title = {{Reservoir porosity estimation from post-stack seismic using deep learning constrained by well-porosity: A near-field application}},
booktitle = {86th EAGE Annual Conference \& Exhibition},
publisher = {European Association of Geoscientists \& Engineers},
year = {2025},
pages = {1--5},
doi = {10.3997/2214-4609.2025101450},
url = {https://doi.org/10.3997/2214-4609.2025101450},
annote = {Abstract only (OpenAlex). NN from post-stack seismic to porosity with a well-porosity loss term; seismic-noise sensitivity tests; Illinois Basin-Decatur Project. Abstract does not mention the well tie}
}
@inproceedings{mirza2025labelquality,
author = {Mirza, S. and Gala, A. and Devarakota, P. and Shah, S.},
title = {{Seismic and label quality assessment: A framework for improving AI models for seismic interpretation}},
booktitle = {86th EAGE Annual Conference \& Exhibition},
publisher = {European Association of Geoscientists \& Engineers},
year = {2025},
pages = {1--5},
doi = {10.3997/2214-4609.2025101452},
url = {https://doi.org/10.3997/2214-4609.2025101452},
annote = {Abstract only (OpenAlex). Seismic image quality metrics plus variability of manual salt interpretations}
}
@inproceedings{rizzuti2025uhr,
author = {Rizzuti, G. and Telling, R. and Vasconcelos, I.},
title = {{Enabling deep-learning-based uncertainty quantification at scale for post-stack UHR seismic inversion}},
booktitle = {86th EAGE Annual Conference \& Exhibition},
publisher = {European Association of Geoscientists \& Engineers},
year = {2025},
pages = {1--5},
doi = {10.3997/2214-4609.202510205},
url = {https://doi.org/10.3997/2214-4609.202510205},
annote = {Abstract only (OpenAlex). Variational Bayesian UHR post-stack inversion with normalizing flows; acoustic-impedance credible intervals; offshore wind site}
}
@article{guillon2020gtmetrics,
author = {Guillon, S{\'e}bastien and Joncour, Fr{\'e}d{\'e}ric and Barrallon, Pierre-Emmanuel and Castani{\'e}, Laurent},
title = {{Ground-truth uncertainty-aware metrics for machine learning applications on seismic image interpretation: Application to faults and horizon extraction}},
journal = {The Leading Edge},
year = {2020},
volume = {39},
number = {10},
pages = {734--741},
doi = {10.1190/tle39100734.1},
url = {https://doi.org/10.1190/tle39100734.1},
annote = {Abstract only (OpenAlex). Precision/recall/IoU with a tolerance distance between prediction and ground truth for thin faults and horizons}
}
@article{berkson1950two,
author = {Berkson, Joseph},
title = {{Are there Two Regressions?}},
journal = {Journal of the American Statistical Association},
year = {1950},
volume = {45},
number = {250},
pages = {164--180},
doi = {10.1080/01621459.1950.10483349},
url = {https://doi.org/10.1080/01621459.1950.10483349},
annote = {Origin of the Berkson error model (error independent of the assigned value); metadata verified via Crossref 2026-10-29}
}
@book{carroll2006measurement,
author = {Carroll, Raymond J. and Ruppert, David and Stefanski, Leonard A. and Crainiceanu, Ciprian M.},
title = {{Measurement Error in Nonlinear Models: A Modern Perspective}},
edition = {2nd},
publisher = {Chapman and Hall/CRC},
year = {2006},
doi = {10.1201/9781420010138},
url = {https://doi.org/10.1201/9781420010138},
annote = {Classical versus Berkson measurement error; metadata verified via Crossref 2026-10-29}
}
@book{fuller1987measurement,
author = {Fuller, Wayne A.},
title = {{Measurement Error Models}},
publisher = {Wiley},
year = {1987},
doi = {10.1002/9780470316665},
url = {https://doi.org/10.1002/9780470316665},
annote = {Errors-in-variables models; metadata verified via Crossref 2026-10-29}
}
@article{frenay2014label,
author = {Fr{\'e}nay, Beno{\^i}t and Verleysen, Michel},
title = {{Classification in the Presence of Label Noise: A Survey}},
journal = {IEEE Transactions on Neural Networks and Learning Systems},
year = {2014},
volume = {25},
number = {5},
pages = {845--869},
doi = {10.1109/TNNLS.2013.2292894},
url = {https://doi.org/10.1109/TNNLS.2013.2292894},
annote = {Label-noise survey (classification); metadata verified via Crossref 2026-10-29}
}
@article{song2023noisy,
author = {Song, Hwanjun and Kim, Minseok and Park, Dongmin and Shin, Yooju and Lee, Jae-Gil},
title = {{Learning From Noisy Labels With Deep Neural Networks: A Survey}},
journal = {IEEE Transactions on Neural Networks and Learning Systems},
year = {2023},
volume = {34},
number = {11},
pages = {8135--8153},
doi = {10.1109/TNNLS.2022.3152527},
url = {https://doi.org/10.1109/TNNLS.2022.3152527},
annote = {Deep learning with noisy labels survey; metadata verified via Crossref 2026-10-29}
}
@misc{bader2017teapot,
author = {Bader, Sean},
title = {{Teapot Dome Well Tie}},
howpublished = {Texas Data Repository, dataset},
year = {2017},
doi = {10.18738/T8/21WDU8},
url = {https://doi.org/10.18738/T8/21WDU8}
}
@inproceedings{mnih2012aerial,
author = {Mnih, Volodymyr and Hinton, Geoffrey E.},
title = {{Learning to Label Aerial Images from Noisy Data}},
booktitle = {Proceedings of the 29th International Conference on Machine Learning (ICML 2012)},
address = {Edinburgh, Scotland, UK},
year = {2012},
url = {https://mlanthology.org/icml/2012/mnih2012icml-learning/},
annote = {Full text read 2026-10-29 (Ghostscript text of http://icml.cc/2012/papers/318.pdf). Sec. 5: registration noise modelled as a translated crop of the true map, t in {0, 8 translations by t_max}, p(t=0)=theta_t; likelihood marginalized over t (Eq. 8) and fitted by EM; p(t) set on a validation set. Sec. 6.1: precision/recall with a 3-pixel buffer because the ground truth is misregistered. Sec. 6.3: lower precision of ABN/ABN-P at low recall on URBAN2, "likely because the test set is poorly registered". No page numbers found.}
}
@article{balakrishnan1962jitter,
author = {Balakrishnan, A. V.},
title = {{On the Problem of Time Jitter in Sampling}},
journal = {IRE Transactions on Information Theory},
year = {1962},
volume = {8},
number = {3},
pages = {226--236},
doi = {10.1109/TIT.1962.1057717},
url = {https://doi.org/10.1109/TIT.1962.1057717},
annote = {Metadata verified via Crossref 2026-10-29 (Crossref lists the successor name IEEE Transactions on Information Theory). Abstract and full text not obtained. Cited only for the general statement that the spectral effect of random timing errors has been studied for sampling jitter; Schwarzmann and Kaeser (arXiv:2509.04199, Sec. II) cite it for "spectral distortion under random timing perturbations".}
}

View File

@@ -0,0 +1,5 @@
\begin{abstract}
Seismic reservoir-property predictors are trained on well logs that a well tie places in two-way time, and the tie is uncertain. We analyse its error as an error in the time index of the label. Under an independence assumption, misregistered labels convolve the optimal predictor with the error distribution and blur the seismic band, as a controlled experiment confirmed to within 1\%. Without time anchors, absolute timing is not identified. A tie computed as a posterior mean has the opposite, Berkson, error structure and sharpens the predictor instead. A calibrated bank of posterior labels attains the oracle's population optimum, but its population gain over a point label is of fourth order in the tie error. On a registration-aware synthetic benchmark calibrated to F3, we compared point ties, posterior-mean labels and a tempered likelihood over a posterior bank under pre-registered rules. The first comparison failed, and the second was designed after that failure. There, posterior-mean labels had 8--22\% lower seismic-band RMSE than the best point tie, but failed when the anchor uncertainty was set at half or twice its true value. The bank gained further in all eight cells with a wide posterior. This gain exceeded the registered population bound for classical tie error in seven cells, but a post hoc bound for Berkson error in only three. Detecting such gains at blind wells requires an accurate reference: with exact ties, 5--18 wells gave a power of 0.8 in most cells; with reference errors of 3\,ms or more, 40 wells did not. The F3 and Volve field tests (four and six wells) failed, and neither could have detected such gains. Teapot Dome has independent time--depth references at no more than two of its 152 wells. We make no field or calibration claim.
\end{abstract}
\noindent\textbf{Keywords:} well tie; registration error; errors-in-variables; seismic porosity prediction; synthetic benchmark; blind-well validation; statistical power

View File

@@ -0,0 +1,18 @@
\section{Introduction}
\label{sec:intro}
Deep networks are widely used to map seismic amplitudes to reservoir properties such as porosity. The common workflow has four steps: tie each well to the seismic, resample the depth logs to two-way time (TWT), train a regressor from seismic to the time-domain labels, and score blind wells against labels produced by the same tie \citep[e.g.][]{xu2024sts,prabowo2025f3,tao2025structural,liu2023lowfrequency}. In this workflow the well tie is a preprocessing step. Its output, a single time--depth curve per well, is treated as exact.
The tie is not exact. It is an inverse problem with a posterior distribution, and Bayesian treatments of it have existed for two decades and are still being developed \citep{buland2003bayesianwavelet,gunning2006waveletextractor,lim2025awsm}. In those treatments the posterior is the end product: no learning step uses it. The size of the problem is easy to underestimate. At the four public wells of the F3 block, sonic-integrated TWT differs from the interpreted time--depth markers by up to 14--66\,ms, and the difference changes by up to 46\,ms inside a 500\,ms target window (Section~\ref{sec:data}). Two time--depth models distributed with the data disagree with the markers by up to 36\,ms. The dominant period of the seismic is 17--20\,ms. Label timing errors of one to several periods are therefore realistic, and they vary with depth, so a bulk lag cannot absorb them.
This is a label error of a particular kind. The label values are measured, but they are placed at the wrong times. Work on noisy labels and on errors in variables mostly concerns errors in the values (Section~\ref{sec:related}). A registration error acts on the time index instead: it is correlated along the well, its effect depends on frequency, and it affects the reference against which blind wells are scored as well as the training labels. We ask what such an error does to a learned predictor, whether training on a tie posterior rather than a point tie removes its effect, and whether a field test can detect the difference. We make four contributions.
\begin{enumerate}
\item[C1] \textbf{Theory.} Under an independence assumption, the MSE-optimal predictor trained on misregistered labels is the correctly registered predictor convolved with the distribution of the timing error, so the seismic band is attenuated by the characteristic function of the error (Proposition~\ref{prop:blur}). A controlled experiment matches this transfer to within 1\%. Without time anchors, a shared network and its label alignment can drift together without changing the loss (Proposition~\ref{prop:ident}), so losses that learn the alignment from the network's own predictions, such as soft-DTW \citep{cuturi2017softdtw} and DILATE \citep{leguen2019dilate}, cannot fix absolute timing. The error of an estimated tie can have the classical structure, which blurs the learned predictor, or the Berkson structure, which sharpens it (Proposition~\ref{prop:tie}). A calibrated bank of posterior labels has the population minimizer of training on the true labels, but its population gain over a point label is of fourth order in the tie error (Proposition~\ref{prop:bank}). We also relate the coverage of predictive intervals to the error structure (Proposition~\ref{prop:coverage}) and give the bias of scoring against a misregistered reference (Proposition~\ref{prop:reference}).
\item[C2] \textbf{A registration-aware benchmark.} We build synthetic data with known true warps from F3 geometry, rock physics and time--depth statistics. We vary drift, seismic signal-to-noise ratio and anchor density, and evaluate under locked, pre-registered pass rules. We report both comparisons that we registered: the first failed, and the second, designed after that failure, passed, with an explicit dependence on correctly specified anchor uncertainty. \todo{S1, S2, S3, S4 and S8 of \texttt{protocol\_bench}: grid fill, misspecification axes, B4 under the SMC posterior, second backbone, controlled cycle skipping.}
\item[C3] \textbf{A family of baselines.} Registration-marginalized learning (RML$_\lambda$), a tempered log-likelihood over a bank of labels, contains point-tie training, hard-min and soft-min shift losses and soft-DTW as special cases (Lemmas~\ref{lem:s1}--\ref{lem:sdtw}). We use this family to define the methods compared on the benchmark, not as a proposed method that wins.
\item[C4] \textbf{Detectability and the scope of field tests.} We derive how accurately the reference at blind wells must be tied, and how many blind wells are needed, for a comparison of tie methods to detect the effects of C1 (Corollary~\ref{cor:tolerance}, Section~\ref{sec:exp:detect}). We audit the public F3 well data: the porosity labels at three of the four wells are a linear function of the sonic log, and the time--depth markers are horizon-tie picks, not check shots. Pre-registered field tests on F3 and Volve failed, and an inventory of Teapot Dome found an independent time--depth reference at no more than two of its wells. These cases bound the scope of the paper.
\end{enumerate}
On the benchmark, labels at the posterior-mean warp of a sequential Monte Carlo tie beat the best point tie by 8--22\% in seismic-band RMSE at F3-like drift in all three full-anchor regimes. With the anchor uncertainty set at half or twice its true value, this advantage no longer passed the registered rule. A bank of posterior samples gained further when the posterior was wide. In seven of eight cells this gain exceeded the population bound that we registered, which assumes classical tie error, but in only three did it exceed the bound for the Berkson error of a posterior-mean tie, which we computed post hoc. With an exact reference, a sign test at blind wells needed 5--18 wells to detect these gains in most cells, and with reference errors of 3\,ms or more, 40 wells did not suffice. Neither public field dataset that we tested meets these conditions.
Section~\ref{sec:related} positions the work. Section~\ref{sec:data} describes the data and the audit, Section~\ref{sec:theory} the theory, and Section~\ref{sec:method} the tie posterior and the methods. Section~\ref{sec:experiments} reports the benchmark, the detectability analysis and the field cases. Section~\ref{sec:discussion} discusses what the results imply for field studies, and the limitations. Proofs are in Appendix~\ref{app:proofs}, and the field tests in Appendix~\ref{app:field}.

View File

@@ -0,0 +1,52 @@
\section{Related work}
\label{sec:related}
Three bodies of work meet in this problem, and they have so far been developed separately. Two others study uncertain labels: in statistics and machine learning in general, and in learned seismic interpretation.
\paragraph{Well ties and their uncertainty.}
\citet{buland2003bayesianwavelet} model the mistie between seismic time and log time as latent marker shifts with a triangular prior. They estimate these shifts jointly with the wavelet by MCMC and report their posterior. \citet{gunning2006waveletextractor} estimate the wavelet jointly with check-shot and marker times (Gaussian priors, monotonicity enforced), a registration shift and a lateral positioning error per well. They obtain uncertainty from a Laplace approximation and choose the wavelet length by marginal likelihood. \citet{lim2025awsm} infer time--depth transform parameters and wavelets jointly with parallel-tempering MCMC and report uncertainty estimates for a Midland Basin case study. Neither prior over time shifts nor a posterior over the time--depth relation is therefore new. In these works, however, the posterior is the end product. \citet{lim2025awsm} pass the estimated wavelets on to AVO/AVA inversion; their abstract does not describe passing the time--depth uncertainty on to a later step. \citet{wu2017multiwelltie} tie several wells at once with smooth depth-variable shifts and give no tie uncertainty. \citet{herrera2012automatedtie} use dynamic time warping for the tie. Among learning-based methods, \citet{tschannen2022partialtie} estimate the wavelet with a variational network: their uncertainty is mainly in wavelet phase, and the bulk shift is found by Bayesian optimization within user-set bounds. \citet{di2023welltie} and \citet{li2025cascadedtie} automate the tie with self-supervised learning and cascaded matching. All these methods output a tie, sometimes with wavelet or shift uncertainty, and stop there.
\paragraph{Learning reservoir properties from seismic with few wells.}
Recent studies predict porosity or impedance with convolutional, recurrent or transformer networks, sometimes with physics constraints or uncertainty estimates \citep{alfarraj2019semisupervised,vashisth2022rwpinn,liu2023lowfrequency,xu2024sts,chen2024multidimensional,li2024bpinn,ntibahanana2024ensemble,corrales2024seis2rock,dou2024seismae,tao2025structural,prabowo2025f3,cordoba2025porosity,rezaei2026krigingrf,sukar2026uncertainty}. In the studies we read in full, the labels are placed on the seismic time axis by a tie that is taken as given. \citet{xu2024sts} say so explicitly, and their augmentation shifts windows laterally, not in time. \citet{ali2025syntheticpseudowells} name the seismic-to-well tie discrepancy as a challenge and avoid it by training on synthetic pseudo-wells. Where uncertainty is estimated, it is the uncertainty of the network or of the data noise. It does not include the uncertainty of the label timing. \citet{cordoba2025porosity} report noise-sensitivity tests, but their abstract does not mention the tie or misregistered labels. Bayesian and variational inversions give posteriors or credible intervals for porosity or impedance \citep{thiebaud2024lfc,rizzuti2024waveletflows,rizzuti2025uhr}, and a bootstrapped network ensemble gives a spread of elastic-property predictions \citep{lim2025bootnet}. None of these abstracts names the well tie as a source of uncertainty.
\paragraph{Losses that tolerate temporal misalignment.}
Soft-DTW \citep{cuturi2017softdtw} and DILATE \citep{leguen2019dilate} replace the pointwise loss with a smoothed minimum over monotone alignments. Shift-tolerant losses that take the minimum over a set of bulk lags are a simpler variant. These losses use no time anchors, no physical tie model and no prior over warps. Proposition~\ref{prop:ident} shows that, without anchors, the absolute timing they learn is not identified. Learned alignment has also been applied to seismic inputs. \citet{huff2024anglestack} train a CNN on synthetic angle stacks moveout-corrected with true and perturbed velocities and use it to align field angle stacks. There the misaligned quantities are the inputs, and the synthetic targets are aligned by construction.
\paragraph{Label noise and errors in variables.}
Measurement-error models distinguish classical error, which is independent of the true value, from Berkson error, which is independent of the assigned value \citep{berkson1950two,fuller1987measurement,carroll2006measurement}. In linear regression, classical error in a covariate attenuates the fitted slope, while Berkson error leaves it unbiased and adds variance. Work on noisy labels in machine learning mostly treats corrupted class labels, with robust losses, sample selection or models of the corruption process \citep{frenay2014label,song2023noisy}. Closest to our setting, \citet{mnih2012aerial} train a network to label roads in aerial images from maps whose objects are misplaced. They model the observed map as a translated crop of the true map, marginalize the likelihood over a small set of translations whose prior is set on validation data, and fit it by expectation--maximization. Without its omission term, this is a bank of shifted labels with $\lambda = 1$ and no anchors (Section~\ref{sec:method:rml}). They also score predictions with a tolerance of three pixels, because the ground truth is itself misregistered, and suggest that their noise-robust models lost precision at low recall on one test set because that set was poorly registered. Proposition~\ref{prop:reference} states the analogous effect for band MSE. The spectral effect of random timing errors has long been studied for sampling jitter \citep{balakrishnan1962jitter}. A misregistered well label differs from these cases in where the error enters. Its values are correct, but they are placed at the wrong times. The error acts on the time index, it is correlated along the well, and its effect depends on frequency: it leaves the low frequencies nearly unchanged and blurs the seismic band (Proposition~\ref{prop:blur}). The classical and Berkson structures carry over to the time index, where they bias the learned predictor in opposite directions (Proposition~\ref{prop:tie}).
\paragraph{Label uncertainty in learned seismic interpretation.}
\citet{quesada2024faultlabels} collected fault labels on 400 F3 images from 38 annotators with different expertise and confidence. \citet{mirza2025labelquality} assess the variability of manual salt interpretations together with seismic image quality. \citet{guillon2020gtmetrics} add a tolerance distance to fault and horizon metrics, because thin boundaries cannot be placed exactly. In these works the label is an interpretation of the seismic image itself, the task is classification or segmentation, and the uncertainty is described by annotator disagreement or a spatial tolerance. In our problem the label values come from well logs, and their position on the seismic time axis is what is uncertain. A physical tie model conditioned on anchors gives a posterior for that position.
\paragraph{Position of this work.}
Table~\ref{tab:positioning} summarizes the comparison. The ingredients are not new: tie posteriors \citep{buland2003bayesianwavelet,gunning2006waveletextractor}, the spectral effect of random timing errors \citep{balakrishnan1962jitter}, the classical and Berkson error structures \citep{carroll2006measurement}, and a likelihood marginalized over label translations \citep{mnih2012aerial}. To our knowledge, in the reviewed literature no work combines them for seismic property prediction. None analyses how tie error in the training labels changes the learned predictor, feeds a tie posterior into training and evaluates the result under known registration error, or derives how accurate the reference at blind wells must be for a comparison of tie methods to detect a difference. The tie posterior itself builds directly on \citet{buland2003bayesianwavelet} and \citet{gunning2006waveletextractor}.
\begin{table}[t]
\centering
\caption{Positioning. DL: learned property prediction; Tie: automated tie; Tie UQ: posterior or uncertainty of the tie; UQ$\to$train: tie uncertainty used in training; Reg.\ eval.: evaluation that accounts for registration error; seg.: segmentation of seismic or aerial images; transl.: likelihood marginalized over a few label translations; tol.: spatial tolerance between prediction and label in the metric. \textsuperscript{a}Assessed from the abstract only.}
\label{tab:positioning}
\small
\begin{tabular}{>{\raggedright\arraybackslash}p{0.42\textwidth}ccccc}
\toprule
Work & DL & Tie & Tie UQ & UQ$\to$train & Reg.\ eval. \\
\midrule
\citet{prabowo2025f3,tao2025structural,xu2024sts,liu2023lowfrequency,corrales2024seis2rock} & \checkmark & -- & -- & -- & -- \\
\citet{cordoba2025porosity}\textsuperscript{a} & \checkmark & -- & -- & -- & -- \\
\citet{li2024bpinn}\textsuperscript{a}, \citet{sukar2026uncertainty} & \checkmark & -- & -- & -- & -- \\
\citet{rizzuti2024waveletflows,rizzuti2025uhr,lim2025bootnet}\textsuperscript{a} & \checkmark & -- & -- & -- & -- \\
\citet{ali2025syntheticpseudowells} & \checkmark & -- & avoided & -- & -- \\
\citet{di2023welltie}\textsuperscript{a}, \citet{li2025cascadedtie} & -- & \checkmark & -- & -- & -- \\
\citet{tschannen2022partialtie} & -- & \checkmark & partial & -- & -- \\
\citet{wu2017multiwelltie} & -- & \checkmark & -- & -- & -- \\
\citet{buland2003bayesianwavelet,gunning2006waveletextractor} & -- & \checkmark & \checkmark & -- & -- \\
\citet{lim2025awsm}\textsuperscript{a} & -- & \checkmark & \checkmark & -- & -- \\
Soft-DTW, DILATE & generic & soft & -- & -- & -- \\
\citet{mnih2012aerial} & seg. & -- & -- & transl. & tol. \\
\citet{quesada2024faultlabels}\textsuperscript{a}, \citet{mirza2025labelquality}\textsuperscript{a} & seg. & -- & -- & -- & -- \\
\citet{guillon2020gtmetrics}\textsuperscript{a} & seg. & -- & -- & -- & tol. \\
This work & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark \\
\bottomrule
\end{tabular}
\end{table}
\todoblock{(1) SEG and EAGE expanded abstracts 2024--2026 were scanned on 28/10/2026; the ten entries added then are abstract-only (\texttt{refs.bib}, block dated 2026-10-28). Still open: the IMAGE 2026 abstract by Palavicini Gurria et al.\ on well ties and seismic inversion as quantitative quality controls (in the official program, text not retrieved); the DOI and pages of \citet{quesada2024faultlabels}; rerun the novelty search on the submission day and revise ``to our knowledge'' if needed. (2) The 28/10 SEG/EAGE entries were assessed from abstracts only; read the full texts if obtained, otherwise keep the footnote. (Full texts of \citet{chen2024multidimensional}, \citet{li2024bpinn}, \citet{di2023welltie} and \citet{dou2024seismae} cannot be obtained, confirmed 28/10/2026; every use of them above was checked against the abstracts and the footnote stays.) (3) Decide whether to cite the Geophysics 2014 version of Herrera \& van der Baan (not obtained; the 2012 preprint is cited). (4) Check that the ``UQ$\to$train'' column is fair to \citet{sukar2026uncertainty}.}

View File

@@ -0,0 +1,72 @@
\section{Data and audit}
\label{sec:data}
\subsection{F3 block}
\label{sec:data:f3}
We use the public F3 Demo 2023 release of the F3 block, Dutch sector of the North Sea \todo{dataset citation (dGB Earth Sciences / TNO); licence CC BY-SA 3.0, verify wording}. The post-stack volume covers inlines 100--750 and crosslines 300--1250 at 4\,ms sampling. Four vertical wells have sonic (DT), density (RHOB) and effective porosity (PHIE) logs: F02-1, F03-2, F03-4 and F06-1. The release also contains seven interpreted horizons and time--depth (TD) markers at each well. All learning experiments use the window 600--1100\,ms TWT (126 samples). Tie likelihoods and anchors use the extended window 400--1300\,ms.
Within the target window, the amplitude spectrum around the wells and over the volume peaks near 60\,Hz with a mean frequency of 49\,Hz. The dominant period is therefore 17--20\,ms. The $-20$\,dB band of the volume spans 4--83\,Hz.
We audited the well data before any modelling. Table~\ref{tab:audit} summarizes the findings, and the paragraphs below explain them.
\begin{table}[t]
\centering
\caption{Audit of the F3 wells in the 600--1100\,ms window. $\Delta t_{\mathrm{DT}}$: TWT from integrated sonic minus TD-marker TWT, over the markers in the window (range, and change within the window). $\max|\Delta t_{\mathrm{wlt}}|$: largest deviation of the distributed OpendTect time--depth model from the markers. $K$: TD markers in the window. Label: relation of PHIE to the logs.}
\label{tab:audit}
\small
\setlength{\tabcolsep}{3pt}
\begin{tabular}{lcccccl}
\toprule
Well & IL/XL & $\Delta t_{\mathrm{DT}}$ (ms) & change (ms) & $\max|\Delta t_{\mathrm{wlt}}|$ (ms) & $K$ & Label \\
\midrule
F02-1 & 362/336 & $+2 \to -44$ & 46 & 28.5 & 11 & from RHOB ($R^2=0.84$) \\
F03-2 & 722/848 & $-3 \to -14$ & 11 & 10.2 & 9 & $-0.2018+0.0011\,\mathrm{DT}$ \\
F03-4 & 442/1007 & $-42 \to -52$ & 10 & 9.2 & 9 & $-0.2018+0.0011\,\mathrm{DT}$ \\
F06-1 & 244/387 & $-21 \to -66$ & 45 & 36.4 & 10 & $-0.2018+0.0011\,\mathrm{DT}$ \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Geometry.}
We located the wells by applying the survey's bin-to-coordinate transform to the wellhead coordinates. F02-1 and F06-1 are 3.2\,km apart, and the other pairs are 8--17\,km apart. The distance to the nearest training well therefore differs greatly between leave-one-well-out folds.
\paragraph{Time--depth relation.}
Integrating the sonic from the first log sample, as is common in learning studies, gives TWT that differs from the TD markers in the window by up to 14--66\,ms, depending on the well. The difference changes with depth by 10--46\,ms (Table~\ref{tab:audit}, Fig.~\ref{fig:tddrift}). The sign is negative at depth, so sonic time is early, as expected from velocity dispersion. The two TD models distributed with the data also disagree. The OpendTect model deviates from the markers by up to 36.4\,ms. A second set of model files is offset from the check-shot tables by $+40.5$, $+40.2$, $+25.2$ and $-14.6$\,ms on average. The sign and size of this offset vary by well, and at F06-1 it changes sign with depth. A datum correction does not explain it. The ``check-shot'' tables have exactly the same depths as the markers. They are horizon-tie picks made on this seismic volume, not independent check-shot surveys. We therefore treat them as anchors with a pick uncertainty $\sigma_a$. The robust spread (MAD) of marker--horizon time differences over 18 pairs at the four wells is 6.9\,ms, and we use $\sigma_a = 7$\,ms. Each well has 9--11 anchors in the target window, 8 to about 148\,ms apart.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{td_drift.pdf}
\caption{Offset of three time--depth sources from the TD markers at the four F3 wells: sonic integrated from a single shallow anchor (integrated DT), the distributed OpendTect time--depth model, and a second distributed model (DT model). The shaded band is the 600--1100\,ms target window.}
\label{fig:tddrift}
\end{figure}
\paragraph{Labels.}
At F03-2, F03-4 and F06-1, PHIE is an exact linear function of the sonic log: $\mathrm{PHIE} = -0.2018 + 0.0011\,\mathrm{DT}$ (DT in $\mu$s/m, $R^2 = 1.00000$, maximum error $10^{-4}$). It is equally exactly $(2650 - \mathrm{RHOB})/1600$. The density at these wells is itself derived from sonic: a national well-log archive shows that the density at F03-4 and F06-1 is a predicted log, and the measured density at F03-2 starts below the target window. At F02-1, PHIE follows the measured density ($R^2 = 0.84$) but is not a deterministic function of it. To give all four wells the same label definition, we use $\mathrm{PHIE}_{\mathrm{DT}} = -0.2018 + 0.0011\,\mathrm{DT}$ at all wells and report the original PHIE as a sensitivity check. The F3 ``porosity'' target in this paper is therefore a linear transform of sonic slowness. We call it porosity only in this sense. Density porosity computed from measured density explains 27--59\% of the variance of this label at four wells with measured density in the window (F02-1, F03-4 and two archive wells outside the release). Choosing the label is therefore choosing what is learned. There is one benefit: the rock-physics chain $\phi \to \mathrm{DT} \to \mathrm{RHOB} \to$ acoustic impedance is known exactly, so the physical tie likelihood of Section~\ref{sec:method} is not an approximation on F3.
\subsection{Synthetic benchmark (D2)}
\label{sec:data:d2}
The synthetic benchmark makes the true registration known while keeping the F3 statistics. Five F3 horizons (Shallow, FS8, FS7, Truncation, MFS4) define the stratigraphic frame. Porosity is a trend ($\phi_0 = 0.32$, slope $-0.008$ per 100\,ms) plus unit offsets and a sum of two Ornstein--Uhlenbeck fields in stratigraphic coordinates (standard deviations 0.010 and 0.006, correlation lengths 10 and 2\,ms), clipped to $[0.05, 0.45]$. The F3 rock physics maps porosity to DT, RHOB and impedance. Seismic is the reflectivity convolved with a 128\,ms zero-phase statistical wavelet estimated from F3, plus noise at a prescribed signal-to-noise ratio (SNR).
The true time--depth warp of each well is drawn from the warp prior of Section~\ref{sec:method:prior}, fitted to the F3 anchors, and scaled by a drift factor $c$ ($g \to c\,g$, $b \to c\,b$). $c = 1$ reproduces the F3 drift level, and $c = 0$ is perfect registration. Anchors are the true times at stratigraphic markers plus $\N(0, \sigma_a^2)$ noise with $\sigma_a = 7$\,ms. Each realization has a pool of 16 training wells, from which nested subsets of $N$ wells are drawn, and 8 test wells at least 1\,km from every other well. Labels are scored in the true time of the earth model. We use five observation regimes:
\begin{itemize}
\item R10, R0 and Rm5: SNR 10, 0 and $-5$\,dB, full anchor density;
\item R0h: SNR 0\,dB with half the anchors;
\item R10tb: SNR 10\,dB with only the top and bottom anchors.
\end{itemize}
Under the F3 warp prior, Rm5 gives the posterior width closest to F3 (Section~\ref{sec:exp:p2r}).
\subsection{Volve field}
\label{sec:data:volve}
The second field dataset is Volve (Norwegian North Sea), released by Equinor under a CC BY-NC-SA 4.0 licence \todo{dataset citation (Equinor Volve data village)}. Its role is to break the label structure of F3. The computed effective porosity PHIF of the operator's petrophysical interpretation is driven by density, not by sonic: within each well its correlation with RHOB is $-0.92$ to $-0.99$, RHOB and NPHI explain 84--98\% of its variance, and adding DT raises this by at most 0.9 percentage points. Six wells have DT, RHOB, NPHI and PHIF: F-1, F-1 A, F-1 B, F-11 A, F-11 T2 and F-12. All six are deviated (maximum inclination 30--82$^\circ$; 4--54$^\circ$ over the labelled interval), and they share one platform. F-1 A and F-1 B leave the F-1 borehole at 2587\,m MD, and F-11 A leaves F-11 T2 at about 2580\,m MD, so the wells form three slot groups, \{F-1, F-1 A, F-1 B\}, \{F-11 A, F-11 T2\} and \{F-12\}, whose members share the hole above the kick-off.
\paragraph{Seismic and geometry.}
We use the post-stack ST10010 full-angle stack (3--41$^\circ$), a 2011 depth migration converted to time, at 4\,ms sampling. Its trace headers carry an invalid time scalar that standard readers apply to the start time, which shifts every sample 8\,ms late. We use the start time of the text header (4\,ms) and checked it against five interpreted horizons: the amplitude extremum along each falls at a lag of 0 to $+2$\,ms. Trajectories come from the operator's definitive surveys; recomputing them by minimum curvature reproduces the listed TVD within 0.01\,m. The seismic input of a well is a $3\times3$ patch of traces interpolated bilinearly along the deviated path at the time given by its time--depth relation, because a vertical trace at one bin differs from the path composite by a relative RMS of 0.19--0.61 over the labelled interval. Learning uses the window 2400--2900\,ms (126 samples) and tie likelihoods the extended window 2000--3200\,ms.
\paragraph{Time--depth and anchors.}
Only F-11 T2 has a zero-offset VSP. As anchors we use the operator's well picks with a TWT from the Ty Formation downwards, excluding picks flagged as not logged, not reached or faulted; each well has 4--9 such anchors within its logged sonic interval. Shallower picks are unreliable (picks at the same depth in a shared borehole differ by about 110\,ms). At reservoir level every unflagged pick lies within $\pm 10$\,ms of the corresponding interpreted horizon, and at F-11 T2 the picks lie within $-6.1$ to $+2.3$\,ms of the VSP. The pick times come from the operator's time--depth models, so they are interpretations, not measurements, as on F3. Time is vertical time: DT is integrated over TVD and calibrated to the anchors by stretching between them. At F-11 T2 this marker-calibrated sonic lies within $-2.4$ to $-0.8$\,ms of the VSP over the labelled interval. We keep $\sigma_a = 7$\,ms from F3; it is not estimated on Volve.
\paragraph{Labels.}
PHIF is used only where DT is valid, which leaves 16--37 labelled 4\,ms samples per well (150 in total) at 2509--2819\,ms. The labelled runs lie 25--179\,m below the deepest anchor, so their timing depends on the drift of the sonic below it. They are shorter than one period at 6\,Hz, so the band split used on F3 is undefined here. The well means of PHIF range from 8.5\,p.u.\ at F-1 to 17.0\,p.u.\ at F-12, against standard deviations of 3.3--6.0\,p.u.\ within wells.

View File

@@ -0,0 +1,233 @@
\section{Theory}
\label{sec:theory}
\paragraph{Notation.}
$t$ is seismic two-way time, $X$ the seismic input around a well, and $y(t)$ the label under correct registration. $\delta(t)$ is the registration error, and the observed label is $\tilde y(t) = y(t + \delta(t))$. The oracle predictor is $m(t) = \E[y(t)\mid X]$, the MSE-optimal predictor under correct labels. The Fourier transform is $\hat g(f) = \int g(t)\,e^{-i2\pi f t}\dd t$, and $T_\beta h(t) = h(t-\beta)$ is a time shift. $S_a$ is the power spectrum of $a$. The seismic band is $|f| \ge f_c$ with $f_c = 6$\,Hz, and $B$ is the corresponding high-pass operator, with $a_b = Ba$. In the experiments $B$ is a zero-phase fourth-order Butterworth filter. Its response is real and non-negative, so every result below holds with $S$ replaced by $|H_B|^2 S$. Spectral statements assume second-order stationarity in $t$, which is a working assumption for well logs.
\subsection{Misregistered labels blur the optimal predictor}
\begin{proposition}[Blur]
\label{prop:blur}
Assume (A1) that for every $t$, $\delta(t)$ is independent of $(X, y(\cdot))$ with distribution $p_t$, and (A2) that $\E[y(t)^2] < \infty$. Then the MSE-optimal predictor of the observed label is
\begin{equation}
\hat y^\star(t) = \E[\tilde y(t)\mid X] = \int p_t(d)\, m(t+d)\dd d .
\end{equation}
If $p_t \equiv p$, then $\hat y^\star$ is $m$ passed through a linear time-invariant filter with frequency response equal to the characteristic function of $\delta$,
\begin{equation}
P(f) = \E\big[e^{i2\pi f\delta}\big], \qquad \delta \sim \N(\mu_\delta, \sigma^2) \;\Rightarrow\; P(f) = e^{i2\pi f\mu_\delta}\, e^{-2\pi^2\sigma^2 f^2}.
\label{eq:transfer}
\end{equation}
\end{proposition}
Only the marginal distribution of $\delta(t)$ at each $t$ enters $\hat y^\star$. Whether the error is a smooth drift or independent jitter does not change the population optimum, although it changes finite-sample learning. A non-zero mean $\mu_\delta$ adds a linear phase, that is, a common shift. This common shift is the direction that Proposition~\ref{prop:ident} shows to be unidentified. Assumption (A1) says that the error is independent of the truth: the observed label at $t$ is the true label at $t + \delta(t)$, with $\delta$ independent of everything else. This is the classical structure of errors-in-variables models \citep{fuller1987measurement,carroll2006measurement}, applied to the time index rather than to the value of the label. It is a modelling assumption. On F3 the same sonic log produces both the label and the time axis, so $\delta$ and $y$ are not strictly independent. Section~\ref{sec:theory:post} shows that a tie estimated from the well data can have the opposite structure, with the opposite effect.
\begin{corollary}[Seismic-band bounds]
\label{cor:band}
Let $\langle h\rangle = \int_{|f|\ge f_c} h\, S_{m}\dd f \big/ \int_{|f|\ge f_c} S_{m}\dd f$. Then
\begin{equation}
\frac{\sd \hat y^\star_b}{\sd y_b} \le \sqrt{\langle |P|^2\rangle} \le \sup_{|f|\ge f_c}|P(f)|,
\qquad
\PCC_b(\hat y^\star) = \kappa(P)\,\PCC_b(m), \quad \kappa(P) = \frac{\langle \operatorname{Re} P\rangle}{\sqrt{\langle|P|^2\rangle}} \le 1 ,
\end{equation}
with equality in $\kappa$ if and only if $P$ is a positive constant on the support of $S_{m_b}$.
\end{corollary}
The coherence at each frequency is unchanged. Blur does not destroy information at the population level, but it reweights the band towards low frequencies. Undoing it would require multiplying by $e^{+2\pi^2\sigma^2 f^2}$, which amplifies estimation error wherever $|P| \approx 0$, and $\sigma$ is unknown in practice. Taking the F3 seismic amplitude spectrum as a proxy for the recoverable band, a Gaussian error with $\sigma = 8$\,ms keeps less than 7\% of the seismic-band variance.
\begin{corollary}[Variance matching rescales amplitude only]
\label{cor:var}
Consider $J(h) = \E\|h - \tilde y\|^2 + \Psi(\E h, \Var h)$ over predictors $h$ that are functions of $X$, where $\Psi$ is any penalty on the mean and variance of the prediction (for example a penalty on the standard-deviation ratio). Every minimizer satisfies $h^\star - \E h^\star = a\,(\hat y^\star - \E\hat y^\star)$ for some $a \ge 0$.
\end{corollary}
A variance-matching loss can therefore restore the overall standard-deviation ratio, but the in-band spectrum keeps the shape $|P|^2 S_m$. The prediction becomes larger but stays blurred. Baseline B2 (Section~\ref{sec:method:baselines}) combines a variance-matching term with a best-shift term and is affected in the same way.
\paragraph{Verification (H1).}
We trained the backbone of Section~\ref{sec:method:train} with MSE on oracle synthetic labels shifted by $\delta_{wj} = \sigma z_{wj}$, $z \sim \N(0,1)$. The shift is fixed within each 64-sample window and independent of everything else, so (A1) holds by construction. We used $c = 0$, $N = 16$, eight realizations and five seeds. The cross-spectrum ratio
\begin{equation}
\hat H_\sigma(f) = \frac{\sum \operatorname{Re}[Y^*(f)\hat Y_\sigma(f)]}{\sum \operatorname{Re}[Y^*(f)\hat Y_0(f)]}
\end{equation}
estimates $P_\sigma(f)$; the sums run over test wells, realizations and seeds. The pre-registered statistic is $r(\sigma)$, the geometric mean of $\hat H_\sigma/P_\sigma$ over frequencies with $f \ge f_c$, $P_\sigma \ge 0.1$ and reference cross-power at least 10\% of its in-band maximum. The hypothesis is rejected if $r \notin [0.5, 2]$ for any $\sigma > 0$. Table~\ref{tab:h1} and Fig.~\ref{fig:h1} show the result: $r = 1.009$, 1.009 and 1.007 for $\sigma = 4$, 8 and 16\,ms, and $r = 1.093$ for $\sigma = 32$\,ms. Proposition~\ref{prop:blur} is not rejected. Two limitations apply. First, the frequency-selection rule keeps only 6.8--22.5\,Hz, where the MSE predictor has coherent power (72\% of the in-band cross-spectrum); the test says nothing above about 23\,Hz. Second, at 32\,ms the measured attenuation is 9\% weaker than predicted and the interval excludes 1. This is within the pre-registered tolerance, and we have not identified its cause.
\begin{table}[t]
\centering
\caption{Test of Proposition~\ref{prop:blur} (H1). $r(\sigma)$: geometric mean of measured over theoretical transfer; 95\% bootstrap interval over realizations. Band metrics in p.u.\ on test wells.}
\label{tab:h1}
\small
\begin{tabular}{rcccccc}
\toprule
$\sigma$ (ms) & $r(\sigma)$ & 95\% CI & frequencies & band RMSE & band PCC & band sd ratio \\
\midrule
0 & 1 & -- & 17 & 0.426 & 0.954 & 0.945 \\
4 & 1.009 & [0.996, 1.019] & 17 & 0.587 & 0.908 & 0.817 \\
8 & 1.009 & [0.990, 1.025] & 17 & 0.805 & 0.817 & 0.677 \\
16 & 1.007 & [0.975, 1.038] & 15 & 1.042 & 0.670 & 0.475 \\
32 & 1.093 & [1.046, 1.143] & 4 & 1.269 & 0.388 & 0.247 \\
\bottomrule
\end{tabular}
\end{table}
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{p2_h1.pdf}
\caption{Test of Proposition~\ref{prop:blur}. (a) Estimated transfer $\hat H_\sigma(f)$ on the frequencies used (solid) and $e^{-2\pi^2\sigma^2 f^2}$ (dashed). The shaded band below 6\,Hz is outside the seismic band and is not used. (b) $r(\sigma)$ with 95\% intervals over realizations and the number of frequencies used; the shaded region is the pre-registered non-rejection interval $[0.5, 2]$. Setting: $c = 0$, $N = 16$, MSE loss.}
\label{fig:h1}
\end{figure}
\subsection{Without anchors, absolute timing is not identified}
Consider $N$ training wells with seismic $X_w$, depth logs $\phi_w$ and warps $u_w = (b_w, g_w)$ (Section~\ref{sec:method:prior}). Let $y^{u}(t) = (\aaf\phi)(z_u(t))$ be the label under warp $u$, where $z_u$ inverts $t_u$ and $\aaf$ is an anti-alias filter. Let $e_b$ be the direction that adds the same $\beta$ to every $b_w$. The joint MAP objective over network parameters $\theta$ and warps $\mathbf{u}$ is
\begin{equation}
\Phi(\theta, \mathbf u) = \sum_w \Big[\mathcal L_w(\theta; y_w^{u_w}) + \log p(u_w) + \sum_k \log \N\big(t_{wk};\, t_{u_w}(z_{wk}),\, \sigma_a^2\big)\Big],
\end{equation}
with Gaussian log-likelihood $\mathcal L_w$ over windows and anchors $(z_{wk}, t_{wk})$.
\begin{proposition}[Identifiability]
\label{prop:ident}
Assume (B) that the model class is closed under output shifts: for each $\theta$ and each admissible $\beta$ there is $\theta'$ with $\mu_{\theta'} = T_\beta \mu_\theta$ and $\sigma_{\theta'} = T_\beta\sigma_\theta$. Then, up to window-edge effects:
\begin{enumerate}
\item[(a)] without anchors, with a flat prior on $b$ and no seismic tie term, $\Phi(\theta', \mathbf u + \beta e_b) = \Phi(\theta, \mathbf u)$, so the objective has a ridge in $\beta$ shared by all wells;
\item[(b)] a prior $b_w \sim \N(0, \sigma_b^2)$ adds curvature $N/\sigma_b^2$ along the ridge;
\item[(c)] anchors with finite $\sigma_a$ add curvature $\sum_w K_w/\sigma_a^2$, where $K_w$ is the number of anchors at well $w$, so that
\begin{equation}
\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}} .
\end{equation}
\end{enumerate}
\end{proposition}
With 4 wells of 16 anchors at $\sigma_a = 7$\,ms, $\sd(\beta) \approx 0.9$\,ms. With only the prior $\sigma_b = 50$\,ms, $\sd(\beta) \approx 50/\sqrt N$, that is 35\,ms for $N = 2$ and 12.5\,ms for $N = 16$. A common shift $\beta$ multiplies the band-limited correlation at frequency $f$ by $\cos(2\pi f\beta)$, and $\cos(2\pi\cdot 20\,\mathrm{Hz}\cdot 12.5\,\mathrm{ms}) = 0$. Assumption (B) holds exactly for fully convolutional networks with a wide enough last layer and approximately for the CNN--GRU used here.
\paragraph{The seismic tie term.}
Seismic is observed on a fixed time axis, so a tie likelihood that compares the seismic with a warped synthetic is not invariant to $\beta$. In principle it pins absolute time. In practice a small shift trades off against a constant wavelet phase rotation: the two coincide at $f_0 = \psi/(2\pi\beta)$ and differ by $2\pi(f - f_0)\beta$ elsewhere. For $\beta = 4$\,ms the largest phase difference over $\pm 30$\,Hz around $f_0$ is only about $43^\circ$. Information about $\beta$ thus comes from the bandwidth, not the centre frequency.
\paragraph{Consequences.}
Shift-tolerant losses and soft-DTW choose the alignment that best fits the network's current prediction and use no anchors. Within the range of their shift bank or band they fall under case (a): network and alignment can drift together without penalty. A tie posterior conditioned on anchors does not have this ridge. Its absolute timing is set before training, with per-well common-shift uncertainty of about $\sigma_a/\sqrt{K_w}$.
\subsection{Labels from a tie: blur or sharpening}
\label{sec:theory:post}
Proposition~\ref{prop:blur} treats the registration error as independent of everything else. A tie estimated from the data at a training well need not have this property. Let $D$ denote all data at the well (seismic, logs and anchors), and let the network input $X$ be a function of $D$. Let $u^\star$ be the true warp, so that $y = y^{u^\star}$, and let $\hat u = \hat u(D)$ be a point tie with label $\tilde y = y^{\hat u}$. The misregistration can be written in either direction,
\begin{equation}
\tilde y(t) = y\big(t + \delta(t)\big),\ \ \delta(t) = t_{u^\star}\big(z_{\hat u}(t)\big) - t;
\qquad
y(t) = \tilde y\big(t + \varepsilon(t)\big),\ \ \varepsilon(t) = t_{\hat u}\big(z_{u^\star}(t)\big) - t .
\label{eq:twoerrors}
\end{equation}
Let $\tilde m(t) = \E[\tilde y(t)\mid X]$ be the optimal predictor of the point label ($\hat y^\star$ in Proposition~\ref{prop:blur}), and let $Q(f) = \E[e^{i2\pi f\varepsilon}]$.
\begin{proposition}[Two error structures]
\label{prop:tie}
Assume (A2) for $y$ and $\tilde y$.
\begin{enumerate}
\item[(a)] \emph{Classical error.} If $\delta(t)$ is independent of $y(\cdot)$ given $X$, with conditional distribution $p_t(\cdot\mid X)$, then
\begin{gather*}
\tilde m(t) = \int p_t(d\mid X)\, m(t+d)\dd d, \\
\Var\big(\tilde y(t)\mid X\big) = \int p_t(d\mid X)\Var\big(y(t+d)\mid X\big)\dd d + \Var_{p_t}\!\big[m(t+d)\big].
\end{gather*}
\item[(b)] \emph{Berkson error.} If $\varepsilon(t)$ is independent of $D$ given $X$, with conditional distribution $q_t(\cdot\mid X)$, then
\begin{gather*}
m(t) = \int q_t(e\mid X)\, \tilde m(t+e)\dd e, \\
\Var\big(y(t)\mid X\big) = \int q_t(e\mid X)\Var\big(\tilde y(t+e)\mid X\big)\dd e + \Var_{q_t}\!\big[\tilde m(t+e)\big].
\end{gather*}
\end{enumerate}
If $p_t$ and $q_t$ do not depend on $t$, then, averaged over the window and up to edge terms, the point label has the larger conditional variance under (a) and the smaller under (b). If they depend on neither $t$ nor $X$, then $\tilde m$ is $m$ filtered by $P$ under (a), and $m$ is $\tilde m$ filtered by $Q$ under (b). For zero-mean Gaussian errors with variance $\sigma^2$, the transfer from $m$ to $\tilde m$ is $e^{-2\pi^2\sigma^2 f^2}$ under (a) and $e^{+2\pi^2\sigma^2 f^2}$ under (b).
\end{proposition}
Structure (a) is the classical structure of measurement-error models, in which the error is independent of the true value. Structure (b) is the Berkson structure, in which the error is independent of the assigned value \citep{berkson1950two,carroll2006measurement}. Here the error lies in the time index of the label, and the two structures bias the learned predictor in opposite directions. Under (a) the point label blurs the optimal predictor and widens the learned variance. Under (b) it sharpens the predictor and narrows the variance. Structure (b) is the natural idealization for a tie computed as a posterior mean, $\hat u = \E[u^\star\mid D]$. Then $\E[u^\star - \hat u\mid D] = 0$ by construction, and in a linear-Gaussian model $u^\star - \hat u$ is independent of $D$. For the bulk offset $b$ in \eqref{eq:warp}, the time error equals the posterior error of $b$ and inherits this property; for the drift it does so approximately, when the posterior is narrow. A tie fitted in another way, for example by maximizing a synthetic--seismic correlation, can have either structure or neither. On synthetic data the two can be told apart: for the bulk offset, classical error means $\Cov(\hat b - b^\star, b^\star) = 0$, and Berkson error means $\Cov(b^\star - \hat b, \hat b) = 0$.
A bank of labels removes the dependence on a single tie when it represents the posterior correctly.
\begin{proposition}[Calibrated bank]
\label{prop:bank}
Call a bank $\{(u_s, \pi_s)\}$ calibrated if, for every integrable $G$, $\sum_s \pi_s G(u_s, D) = \E[G(u^\star, D)\mid D]$. For a calibrated bank:
\begin{enumerate}
\item[(a)] the mean label $\bar y = \sum_s \pi_s y^{u_s}$ satisfies $\bar y(t) = \E[y(t)\mid D]$ and $\E[\bar y(t)\mid X] = m(t)$;
\item[(b)] for every network $(\mu_\theta, \sigma_\theta)$ that depends on the data only through $X$, $\E\big[\sum_s \pi_s \ell_s\big] = \E[\ell^\star]$, where $\ell^\star$ is the window log-likelihood \eqref{eq:rml} of the label at the true warp.
\end{enumerate}
Hence the $\lambda \to 0$ limit of RML (Lemma~\ref{lem:sandwich}) has the population minimizer of training on the true labels, $\mu = m$ and $\sigma^2 = \Var(y\mid X)$, and MSE on the mean label has the population minimizer $\mu = m$.
\end{proposition}
Calibration is an idealization; it holds for an exact posterior sample as $S \to \infty$. Under it, marginalizing over the posterior removes the population bias of both structures. The mean warp does not share this property. \mPM{} trains on the label at the mean warp $\bar u$, not on the mean label. Expanding $y^{u}$ around $\bar u = \sum_s\pi_s u_s$,
\begin{equation*}
\bar y - y^{\bar u} = \tfrac12 \sum_s \pi_s\, (u_s - \bar u)^\top \nabla_u^2 y^{\bar u}\, (u_s - \bar u) + O\big(\|u_s - \bar u\|^3\big),
\end{equation*}
so the two labels agree to first order in the posterior spread. If the time error of the mean warp has structure (b), the population optimum of \mPM{} is sharpened by $1/Q$, while that of the mean label is exact.
\begin{corollary}[Two modes]
\label{cor:twomode}
Let the error ($\delta$ under (a), $\varepsilon$ under (b)) be constant over the window and equal to $\pm\Delta/2$ with probability $\frac12$ each, independently of $X$. Then $P(f) = Q(f) = \cos(\pi f\Delta)$, and under either structure the transfer from $m$ to $\tilde m$ is negative for $1/(2\Delta) < |f| < 3/(2\Delta)$: there the point label trains the network towards the wrong sign. A Gaussian error with the same variance $\Delta^2/4$ has $P(f) = e^{-\pi^2\Delta^2f^2/2} > 0$ at every frequency. The mean label of a calibrated bank has transfer 1. Under (a), a bank of the point label shifted by $\pm\Delta/2$ with equal weights has transfer $\cos^2(\pi f\Delta) \ge 0$.
\end{corollary}
The phase reversal is a property of multimodal errors that a Gaussian summary hides. If the two modes are one dominant period apart, $\Delta = 1/f_0$, the reversed band is $f_0/2 < |f| < 3f_0/2$. The F3 seismic, from which the D2 wavelet is estimated, peaks near 60\,Hz (Section~\ref{sec:data:f3}), which gives 30--90\,Hz. Cycle skipping produces errors of this kind, and at $c = 2$ the SMC posterior is multimodal (Section~\ref{sec:method:posterior}). In this example, a bank centred on the point label removes the reversal only by attenuating the band further.
\begin{remark}[$\lambda > 0$]
\label{rem:lambda}
Proposition~\ref{prop:bank} concerns the limit $\lambda \to 0$. Expanding the cumulant generating function in \eqref{eq:rml},
\begin{equation*}
\RML_\lambda = -\frac1n\Big[\sum_s \pi_s\ell_s + \frac\lambda2 \Var_\pi(\ell) + O(\lambda^2)\Big].
\end{equation*}
The second term rewards predictors that fit some bank members much better than others. For $\lambda > 0$ the responsibilities of Lemma~\ref{lem:grad} shift weight towards the members that agree with the current network, which amounts to an implicit re-registration, and the population minimizer is in general no longer $(m, \Var(y\mid X))$.
\end{remark}
\paragraph{How much can a bank gain?}
Because $\E[y - m\mid X] = 0$, every predictor $h$ that depends on the data only through $X$ satisfies
\begin{equation*}
\E|B(h - y)|^2 = \E|B(m - y)|^2 + \E|B(h - m)|^2 ,
\end{equation*}
so in population no method beats the oracle in band MSE. If a point-label method converges to $\tilde m$ and a bank method to $m$, the ratio of their band RMSEs is
\begin{equation}
\rho^\star = \Big(1 + \frac{\E|B(\tilde m - m)|^2}{\E|B(m - y)|^2}\Big)^{-1/2},
\label{eq:rhostar}
\end{equation}
and no method can improve on the point label by more than this factor. With errors that do not depend on $t$ or $X$, $\E|B(\tilde m - m)|^2 = \int_{|f|\ge f_c}|1 - P|^2 S_m\dd f$ under (a) and $\int_{|f|\ge f_c}|1 - Q|^2|Q|^{-2}S_m\dd f$ under (b). For Gaussian errors both integrands equal $(2\pi^2\sigma^2f^2)^2 S_m$ to leading order, so the population distortion is of fourth order in $\sigma$. Beyond leading order the integrand under (b) is larger by the factor $e^{4\pi^2\sigma^2f^2}$, so a Berkson error leaves room for a larger gain than a classical error of the same width. The factor grows quickly with frequency: for $\sigma = 2$\,ms it is 1.10 at 25\,Hz and 1.77 at 60\,Hz. The weight $f^4$ also moves the distortion to high frequencies. For the Oracle predictions of Section~\ref{sec:exp:p2r}, 71--73\% of the band power that is coherent with the label lies below 25\,Hz, but the median frequency of the leading-order distortion is 67--72\,Hz. There the integral under (b) is 1.5--1.7 times that under (a) at $\sigma = 1.5$\,ms, 2.1--2.6 times at 2\,ms and 3.3--4.6 times at 2.5\,ms. A bound computed for one structure therefore does not hold for the other. The bound $1/B_a(\sigpost)$ registered for Section~\ref{sec:exp:p2r} is $\rho^\star$ under (a) for Gaussian errors, with the Oracle network's predictions in place of $m$. Section~\ref{sec:exp:p2r} also evaluates $1/B_b$, the same estimate under (b).
\paragraph{Finite samples.}
The label error itself is of first order. For zero-mean errors with variance $\sigma^2$, $\tilde y - y \approx \delta\, y'$ under (a) and $\tilde y - y \approx -\varepsilon\,\tilde y'$ under (b). To this order its conditional mean given $X$ vanishes, and for an error that is constant over the window its in-band variance is $\sigma^2\int_{|f|\ge f_c}(2\pi f)^2 S_y\dd f$. Most of this variance moves label noise that is unpredictable from $X$ anyway. To second order in $\sigma$ and averaged over the window, the conditional variance that a network trained on $\tilde y$ has to absorb grows by the mean of $\sigma^2 m'^2$ under (a) and shrinks by about as much under (b) (Proposition~\ref{prop:tie}). This is a second-order effect, against the fourth-order distortion of $\tilde m$, so with few wells finite-sample effects can outweigh the population bias. The argument is heuristic. It suggests that a tie error with exactly structure (b) would not, to second order, make a network worse than the Oracle, because its labels carry less conditional noise than the true labels. A bank can also change finite-sample learning in ways that \eqref{eq:rhostar} does not capture. A learned variance absorbs the spread of the bank and down-weights samples where the members disagree, and for $\lambda > 0$ the responsibilities re-register the labels during training (Remark~\ref{rem:lambda}). Section~\ref{sec:exp:p2r} compares the measured gains with $\rho^\star$.
\subsection{Coverage of the predictive intervals}
\label{sec:theory:cov}
Let a method predict a mean $\mu$ and a variance $s^2$ at every test sample. For method $j$ let $v_j = \E s^2$, $w_j = \E(y - \mu)^2$ and $\xi_j = v_j/w_j$, with expectations over test samples; $\xi = 1$ means that the predicted variance matches the squared error on average.
\begin{proposition}[Coverage]
\label{prop:coverage}
\begin{enumerate}
\item[(a)] For any methods $j$ and $O$, $\xi_j - \xi_O = (\Delta v - \xi_O\,\Delta w)/w_j$, with $\Delta v = v_j - v_O$ and $\Delta w = w_j - w_O$.
\item[(b)] Let $y$ be stationary, and let (A1) hold with real $0 \le P \le 1$. Compare the point label at its population optimum ($\mu = \tilde m$, $s^2 = \Var(\tilde y\mid X)$) with the oracle at its optimum ($\mu = m$, $s^2 = \Var(y\mid X)$). Then $\xi_O = 1$ and
\begin{equation*}
\xi_j - \xi_O = \frac{2}{w_j}\int P(1 - P)\, S_m\dd f \ \ge 0 .
\end{equation*}
\item[(c)] Under structure (b) of Proposition~\ref{prop:tie}, with $q_t$ independent of $t$ and $y$ stationary, the point label at its population optimum has $\xi_j \le 1$. A calibrated bank has $\xi_j = 1$.
\end{enumerate}
If $y - \mu = sZ/\sqrt{\xi}$ with $Z$ standard normal and independent of $s$, the interval $\mu \pm z s$ covers with probability $2\Phi(z\sqrt{\xi}) - 1$, which increases with $\xi$.
\end{proposition}
Part (a) is an identity and holds for any finite ensemble. A method covers more than the Oracle when its predicted variance exceeds the Oracle's by more than $\xi_O$ times its excess squared error. Parts (b) and (c) describe the population limit. There, classical tie error widens the intervals of a point-label method, Berkson error narrows them, and a calibrated bank matches the oracle. A finite ensemble can be far from this limit, and in our experiments every ensemble is (Section~\ref{sec:exp:p2r}).
\subsection{Scoring against a misregistered reference}
\label{sec:theory:ref}
Field evaluation compares predictions with labels at blind wells, and those labels need a tie as well. Let the reference be $y_{\mathrm{ref}}(t) = y(t + \varepsilon_r)$, where $\varepsilon_r$ is constant over the window, independent of the prediction $\hat y$ and of the true label $y$, and has characteristic function $Q_r$. Let $\hat y$ and $y$ be jointly stationary with cross-spectrum $S_{\hat y y}$, defined by $\E[\hat y(t)\,y(t+\tau)] = \int S_{\hat y y}(f)\,e^{i2\pi f\tau}\dd f$.
\begin{proposition}[Misregistered reference]
\label{prop:reference}
Under these assumptions,
\begin{equation}
\E|B(\hat y - y_{\mathrm{ref}})|^2 = \E|B(\hat y - y)|^2 + 2\int_{|f|\ge f_c}\operatorname{Re}\big[(1 - Q_r(f))\,S_{\hat y y}(f)\big]\dd f .
\label{eq:refbias}
\end{equation}
\end{proposition}
For a symmetric error, $0 \le 1 - Q_r \le 2$, so the reference penalizes in-band agreement with the true label. The extra term depends on the method, so it can change the ranking of two methods, and it does not average out over wells: more blind wells reduce the variance of a comparison but not its bias.
\begin{corollary}[Tolerance]
\label{cor:tolerance}
For two methods $A$ and $B$, let $G$ be the true band-MSE advantage of $A$ and $G_r$ the advantage measured against $y_{\mathrm{ref}}$. Then $G_r - G = 2\int_{|f|\ge f_c}\operatorname{Re}\big[(1 - Q_r)(S_{\hat y_B y} - S_{\hat y_A y})\big]\dd f$. Let $\hat y_A = Hm$ and $\hat y_B = HPm$, with real filters $0 \le H, P \le 1$: $A$ learns the oracle and $B$ the blurred optimum of (a), both shrunk by the same finite-sample factor $H$. Then
\begin{equation*}
G = \int_{|f|\ge f_c} H(1 - P)\big[2 - H(1 + P)\big] S_m\dd f \ \ge 0,
\qquad
G_r = \int_{|f|\ge f_c} H(1 - P)\big[2Q_r - H(1 + P)\big] S_m\dd f .
\end{equation*}
For $H = 1$ and zero-mean Gaussian errors with standard deviations $\sigma$ and $\sigma_r$, $2Q_r - 1 - P = 2\pi^2f^2(\sigma^2 - 2\sigma_r^2) + O(f^4)$, so to leading order the measured advantage has the sign of the true one only if $\sigma_r < \sigma/\sqrt2$.
\end{corollary}
Shrinkage relaxes this condition, because $2Q_r - H(1 + P)$ grows as $H$ decreases. If $B$ is over-sharp instead, as under (b), with $\hat y_B = HKm$ and $K \ge 1$, then $G_r - G = 2\int_{|f|\ge f_c} H(K - 1)(1 - Q_r)S_m\dd f \ge 0$, and the reference exaggerates the advantage of $A$. Independence between $\varepsilon_r$ and the prediction is plausible for a reference from check shots or a vertical seismic profile. A reference tied by synthetic--seismic matching depends on the same seismic as the prediction, and its error adds a covariance term to \eqref{eq:refbias}. Section~\ref{sec:exp:detect} estimates how many blind wells a comparison needs at a given reference error.

View File

@@ -0,0 +1,157 @@
\section{Registration-marginalized learning}
\label{sec:method}
RML has two stages. First, a posterior over the time--depth warp of each training well is computed from anchors and, optionally, from the seismic. No network is involved. Second, a network is trained on a bank of labels drawn from this posterior. At prediction time no warp is needed: the network maps seismic to a property trace on the seismic time axis.
\subsection{Warp prior and anchors}
\label{sec:method:prior}
For well $w$ with depth logs $\phi_w(z)$, $\mathrm{DT}_w(z)$ and $\rho_w(z)$, the time--depth map is
\begin{equation}
t_w(z; b_w, g_w) = t_{w,\mathrm{ref}} + b_w + 2\int_{z_{\mathrm{ref}}}^{z} \mathrm{DT}_w(u)\, e^{g_w(u)}\dd u .
\label{eq:warp}
\end{equation}
The log-slowness correction $g_w$ describes sonic--seismic drift from dispersion, tool effects or washouts. Because $e^{g} > 0$, the map is monotone by construction. $b_w \sim \N(0, \sigma_b^2)$ is a bulk offset. The prior on $g_w$ is a Gaussian process with constant mean $m_g$ and a Mat\'ern-3/2 kernel with scale $\sigma_g$ and length $\ell$. The hyperparameters $(m_g, \sigma_g, \ell)$ are fitted by type-II maximum likelihood on the anchors of the training wells only. $\sigma_a$ and $\sigma_b$ are fixed. Anchors are observed as $t_{wk} = t_w(z_{wk}) + \varepsilon_{wk}$ with $\varepsilon_{wk} \sim \N(0, \sigma_a^2)$. On F3, \eqref{eq:warp} has an important consequence: the same sonic log produces both the label and the time axis, so label and registration are coupled.
Fitted to the F3 anchors, the prior has $m_g = 0.014$, $\sigma_g = 0.10$ and $\ell = 71$\,ms. The fitted bulk spread is $\sigma_b = 19$\,ms. In leave-one-anchor-out tests, 87\% of held-out anchors lie inside the 90\% predictive interval. The synthetic benchmark draws its true warps from this fitted prior (Section~\ref{sec:data:d2}). Type-II maximum likelihood for $\sigma_a$ on F3 gives 0.4\,ms. This value is not reliable, because it treats the markers as exact: they are picks on the same seismic. We therefore use the empirical spread $\sigma_a = 7$\,ms (Section~\ref{sec:data:f3}). On F3, $\sigma_a$ is not identifiable from the data at hand.
\subsection{Physical tie likelihood}
\label{sec:method:tie}
For a training well with seismic trace $\mathbf s_w$ at the well location,
\begin{equation}
p(\mathbf s_w \mid g_w, b_w, \psi) = \N\big(\mathbf s_w;\ \alpha_w \mathbf W_\psi\, \mathbf r_w(b_w, g_w),\ \sigma_n^2 \mathbf I\big),
\end{equation}
where $\mathbf r_w$ is the reflectivity computed from acoustic impedance $\rho_w/\mathrm{DT}_w$ along the warp and blocked to 4\,ms, and $\mathbf W_\psi$ convolves with a 128\,ms statistical wavelet rotated by a constant phase $\psi$. The amplitude $\alpha_w \ge 0$ and the noise level $\sigma_n$ are profiled out, which gives $\log p = -\tfrac n2 \log \mathrm{RSS}$ over the extended window. The residuals are autocorrelated, so this likelihood is overconfident. We temper it by $\gamma = 1/\kappa$, where $\kappa$ is the variance inflation implied by the residual autocorrelation at the best anchor-only sample. The phase $\psi$ is chosen on a $15^\circ$ grid by marginal likelihood on the training wells. Test wells never enter this step.
\subsection{Two tie posteriors}
\label{sec:method:posterior}
\paragraph{Anchor posterior with importance weights (P2).}
We draw $S = 64$ warps per well from the anchor-conditioned posterior. The proposal is a Laplace (Gauss--Newton) approximation, refined by elliptical slice sampling \citep{murray2010ess}. Physical weights $\pi_s \propto p(\mathbf s_w\mid u^{(s)})^{\gamma}$ use the largest $\gamma$ that keeps the effective sample size at least $S/4$.
\paragraph{Sequential Monte Carlo posterior (P2r).}
Importance weights over 64 anchor-conditioned samples cannot move mass to warps that the anchor posterior rarely proposes. In development runs the weighted posterior did not contract to the true warp (Section~\ref{sec:exp:diag}). The second posterior therefore uses tempered sequential Monte Carlo. We introduced it only after the first pre-registered comparison had failed, so it is a deviation from the original protocol, and we report it as one (Section~\ref{sec:exp:diag}). It starts from $P = 1024$ anchor-posterior samples and targets $p(u\mid \text{anchors})\, p(\mathbf s_w\mid u, \psi)^{\gamma}$. The tempering exponent rises from 0 to $\gamma$ in adaptive steps that keep the effective sample size at least $P/2$. Each step uses systematic resampling followed by eight elliptical slice moves. Before the trial we registered a stability criterion: the 95th percentile over $t$ of the difference between mean warps of independent runs must not exceed 0.5\,ms. $P = 1024$ meets it at $c = 1$ on development data. At $c = 2$ the posterior is multimodal and the mean warp is unstable under every configuration we tried. We summarize posterior width by $\sigpost = w_{90}/3.29$, where $w_{90}$ is the 90\% interval width of $\tau(t)$ averaged over the main window and the training wells. No labels are used to compute it.
\subsection{Labels for each warp}
\label{sec:method:labels}
For each warp sample,
\begin{equation}
y_w^{(s)}(t_i) = (\aaf\phi_w)\big(z_w^{(s)}(t_i)\big),
\end{equation}
where $z_w^{(s)}$ is the inverse of $t_w(\cdot\,; u^{(s)})$, which exists because the warp is monotone, and $\aaf$ is an anti-alias filter applied before sampling at 4\,ms. Samples whose warp does not cover the main window receive zero weight. Every method in this paper, including the point-tie baselines and the oracle, builds labels with the same operator. Methods differ only in the warps they use.
\subsection{Training objective}
\label{sec:method:rml}
The network outputs a mean $\mu_\theta$ and a standard deviation $\sigma_\theta$ for every sample. For a window of $n$ samples and a bank of $S$ labels with weights $\pi_s > 0$, $\sum_s \pi_s = 1$, let
\begin{equation}
\ell_s = \sum_{i=1}^{n} \log\N\big(y_{s,i};\, \mu_i, \sigma_i^2\big), \qquad
\RML_\lambda = -\frac{1}{\lambda n}\log\sum_{s=1}^{S}\pi_s\, e^{\lambda \ell_s}, \qquad
\RML_\infty = -\frac1n\max_s \ell_s .
\label{eq:rml}
\end{equation}
The training loss is the mean of $\RML_\lambda$ over windows and wells.
\paragraph{Choice of $\lambda$.}
With $\lambda = 1$, differences between bank members are $O(n)$ and the log-sum-exp puts almost all weight on one member. Residuals are also autocorrelated, so a window holds less information than $n$ independent observations. If two members differ by $\Delta = \sum_i d_i$, and $d_i$ is a product of two zero-mean Gaussian processes with common autocorrelation $\rho$, then $\Var\Delta \approx n \Var(d)\,\tau_c$ with $\tau_c = 1 + 2\sum_{k\ge1}\rho(k)^2$. Setting $\lambda = 1/\tau_c$ gives $\lambda\Delta$ the variance of a log-likelihood difference over $n/\tau_c$ independent observations. This is the simplest magnitude adjustment of a composite likelihood \citep{pauli2011composite,ribatet2012composite}. Residuals are not available before training, so we estimate $\rho$ from the pooled autocorrelation of the high-passed training labels, truncated at the first non-positive lag. This gives $\tau_c \approx 2.7$ samples and $\lambda \approx 0.37$, nearly constant across the grid. The choice is a heuristic. We fixed it before the experiments and make no claim about it.
\paragraph{Special cases.}
The loss \eqref{eq:rml} contains the common alternatives. All five statements are exact and are checked numerically in the code's unit tests. Proofs are in Appendix~\ref{app:proofs}.
\begin{lemma}[Point tie]
\label{lem:s1}
If $S = 1$, or all bank members coincide, then $\RML_\lambda = -\ell/n$, the Gaussian negative log-likelihood, for every $\lambda$.
\end{lemma}
\begin{lemma}[Between hard-min and mixture mean]
\label{lem:sandwich}
Let $M(\lambda) = \lambda^{-1}\log \E_\pi e^{\lambda\ell}$. Then $\RML_\lambda = -M(\lambda)/n$ is non-increasing in $\lambda$, with
\begin{equation}
-\frac1n\max_s\ell_s \le \RML_\lambda \le -\frac1n\sum_s\pi_s\ell_s ,
\end{equation}
and it tends to the right-hand side as $\lambda \to 0$ and to $\RML_\infty$ as $\lambda \to \infty$. For uniform $\pi$, $0 \le \RML_\lambda - \RML_\infty \le \log S/(\lambda n)$.
\end{lemma}
As $\lambda \to 0$, the optimal mean is the regression of the $\pi$-weighted mean label on $X$, and the optimal variance adds the spread of the bank. Whether this blurs the predictor depends on how the bank relates to the true warp. If the members scatter around a point tie whose error satisfies (A1), the mean label is blurred further. If the bank is the calibrated posterior, the population optimum is that of the true warp (Proposition~\ref{prop:bank}).
\begin{lemma}[Gradient]
\label{lem:grad}
$\nabla_\theta \RML_\lambda = -\frac1n\sum_s r_s \nabla_\theta \ell_s$ with responsibilities $r = \operatorname{softmax}(\log\pi + \lambda\ell)$.
\end{lemma}
Each gradient step is therefore a generalized M-step whose weights are computed at the current $\theta$.
\begin{lemma}[Shift-tolerant losses]
\label{lem:shift}
With a bank of the point-tie label shifted by every integer lag in $\pm K$ samples and uniform $\pi$, $\RML_\infty$ is the hard-min shift loss with learned variance, and $\RML_{1/\tau_c}$ is its soft-min version.
\end{lemma}
\begin{lemma}[Soft-DTW]
\label{lem:sdtw}
Let $D_{ij} = -\log\N(y_j; \mu_i, \sigma_i^2)$, let $\mathcal P$ be the set of monotone alignment paths from $(0,0)$ to $(n-1,n-1)$ within a Sakoe--Chiba band, and let $\langle A, D\rangle_w$ be the path cost with symmetric step weights (diagonal steps counted twice; \citealp{sakoe1978dp}). For soft-DTW with these steps \citep{cuturi2017softdtw},
\begin{equation}
\frac{\mathrm{sDTW}_\gamma(D)}{2n} = \RML_{\lambda = 2/\gamma}\Big[\text{bank} = \mathcal P,\ \pi \text{ uniform},\ \ell_A = -\tfrac12\langle A, D\rangle_w\Big] - \frac{\gamma}{2n}\log|\mathcal P| .
\end{equation}
\end{lemma}
The last term does not depend on $\theta$. On the diagonal path, $\ell_A$ equals the Gaussian log-likelihood of the window. Soft-DTW is therefore RML over every monotone alignment in the band, with a uniform prior, no anchors and no physics, at $\lambda = 2/\gamma$; with $\gamma = 0.1$ this is $\lambda = 20$, much closer to the hard minimum than $\lambda \approx 0.37$. Symmetric steps give every path the same total weight $2n$. With standard steps, longer paths visit more cells and, since the negative log-likelihood can be negative, would be preferred. DILATE \citep{leguen2019dilate} adds a temporal-distortion term $\langle A^\star, \Omega\rangle$ with $A^\star = \nabla_D \mathrm{sDTW}_\gamma$ and $\Omega_{ij} = ((i-j)/n)^2$. Its gradient is a Hessian--vector product, which we compute by forward-mode differentiation of the backward pass \citep{mensch2018diffdp}. Our version differs from the original in two ways: the cost is the Gaussian negative log-likelihood, and the steps are symmetric.
\subsection{Network and training}
\label{sec:method:train}
All learned methods share one backbone and differ only in their labels and loss. The input is a $3\times3$ trace patch around the well (nine channels), z-scored per channel within each well. Three dilated 1-D convolutions (kernel 5, dilations 1, 2 and 4, 64 channels) feed a two-layer bidirectional GRU. A $1\times1$ head with a $1\times1$ skip connection outputs $\mu$ and $\sigma$ (softplus, $\sigma \ge 10^{-3}$). Dropout is 0.05. We train with Adam (learning rate $5\times10^{-3}$, gradient clipping at 5) on full batches of all training wells. Losses are computed on 64-sample windows starting at samples $0, 2, \dots, 62$ of the 126-sample main window. Labels are standardized by the mean and standard deviation of the anti-aliased log over the training wells. These statistics do not depend on the tie. The number of iterations is selected separately for each method from $\{125, 250, 500, 1000, 2000\}$ by total RMSE on the development realizations; on F3 it is selected by inner validation (Appendix~\ref{sec:exp:f3}). Every method has the same candidate set, and band metrics are not used for selection. Ensembles average five seeds (on F3, three inner models $\times$ five seeds), with $\mu = \overline{\mu_s}$ and $\sigma^2 = \overline{\sigma_s^2} + \Var_s \mu_s$.
\subsection{Compared methods}
\label{sec:method:baselines}
Table~\ref{tab:methods} lists the methods. In the language of Lemmas~\ref{lem:s1}--\ref{lem:sdtw}, the B3 family is RML with $S = 1$ at different point ties. B4 is RML with anchor-free banks, and M1, M2 and \mRML{} are RML with anchor-conditioned banks.
\begin{table}[t]
\centering
\caption{Compared methods. All learned methods use the backbone of Section~\ref{sec:method:train}. Bank: labels entering \eqref{eq:rml}.}
\label{tab:methods}
\small
\begin{tabular}{lp{0.5\linewidth}l}
\toprule
ID & Labels / bank & Loss \\
\midrule
\multicolumn{3}{l}{\emph{Field baselines (F3 only)}} \\
B0a & depth--time trend fitted on training wells (no seismic) & -- \\
B0b & ridge, random forest or gradient boosting on seismic attributes and TWT & -- \\
B1 & model-based impedance inversion with a well-interpolated low-frequency model, then linear $\phi$--impedance & -- \\
B2 & backbone with a composite loss$^{\dagger}$ & composite \\
\midrule
\multicolumn{3}{l}{\emph{Point ties ($S = 1$)}} \\
B3a & sonic integration from one shallow anchor & NLL \\
B3b & marker-calibrated sonic through the anchors & NLL \\
B3c & B3b plus local shifts from synthetic--seismic correlation & NLL \\
B3c-R & B3c with the SMC-estimated wavelet phase & NLL \\
B3d & weighted mean warp of the P2 anchor posterior & NLL \\
\mPM & mean warp of the SMC posterior & NLL \\
Oracle & true warp (synthetic only; a ceiling, not a competitor) & NLL \\
\midrule
\multicolumn{3}{l}{\emph{Anchor-free alignment losses (labels B3b)}} \\
B4a & B3b shifted by $\pm 8$ samples, uniform $\pi$ & $\RML_\infty$ \\
B4b & as B4a & $\RML_{1/\tau_c}$ \\
B4c & all monotone alignments in a $\pm8$ band & soft-DTW, $\gamma = 0.1$ \\
B4d & as B4c & DILATE, $\alpha = 0.5$ \\
\midrule
\multicolumn{3}{l}{\emph{Anchor-conditioned banks}} \\
M1 & 64 anchor-posterior warps, uniform $\pi$ & $\RML_{1/\tau_c}$ \\
M2 & as M1, tempered physical weights & $\RML_{1/\tau_c}$ \\
\mRML & 64 SMC particles, uniform $\pi$ & $\RML_{1/\tau_c}$ \\
\midrule
B5 & five-seed ensemble of B3b & NLL \\
\bottomrule
\end{tabular}
\smallskip
\footnotesize $^{\dagger}$Labels as B3b; deterministic output. Loss: Huber regression loss $+\,0.60$ correlation $+\,0.05$ first-difference $+\,0.10$ standardized-shape $+\,0.10$ variance-matching $+\,0.20$ best-shift MSE (minimum over shifts of $\pm 8$ samples).
\end{table}
\subsection{Metrics}
\label{sec:method:metrics}
Accuracy is reported in porosity units (p.u., porosity $\times 100$). We split every trace into a low band ($|f| < f_c$) and a seismic band ($|f| \ge f_c$, $f_c = 6$\,Hz). The split uses a zero-phase fourth-order Butterworth filter. On F3, energy below 5\,Hz is 0.2--0.5\% of the total. The primary metrics are RMSE and Pearson correlation in the seismic band (band RMSE, band PCC): registration errors act there, while the low band is dominated by the trend. We also report total RMSE and PCC and the band standard-deviation ratio. Calibration is described by the coverage of central intervals at 50, 80, 90 and 95\%, the calibration error (mean absolute deviation of coverage from nominal over these levels), the Gaussian negative log-likelihood and the CRPS. Warp accuracy (synthetic only) is the RMSE of $\tau(t)$ against the true warp over the main window, together with 90\% coverage. Statistics are computed per test well and then macro-averaged. Intervals are 95\% bootstrap intervals over realizations (2000 resamples). On F3 the time samples within a well are not independent and there are only four wells. Field results are therefore descriptive, and we compute no per-sample $p$-values.

View File

@@ -0,0 +1,251 @@
\section{Experiments}
\label{sec:experiments}
We ran two pre-registered synthetic experiments, in order, and then pre-registered field tests on F3 and Volve (Section~\ref{sec:exp:scope}; details in Appendix~\ref{app:field}). Before each main run, the protocol (grid, methods, iteration budgets, pass rules) was locked by a SHA-256 hash, and the scripts refuse to run if the hash does not match. The two synthetic protocols were also committed and tagged in version control before their main runs. The field protocols were committed only after their runs, so for them the record of timing is the time stamp inside the lock file (Appendix~\ref{app:field}). In the synthetic experiments, every design choice was made on two development realizations (900 and 901), which are never used for results. Test labels were never used to choose a shift, checkpoint or hyperparameter. In the synthetic experiments, a comparison \emph{improves} if the candidate's seismic-band RMSE is at most 0.90 times that of the best competitor, \emph{or} its band PCC is at least 0.05 higher. Here ``best'' means the competitor with the smallest mean band RMSE in that cell. A cell \emph{passes} if the comparison improves in at least 4 of 5 seeds (each averaged over realizations) and in more than half of the realizations (each averaged over seeds). All cells use eight test wells.
\subsection{Experiment 1: anchor-posterior banks (gate G-B)}
\label{sec:exp:p2}
\paragraph{Design.}
SNR 10\,dB with full anchors; drift $c \in \{0, 0.5, 1, 2\}$; $N \in \{2, 4, 8, 16\}$; realizations 0--7; five seeds. The candidate was M2. The competitors were all point ties (B3a--B3d) and all anchor-free alignment losses (B4a--B4d). The gate required M2 to pass in at least 3 of the 4 cells at $c = 1$. In addition, at $c = 0$ the ratio of M2 to the best competitor had to be at most 1.02, both averaged over $N$ and for each $N$.
\paragraph{Result: the gate failed.}
No cell at $c = 1$ passed. The ratio of M2 to the best competitor (B3c in every cell) was 1.045, 1.025, 1.020 and 0.985 for $N = 2$, 4, 8 and 16, with band PCC differences between $-0.018$ and $+0.003$ (Fig.~\ref{fig:p2phase}). The zero-drift guard also failed: the macro ratio was 1.039, and the per-$N$ ratios against B3d were 1.015, 1.045, 1.051 and 1.056. Table~\ref{tab:p2} gives band RMSE for every method at $c = 1$. M2 was about as good as the best point tie and B3d, and it stayed 20--24\% above the oracle. We report this verdict as it stands; nothing in the second experiment changes it.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{p2_phase.pdf}
\caption{Experiment 1 (gate G-B). (a) Band RMSE of M2 divided by that of the best competitor, and (b) band PCC difference, over drift factor $c$ and number of training wells $N$. Cells show the mean over 8 realizations $\times$ 5 seeds, the 95\% bootstrap interval over realizations, and, in (a), the best competitor and whether the cell passed the pre-registered rule. The outlined row ($c = 1$) is the F3-like drift level.}
\label{fig:p2phase}
\end{figure}
\begin{table}[t]
\centering
\caption{Experiment 1 at F3-like drift ($c = 1$, SNR 10\,dB, full anchors): band RMSE and band PCC, mean over 8 realizations $\times$ 5 seeds.}
\label{tab:p2}
\small
\begin{tabular}{llcccc}
\toprule
& & \multicolumn{2}{c}{band RMSE (p.u.)} & \multicolumn{2}{c}{band PCC} \\
\cmidrule(lr){3-4}\cmidrule(lr){5-6}
Family & Method & $N = 4$ & $N = 16$ & $N = 4$ & $N = 16$ \\
\midrule
Point tie & B3a & 1.480 & 1.420 & 0.202 & 0.258 \\
& B3b & 0.937 & 0.774 & 0.729 & 0.826 \\
& B3c & \textbf{0.716} & 0.569 & \textbf{0.855} & 0.914 \\
& B3d & 0.759 & 0.627 & 0.833 & 0.891 \\
\midrule
Anchor-free & B4a (hard-min shift) & 1.304 & 1.184 & 0.429 & 0.526 \\
& B4b (soft-min shift) & 1.289 & 1.103 & 0.436 & 0.583 \\
& B4c (soft-DTW) & 0.978 & 0.743 & 0.704 & 0.838 \\
& B4d (DILATE) & 0.967 & 0.731 & 0.714 & 0.844 \\
\midrule
Anchor bank & M1 & 0.805 & 0.589 & 0.809 & 0.905 \\
& M2 & 0.735 & \textbf{0.560} & 0.849 & \textbf{0.917} \\
\midrule
Ceiling & Oracle & 0.612 & 0.451 & 0.897 & 0.948 \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Anchor-free alignment losses.}
At $N = 4$, all four anchor-free losses were worse than B3b, the point tie whose labels they start from. Hard-min and soft-min shift banks (B4a, B4b) were 38--53\% worse than B3b at both $N$. At $N = 16$, soft-DTW and DILATE were 4--6\% better than B3b, but still far behind B3c and M2. This is what Proposition~\ref{prop:ident} predicts. Within the shift range, the loss cannot tell a better alignment from a jointly shifted network and label, so the extra freedom fits noise rather than recovering timing.
\paragraph{Anchors are necessary (H4).}
At $c = 1$, $N = 4$ we removed the anchors from M1 and M2 and kept only the warp prior ($\sigma_b = 50$\,ms) and, for M2, the tie likelihood. To favour the anchor-free variant, it was given the true (zero) wavelet phase. Warp RMSE rose from 3.15 to 31.1\,ms for M2 (ratio 9.9, 95\% CI [8.3, 11.4]) and from 3.71 to 33.0\,ms for M1. Band RMSE rose from 0.735 to 1.398 p.u.\ for M2 (ratio 1.90, CI [1.80, 2.04]) and from 0.805 to 1.594 for M1. The pre-registered hypothesis that anchors are necessary was not rejected. The size of the warp error is consistent with Proposition~\ref{prop:ident}: with $\sigma_b = 50$\,ms and $N = 4$, $\sd(\beta) \approx 25$\,ms.
\paragraph{Calibration (H3).}
The pre-registered hypothesis that M2 ensembles are better calibrated than B5 (B3b ensembles) was rejected. Pooled over $N$ at $c = 1$, the calibration error was 0.278 for M2-ens against 0.230 for B5 (difference 0.048, 95\% CI [0.035, 0.061]). Every ensemble under-covered.
\subsection{Diagnosis on development data and deviation}
\label{sec:exp:diag}
Gate G-B prescribed a time-boxed diagnosis followed by a pivot. Using only the development realizations, we found that the failure lay in registration, not in the loss. The M2 posterior was 64 anchor-conditioned samples reweighted by tempered tie likelihoods. It did not contract to the true warp: at $c = 1$, its warp RMSE was 3.25\,ms with a 90\% interval width of 11.6\,ms. This is comparable to the correlation-based point tie B3c (3.85\,ms), which explains why M2 $\approx$ B3d $\approx$ B3c. The SMC posterior of Section~\ref{sec:method:posterior}, with the wavelet phase re-estimated from its evidence, reached a warp RMSE of 0.56\,ms with 97\% coverage of the 90\% interval, and labels at its mean warp were close to the oracle. Experiment 1 therefore could not test whether posterior labels help, because its posterior was not informative enough.
\paragraph{Deviation.}
Re-running on new realizations was not among the options pre-registered for a G-B failure. The second experiment is a new pre-registration, designed \emph{after} seeing the first failure, using development realizations only, and run on realizations 8--15, which had not been generated when its protocol was locked. The verdict of Experiment 1 stands. Two potential stresses were not tested: the bulk-offset prior $\sigma_b$ was neither learned nor varied, and a rock-physics misspecification stress was cut for time. The anchor uncertainty $\sigma_a$ was varied and is reported below.
\subsection{Experiment 2: SMC tie posterior}
\label{sec:exp:p2r}
\paragraph{Design.}
Five observation regimes (Section~\ref{sec:data:d2}); $c \in \{0, 1, 2\}$; $N \in \{4, 16\}$; realizations 8--15; five seeds. Registration and SMC were run once per (realization, $c$, $N$). The protocol pre-registered three questions:
\begin{itemize}
\item \textbf{H2a.} Do labels at the SMC mean warp (\mPM) beat the best point tie (B3b, B3c, B3c-R)? This is decided per full-anchor regime (R10, R0, Rm5). A regime passes if both cells at $c = 1$ pass and the zero-drift guard holds. A secondary comparison adds B3d, the Experiment~1 posterior mean, to the competitors.
\item \textbf{H2b.} Does RML on the SMC bank (\mRML) beat \mPM{} when the posterior is wide ($\sigpost \ge 1.5$\,ms)? At $N = 16$ the protocol requires that (a) at least two thirds of wide cells pass; (b) the Spearman correlation between $\sigpost$ and the ratio \mRML/\mPM{} over all cells is negative; and (c) the mean ratio over narrow cells is at most 1.02.
\item \textbf{$\sigma_a$ scope.} H2a is repeated at R10, $c = 1$ with every method registered using $\sigma_a = 3.5$ or 14\,ms, while the data are generated with 7\,ms.
\end{itemize}
Cells at $c = 2$ are reported with an ``unstable posterior'' flag and are not used as primary evidence (Section~\ref{sec:method:posterior}). Calibration was not tested as a hypothesis. Development runs had shown that the seed ensembles under-cover more when trained on better labels, so the protocol made calibration descriptive only.
\paragraph{H2a: posterior-mean labels beat the best point tie.}
All three full-anchor regimes passed (Table~\ref{tab:h2a}; Fig.~\ref{fig:p2rgrid} shows every method relative to the Oracle). At $c = 1$, \mPM{} reduced band RMSE relative to the best point tie by 14\% and 22\% at R10 ($N = 4$, 16), by 11\% at R0 and by 8\% at Rm5. At Rm5 the ratio stayed above 0.90 and the cells passed on band PCC ($+0.10$ and $+0.09$). Most of the gain is already present without drift. At $c = 0$ the macro ratios are 0.81, 0.85 and 0.88, against 0.78--0.92 at $c = 1$. Part of the advantage therefore comes from the seismic-conditioned, phase-estimated tie itself, not from correcting drift. When B3d is added as a competitor, H2a holds at R10 (2/2 cells; macro ratio at $c = 0$ is 0.94), holds in 1 of 2 cells at R0 and fails at Rm5 (0/2; ratios 0.98 and 0.97 against B3d). The claim that SMC labels beat the anchor posterior of Experiment~1 is therefore limited to high SNR. \mRML{} under the same rule passed all three regimes against point ties and R10 and R0 with B3d included.
\begin{table}[t]
\centering
\caption{H2a at $c = 1$: band RMSE of \mPM{} divided by that of the best point tie (95\% bootstrap CI over realizations) and band PCC difference. Zero-drift macro: same ratio at $c = 0$, averaged over $N$ (guard $\le 1.02$). Last column: verdict with B3d added as a competitor.}
\label{tab:h2a}
\small
\begin{tabular}{lcccccc}
\toprule
& \multicolumn{2}{c}{$N = 4$} & \multicolumn{2}{c}{$N = 16$} & & \\
\cmidrule(lr){2-3}\cmidrule(lr){4-5}
Regime & ratio & $\Delta$PCC & ratio & $\Delta$PCC & zero-drift & with B3d \\
\midrule
R10 & 0.857 [0.805, 0.922] & +0.039 & 0.782 [0.748, 0.813] & +0.037 & 0.809 & 2/2 \\
R0 & 0.888 [0.856, 0.926] & +0.078 & 0.888 [0.870, 0.909] & +0.060 & 0.851 & 1/2 \\
Rm5 & 0.915 [0.883, 0.953] & +0.102 & 0.923 [0.908, 0.940] & +0.089 & 0.878 & 0/2 \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{The gain requires a correct $\sigma_a$.}
With misspecified anchor uncertainty, no cell passed (Table~\ref{tab:sigmaa}). Over-trusting the anchors ($\sigma_a = 3.5$\,ms) made \mPM{} 14\% \emph{worse} than the best point tie at $N = 16$. Under-trusting them (14\,ms) left a 7\% gain at $N = 16$ that did not pass. The SMC posterior was miscalibrated in both directions. With 3.5\,ms the warp RMSE was 4.8\,ms against a $\sigpost$ of 2.5\,ms (90\% coverage 0.62). With 14\,ms it was 2.8\,ms against 0.9\,ms (coverage 0.52). With the correct 7\,ms it was 0.63\,ms (coverage 0.89). On F3 the markers are not independent check shots, and $\sigma_a$ cannot be identified from them. This is the main risk for transfer to the field.
\begin{table}[t]
\centering
\caption{$\sigma_a$ arm (R10, $c = 1$; data generated with $\sigma_a = 7$\,ms; every method registered with $\sigma_a^{\mathrm{reg}}$). Ratio: band RMSE of \mPM{} divided by that of the best point tie. Warp RMSE and coverage: SMC posterior on the training wells, $N = 16$.}
\label{tab:sigmaa}
\small
\setlength{\tabcolsep}{4pt}
\begin{tabular}{ccccccc}
\toprule
$\sigma_a^{\mathrm{reg}}$ (ms) & ratio $N = 4$ & ratio $N = 16$ & cells pass & $\sigpost$ (ms) & warp RMSE (ms) & cov$_{90}$ \\
\midrule
3.5 & 0.977 [0.908, 1.038] & 1.141 [1.094, 1.194] & 0/2 & 2.52 & 4.80 & 0.62 \\
7 & 0.857 [0.805, 0.922] & 0.782 [0.748, 0.813] & 2/2 & 0.59 & 0.63 & 0.89 \\
14 & 0.985 [0.897, 1.067] & 0.928 [0.867, 1.004] & 0/2 & 0.92 & 2.81 & 0.52 \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{H2b: RML helps when the posterior is wide.}
At $N = 16$ all three tests passed (Table~\ref{tab:h2b}, Fig.~\ref{fig:h2b}a). All 8 wide cells passed, the ratio decreased with $\sigpost$ (Spearman $\rho = -0.85$, one-sided permutation $p < 0.001$), and the mean ratio over narrow cells was 0.996. The gains in wide cells ranged from 2\% (Rm5, $c = 1$) to 11\% (R10tb, $c = 1$). At $c = 2$ they reached 33\% (R10tb), but those cells are flagged unstable. At $N = 4$, which was reported but not used for the verdict, 6 of 8 wide cells passed ($\rho = -0.77$, narrow mean 1.001).
\paragraph{Comparison with the population bound.}
The column $1/B_a$ of Table~\ref{tab:h2b} is the registered bound: $\rho^\star$ of \eqref{eq:rhostar} for Gaussian classical error at $\sigpost$, computed by blurring the Oracle's predictions. It is the largest gain over the point label that removing a population blur could give (Section~\ref{sec:theory:post}). The measured ratio is below it in 7 of the 8 wide cells (Fig.~\ref{fig:h2b}b). At Rm5, $c = 1$, for example, the bound allows no gain (1.000), yet RML gained 2\%. The exception is R10tb at $c = 2$, where $\sigpost$ lies beyond the 6\,ms edge of the grid on which $B$ was computed. The tabulated value is therefore $1/B_a(6\,\mathrm{ms})$, and at $\sigpost$ itself the bound is 0.481.
The registered structure is not the one expected for \mPM{}, whose labels sit at the posterior-mean warp. The natural idealization for the error of a posterior mean is the Berkson structure (b), and under (b) the bound is lower (Section~\ref{sec:theory:post}). The column $1/B_b$ gives this bound, computed post hoc in the same way but by sharpening the Oracle's predictions, at $\sigpost$ itself. The measured ratio is below it in 3 of the 8 wide cells, all at $c = 1$ (R0, R0h and R10tb). In R0h and R10tb the margin is less than 0.004, well inside the 95\% interval of the ratio. Sharpening also amplifies the Oracle's own estimation error, which lowers $1/B_b$, most of all at $c = 2$. Two variants limit this amplification. One holds the gain at its 60\,Hz value above 60\,Hz. The other replaces the spectrum of the Oracle's predictions by their cross-spectrum with the true labels. Both select the same three cells, and with the cross-spectrum the (a) bound is exceeded in only 5 of the 8 cells.
Both bounds are evaluated at the posterior width, which understates the error of an overconfident posterior. Evaluated instead at the measured warp error of \mPM{} on the training wells, the ratio is still below the (a) bound in 6 of the 8 cells but below the (b) bound in at most one (R0, $c = 1$, under the two variants). An excess over the population bound is therefore not established. It appears under the classical structure, and under the Berkson structure it is confined to $c = 1$ and mostly disappears at the measured warp error. Whether the error of the mean warp has the Berkson structure was not tested (Section~\ref{sec:exp:mech}).
The Oracle's advantage over \mPM{} can be compared with the same bounds. These ratios are post hoc and computed from the registered band RMSE of every method. At $c = 1$, $N = 16$, the Oracle's band RMSE was 0.93, 0.92 and 0.93 times that of \mPM{} at R0, R0h and Rm5, and 0.76 times at R10tb. These ratios are below the (a) bound in all four cells, below the (b) bound at $\sigpost$ in three or four of them, depending on the estimator, and below the (b) bound at the measured warp error in one or two. Part of the gap is not caused by registration at all. At $c = 0$, where the SMC warp RMSE on the training wells was 0.2--0.7\,ms and every bound is within 0.4\% of 1, the Oracle was still 1--3\% better than \mPM{} at $N = 16$. The two also differ in training length, which was selected on development data (500 and 250 iterations; Section~\ref{sec:method:train}).
In the wide cells at $N = 16$, \mRML{} closed 27--46\% of the gap between \mPM{} and the Oracle at $c = 1$, and 39--65\% at $c = 2$. It never reached the Oracle. Its band RMSE stayed 4--6\% above the Oracle's at R0, R0h and Rm5, and 17\% ($c = 1$) and 63\% ($c = 2$) above it at R10tb. The confirmatory experiments do not show where the gain comes from. If the error of the mean warp has the Berkson structure, most of the gain is within what removing the population sharpening of \mPM{} could give. A bank can also gain in finite samples. It acts as label augmentation: the network cannot memorize a single misregistered label, and the learned variance absorbs the spread of the bank and down-weights samples where the members disagree. For $\lambda > 0$ the responsibilities re-register the labels during training (Remark~\ref{rem:lambda}). When the posterior is multimodal, the error of the mean warp is not Gaussian, and the gain available to a bank can exceed the Gaussian bound (Corollary~\ref{cor:twomode}). Section~\ref{sec:exp:mech} examines these sources in an exploratory analysis.
\begin{table}[t]
\centering
\caption{H2b at $N = 16$, wide cells ($\sigpost \ge 1.5$\,ms): band RMSE of \mRML{} divided by that of \mPM{} (95\% CI); the population bounds at $\sigpost$ for Gaussian classical error, $1/B_a$ (registered), and for Gaussian Berkson error, $1/B_b$ (post hoc), computed by blurring and by sharpening the Oracle's predictions (Section~\ref{sec:theory:post}); and the SMC warp error on the training wells. A ratio below a bound is a larger gain than removing that population distortion could give. $\dagger$: unstable posterior ($c = 2$). $\ddagger$: $\sigpost$ exceeds the 6\,ms grid of $B$; the entry is $1/B_a(6\,\mathrm{ms})$, and the bound at $\sigpost$ is 0.481.}
\label{tab:h2b}
\small
\begin{tabular}{lcccccccc}
\toprule
Regime & $c$ & $\sigpost$ (ms) & ratio & 95\% CI & $1/B_a$ & $1/B_b$ & warp RMSE (ms) & cov$_{90}$ \\
\midrule
R0 & 1 & 1.53 & 0.967 & [0.956, 0.979] & 0.999 & 0.982 & 1.86 & 0.86 \\
R0h & 1 & 1.72 & 0.970 & [0.953, 0.989] & 0.996 & 0.972 & 2.36 & 0.83 \\
R10tb & 1 & 1.92 & 0.890 & [0.866, 0.915] & 0.964 & 0.893 & 4.78 & 0.53 \\
Rm5 & 1 & 2.56 & 0.982 & [0.966, 0.995] & 1.000 & 0.904 & 2.91 & 0.86 \\
R0 & 2$^\dagger$ & 2.79 & 0.952 & [0.940, 0.962] & 0.968 & 0.768 & 2.72 & 0.94 \\
Rm5 & 2$^\dagger$ & 3.96 & 0.964 & [0.953, 0.977] & 0.980 & 0.285 & 3.92 & 0.91 \\
R0h & 2$^\dagger$ & 4.18 & 0.904 & [0.889, 0.925] & 0.910 & 0.132 & 4.10 & 0.94 \\
R10tb & 2$^\dagger$ & 11.49 & 0.667 & [0.615, 0.713] & 0.634$^\ddagger$ & $<$0.001 & 19.08 & 0.62 \\
\bottomrule
\end{tabular}
\end{table}
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{p2r_h2b.pdf}
\caption{H2b. (a) Band RMSE of \mRML{} divided by that of \mPM{} against the posterior width $\sigpost$, for every regime $\times$ $c$ $\times$ $N$ cell (filled: $N = 16$; open: $N = 4$; marker shape: drift factor $c$). Bars are 95\% bootstrap intervals over realizations. The dashed line is the pre-registered 1.5\,ms threshold for wide cells. (b) The same ratio against the registered population bound $1/B_a(\sigpost)$ for classical error, computed from Oracle predictions (Section~\ref{sec:theory:post}). Cells below the diagonal gained more than removing a classical population blur could give. The bound $1/B_b$ for Berkson error, the natural idealization for labels at the posterior-mean warp, is lower, and at $N = 16$ only three wide cells, all at $c = 1$, lie below it (Table~\ref{tab:h2b}). For R10tb at $c = 2$ the bound is evaluated at the 6\,ms edge of its grid. Cells at $c = 2$ have an unstable posterior and are not primary evidence.}
\label{fig:h2b}
\end{figure}
\paragraph{Posterior quality.}
The SMC posterior was close to calibrated when the anchors were dense and $\sigma_a$ was correct. At $c = 1$, $N = 16$, the 90\% coverage was 0.89 at R10, 0.86 at R0 and 0.86 at Rm5. With only top and bottom anchors (R10tb) it was overconfident: warp RMSE 4.8\,ms against $\sigpost = 1.9$\,ms, with 90\% coverage 0.53. RML still gained the most in this regime. The bank covers part of the error even when its width understates it.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{p2r_grid.pdf}
\caption{Experiment 2 overview. Band RMSE of each method divided by that of the Oracle (true warp), by anchor regime and drift factor $c$, for (a) $N = 4$ and (b) $N = 16$ training wells. Each entry is the mean over 8 realizations $\times$ 5 seeds. The colour scale is clipped at 2.0; R10tb at $c = 2$ reaches 3.15. \mPM{} is B3d-Sa and \mRML{} is M2-Sa.}
\label{fig:p2rgrid}
\end{figure}
\paragraph{Predictive uncertainty (descriptive).}
Every five-seed ensemble under-covered. At R10, $c = 1$, $N = 16$, the 90\% coverage was 0.79 for B5, 0.58 for \mPM-ens, 0.58 for \mRML-ens and 0.48 for Oracle-ens, with calibration errors 0.114, 0.300, 0.291 and 0.379. Ensembles trained on better labels predicted smaller $\sigma$ and covered less.
Table~\ref{tab:t4} examines this pattern post hoc, with the dispersion ratio $\xi$ of Section~\ref{sec:theory:cov} computed from the saved test-well predictions. Every ensemble was too narrow: $\xi$ was 0.19 for the Oracle and at most 0.66 (B5), against 1 for a matched second moment. Because $\xi_O$ is small, Proposition~\ref{prop:coverage}(a) requires only a small excess of predicted variance for a method to cover more than the Oracle. Each method had a larger $\xi$ and a higher coverage than the Oracle in 80--99\% of the 240 realization cells. The ordering follows training length as much as label quality. At R10, B3c-R had a median warp error of 3.5\,ms on the training wells, against 0.55\,ms for the SMC mean warp. It was trained for the Oracle's 500 iterations and reached the same $\xi$ as \mPM{} at 250. Over all regimes its excess over the Oracle was the smallest of any method (0.02--0.03). Most of the excess of \mPM{} and \mRML{} was already present at $c = 0$, where the median warp error of their labels was 0.34\,ms. Within the 250-iteration group, the methods with worse labels (B3d, B3c) had the larger excess, as Proposition~\ref{prop:coverage}(b) predicts. Training length acts on its own. On the development realizations of Experiment~1 (SNR 10, $c = 1$, $N = 16$), the 90\% coverage of single Oracle models fell from 0.47 after 125 iterations to 0.23 after 500 and 0.10 after 2000. Their mean $\sigma$ fell by a factor of five, while their RMSE varied by less than 10\%. In Experiment~2 training length and label source are confounded, so parts (b) and (c) of Proposition~\ref{prop:coverage} are not tested. A seed ensemble of a heteroscedastic network does not carry the tie posterior to the test wells. We make no calibration claim.
\begin{table}[t]
\centering
\caption{Dispersion of the five-seed ensembles (post hoc, descriptive). Left: R10, $c = 1$, $N = 16$. Iterations: training length selected on development data. rms $s$: root mean predicted variance $\overline{\sigma_s^2} + \Var_s\mu_s$; RMSE of the ensemble mean (p.u.); $\xi$: dispersion ratio of Section~\ref{sec:theory:cov}, averaged over realizations; cov$_{90}$: coverage of the central 90\% Gaussian interval. Right: mean excess $\xi_j - \xi_O$ over the Oracle in the same realization, averaged over the five regimes, both $N$ and eight realizations, by drift factor $c$.}
\label{tab:t4}
\small
\begin{tabular}{lcccccccc}
\toprule
& & \multicolumn{4}{c}{R10, $c = 1$, $N = 16$} & \multicolumn{3}{c}{$\xi_j - \xi_O$} \\
\cmidrule(lr){3-6}\cmidrule(lr){7-9}
Ensemble & iterations & rms $s$ & RMSE & $\xi$ & cov$_{90}$ & $c = 0$ & $c = 1$ & $c = 2$ \\
\midrule
Oracle & 500 & 0.48 & 1.13 & 0.189 & 0.48 & -- & -- & -- \\
B3c-R & 500 & 0.61 & 1.20 & 0.262 & 0.55 & 0.018 & 0.027 & 0.026 \\
\mPM{} & 250 & 0.58 & 1.15 & 0.265 & 0.58 & 0.032 & 0.051 & 0.058 \\
\mRML{} & 250 & 0.60 & 1.16 & 0.275 & 0.58 & 0.031 & 0.046 & 0.054 \\
B3d & 250 & 0.76 & 1.24 & 0.379 & 0.65 & 0.041 & 0.072 & 0.064 \\
B3c & 250 & 0.74 & 1.23 & 0.372 & 0.64 & 0.058 & 0.072 & 0.064 \\
B5 & 125 & 1.10 & 1.36 & 0.662 & 0.79 & 0.199 & 0.199 & 0.179 \\
\bottomrule
\end{tabular}
\end{table}
\subsection{Mechanism of the bank gain (exploratory)}
\label{sec:exp:mech}
\todoblock{T2, exploratory, on the Experiment~2 bank (realizations 8--15), declared in \texttt{docs/research/t2-mechanism.md} before it is run (scheduled 1/11/2026). Planned tests: (i) warp error of the responsibility-weighted bank against that of the mean warp, at the end of training (re-registration, Remark~\ref{rem:lambda}); (ii) a control bank of random Gaussian-process time shifts with the same spread (label augmentation); (iii) split of the wide cells by posterior multimodality (Corollary~\ref{cor:twomode}); (iv) the Berkson-versus-classical covariance test of Section~\ref{sec:theory:post} for the bulk offset of \mPM{} and B3c-R, which decides which bound of Table~\ref{tab:h2b} applies; (v) \mPM{} retrained at the Oracle's budget, to separate training length from label error. The question is whether any gain remains beyond the population correction of the Berkson structure, not why a gain exceeds the registered bound. Disclose that the post hoc ratios and both bounds of Section~\ref{sec:exp:p2r}, at $\sigpost$ and at the warp error and with the 60\,Hz and cross-spectral variants, were inspected on 29/10/2026, before the declaration.}
\subsection{Detectability of a gain at blind wells (exploratory)}
\label{sec:exp:detect}
A field test scores predictions at blind wells against labels that need a tie of their own. By Proposition~\ref{prop:reference}, an error in that reference biases the comparison, and more wells reduce its variance but not its bias. To estimate how many blind wells a field test needs, we rescored the saved test predictions of Experiment~2 against perturbed references. The analysis was declared before it was run, but after both field gates had failed (Section~\ref{sec:exp:scope}). After the first run we added points to the grid of reference errors, from $\{0, 2, 4, 8\}$ to $\{0, 0.5, 1, 1.5, 2, 3, 4, 8\}$\,ms, because the outcome changed between 0 and 2\,ms, where the grid had no points. No rule, threshold or input changed. The analysis is exploratory.
\paragraph{Design.}
We used the cells at R10, R0 and Rm5 with $c = 1$ and $N \in \{4, 16\}$, and compared \mRML{} with the best point tie of each cell, the competitor of H2a: B3c-R in four cells, B3c at R10 with $N = 4$ and B3b at Rm5 with $N = 4$. For each test well, the reference is the true label read at $t + s(t)$, with $s = a + bx$, where $x$ runs linearly from $-1$ to 1 across the window, $a \sim \N(0, \sigma_{\mathrm{ref}}^2)$ and $b \sim \N(0, \sigma_{\mathrm{ref}}^2/4)$. The RMS of $s$ is then $1.04\,\sigma_{\mathrm{ref}}$. Each well receives 64 draws. A well counts as a win if the seed-averaged \mRML{} has the lower band RMSE against this reference. Wells of one realization share their training wells, so their outcomes are correlated. The probability that a rule passes with $n$ blind wells is therefore computed from a beta-binomial distribution whose mean is the win rate and whose intra-class correlation is that of the outcome within realizations. We compare two rules: $k$ of $n$ wells with $k = \lceil 0.75n\rceil$, the form of both field gates (three of four on F3, five of six on Volve), and a one-sided sign test at $\alpha = 0.05$. $N^\star$ is the smallest $n \le 40$ at which a rule passes with probability at least 0.8.
\paragraph{A reference error of a few milliseconds reverses the ranking.}
With an exact reference, \mRML{} won at 81--97\% of the test wells, and its median band RMSE was 0.80--0.92 times that of the competitor (Table~\ref{tab:t3}). Both numbers worsened as the reference error grew. At $\sigma_{\mathrm{ref}} = 4$\,ms, the win rate was 0.46--0.64 and the median ratio 0.96--1.01. At 8\,ms, the win rate was 0.22--0.44 and the median ratio exceeded 1 in every cell: against this reference the point tie scored better, although against the true labels it was worse. In the three cells with $N = 16$, the median ratio crossed 1 between 3.6 and 4.3\,ms. Corollary~\ref{cor:tolerance} places the crossing, to leading order and without shrinkage, at $\sigma/\sqrt2$, where $\sigma$ is the tie error of the point label. The RMS warp error of B3c-R on the training wells of these cells was 4.2, 5.8 and 7.3\,ms at R10, R0 and Rm5, so $\sigma/\sqrt2$ is 3.0, 4.1 and 5.1\,ms. The simulated crossings follow the same order and lie within 1\,ms of these values. The agreement can only be approximate: \mRML{} is not the oracle that the corollary assumes, the tie errors are not constant Gaussian shifts, and the reference error here includes a stretch.
\paragraph{Wells needed.}
With an exact reference, the sign test needs five blind wells at R0 (both $N$) and at R10 with $N = 16$, and 18 and 11 wells at Rm5 with $N = 4$ and 16. At R10 with $N = 4$, the outcomes are strongly correlated within realizations (intra-class correlation 0.45), and no $n \le 40$ reaches a pass probability of 0.8. The number of wells rises quickly with the reference error. At 1\,ms, four of the six cells need 11--30 wells; at 2\,ms, only R0 stays within 40 (23 and 37 wells); at 3\,ms or more, no cell does. The $k$-of-$n$ rule appears to need fewer wells, but it is not a test. With independent wells and no true difference, it passes with probability $5/16 = 0.31$ at $n = 4$ and $7/64 = 0.11$ at $n = 6$. A one-sided sign test at $\alpha = 0.05$ cannot reject at all with four wells, because its smallest attainable $p$-value is $1/16$.
\begin{table}[t]
\centering
\caption{Detectability at blind wells (exploratory; saved test predictions of Experiment~2, $c = 1$). Competitor: the best point tie of the cell. Win: fraction of the 64 test wells at which \mRML{} has the lower band RMSE against the perturbed reference; ratio: median ratio of band RMSE, \mRML{} to competitor; ICC: intra-class correlation of the win within realizations. $N^\star$: smallest number of blind wells at which a one-sided sign test ($\alpha = 0.05$) rejects with probability at least 0.8; --: not reached with 40 wells.}
\label{tab:t3}
\small
\setlength{\tabcolsep}{4pt}
\begin{tabular}{llccccccccccc}
\toprule
& & \multicolumn{3}{c}{$\sigma_{\mathrm{ref}} = 0$} & \multicolumn{2}{c}{win} & \multicolumn{6}{c}{$N^\star$ at $\sigma_{\mathrm{ref}}$ (ms)} \\
\cmidrule(lr){3-5}\cmidrule(lr){6-7}\cmidrule(lr){8-13}
Cell & Competitor & win & ratio & ICC & 4\,ms & 8\,ms & 0 & 0.5 & 1 & 1.5 & 2 & $\ge 3$ \\
\midrule
R10, $N = 4$ & B3c & 0.81 & 0.85 & 0.45 & 0.53 & 0.39 & -- & -- & -- & -- & -- & -- \\
R10, $N = 16$ & B3c-R & 0.97 & 0.80 & 0.00 & 0.46 & 0.22 & 5 & 5 & 11 & 23 & -- & -- \\
R0, $N = 4$ & B3c-R & 0.95 & 0.87 & 0.07 & 0.64 & 0.39 & 5 & 8 & 11 & 13 & 23 & -- \\
R0, $N = 16$ & B3c-R & 0.97 & 0.87 & 0.00 & 0.48 & 0.27 & 5 & 8 & 13 & 18 & 37 & -- \\
Rm5, $N = 4$ & B3b & 0.84 & 0.92 & 0.39 & 0.60 & 0.44 & 18 & 30 & -- & -- & -- & -- \\
Rm5, $N = 16$ & B3c-R & 0.89 & 0.92 & 0.08 & 0.51 & 0.31 & 11 & 16 & 30 & -- & -- & -- \\
\bottomrule
\end{tabular}
\end{table}
\subsection{Scope: two field cases}
\label{sec:exp:scope}
\paragraph{Both field gates failed.}
We ran two field tests under locked protocols. On F3, with four wells, gate G-C required \mRML{} to have a lower band RMSE than the selected point tie at no fewer than three of the four blind wells, and macro coverage of its 80\% and 90\% intervals within $[0.75, 0.85]$ and $[0.85, 0.95]$. On Volve, with six deviated wells and a density-driven porosity label, gate G-D asked for the same at five of six wells under two hold-out schemes, with total RMSE on the labelled samples. Both gates failed. On F3, \mRML{} improved at one well of four, and coverage was 0.52 and 0.61. Its sensitivity variants (anchor uncertainty, scoring reference, band split, label) improved at one to three wells and never met the coverage condition. On Volve, \mRML{} improved at two (leave-one-well-out) and three (slot) of six wells, and coverage of the 90\% interval was 0.48 and 0.47. No method had skill at the Volve blind wells: $R^2$ was negative for every method, and a constant at the training-well mean of PHIF had a lower macro RMSE than every network (6.03 and 6.59\,p.u.\ under the two schemes, against 6.50 and 7.13\,p.u.\ for \mRML; post hoc). Appendix~\ref{app:field} gives the designs, all tables and the protocol deviations. Neither test is an independent replication. F3 also supplied the statistics and the warp prior of the synthetic generator (Section~\ref{sec:data:d2}), and the Volve test was designed after the F3 gate had failed.
\paragraph{Neither test could have detected the effect.}
After both gates had failed, we stated four conditions under which a field test of this kind bears on the synthetic result, and evaluated them without test labels. The thresholds of C1 and C2 were taken mechanically from Experiment~2, so the conditions are post hoc but were not tuned to the field results. (C1) The networks have blind-well skill within the range in which Experiment~2 found the effect: at inner-validation wells, a band PCC of at least 0.468 and an $R^2$ of at least 0.053, the smallest values reached by the best point tie in the cells that passed H2a, and a lower RMSE than a constant. (C2) The tie posterior is wide, $\sigpost \ge 1.5$\,ms, the threshold of H2b; this condition matters only for the comparison with \mPM. (C3) $\sigma_a$ is identified by independent time--depth data at three or more wells outside the test set, because a misset $\sigma_a$ removed the H2a advantage (Table~\ref{tab:sigmaa}). (C4) The number of blind wells reaches $N^\star$ (Table~\ref{tab:t3}). C2 held on both datasets, with median $\sigpost$ of 2.8\,ms on F3 and 4.3\,ms on Volve. C1 failed on both: band PCC at the inner-validation wells was 0.15 on F3 and 0.13 and 0.04 on Volve (leave-one-well-out and slot), and $R^2$ was 0.04, $-0.99$ and $-0.99$. C3 and C4 fail by construction. F3 has no independent time--depth data, and Volve has check shots at two wells. Both tests scored against marker-calibrated sonic ties of the test wells, whose errors are unknown. With four wells no sign test can reject, and with independent wells the gate rules pass with probability 0.31 (three of four) and 0.11 (five of six) when there is no true difference. The failure of either gate is therefore no evidence against the synthetic result, and a pass would not have been evidence for it.
\paragraph{Limits of field validation.}
A dataset with more wells does not by itself remove the constraint. After the field tests we inventoried Teapot Dome (NPR-3, Wyoming; \citealp{bader2017teapot}), where 152 wells inside the 3-D survey have density logs across a common target interval. This step is post hoc and exploratory. Its conditions were declared before the data were obtained, and the alternative reference described next was declared after the inventory but before any residual or porosity value was computed. Time--depth tables exist at four wells. Three are labelled as derived from synthetic seismograms, and the fourth, a vertical seismic profile, ends above the main reservoirs. Even counting one of the three as independent, at most two wells have an independent time--depth reference, against the $3 + 11$ that C3 and C4 need at Rm5. As an alternative reference, we paired the times of two interpreted 3-D horizons at the wells with the depths of the corresponding formation tops. On 37 development wells we predicted each time from the depth with a quadratic lateral trend of average velocity, fitted by leave-one-out. The residual standard deviation was 6.75\,ms (90\% bootstrap interval over wells 4.1--9.4\,ms; robust estimate 5.0\,ms). Most of it was a bulk shift per well (6.6\,ms): the residuals of the two horizons at a well were correlated (0.85), and those of neighbouring wells were not. The shift is therefore not a smooth velocity change that the trend missed; it resembles per-well errors of datum, statics or top picks. The differential part was 2.8\,ms, and 2.5\,ms from the sonic at five wells. Every estimate exceeded the declared tolerance of 1.5\,ms, the largest grid value at which the Rm5 cell with $N = 16$ reaches a power of 0.8 with no more than the 115 remaining wells. We therefore stopped before reading any porosity value. One dataset is not a survey, but in this one the binding constraint on field validation was the error of the scoring reference, not the number of wells.

View File

@@ -0,0 +1,33 @@
\section{Discussion}
\label{sec:discussion}
\paragraph{What the synthetic experiments show.}
The two experiments separate two questions that are easy to conflate. The first is whether the tie posterior is informative. The second is whether training on it helps. In Experiment~1 the posterior was not informative: 64 anchor-conditioned samples reweighted by tie likelihoods stayed as wide as the anchors allowed, and labels drawn from them were no better than a good correlation-based point tie. Once the posterior contracted (SMC, Experiment~2), labels at its mean beat every point tie in all three full-anchor regimes, and a bank of its samples gained further when the posterior was wide. Better registration of the training labels came first. Marginalizing over what remained then added a smaller, width-dependent gain. Neither result says that marginalization rescues a poor posterior, and Experiment~1 is direct evidence that it does not.
\paragraph{Where the bank gain comes from.}
The theory gives a population limit, and whether the measured gains exceed it depends on the structure of the tie error. In population, a calibrated bank has the minimizer of training on the true labels (Proposition~\ref{prop:bank}), and no method improves on a point label by more than the factor $\rho^\star$ of \eqref{eq:rhostar}. Its distortion term is of fourth order in the tie error. For the Oracle predictions of Experiment~2 it sits near 70\,Hz, where a Berkson error distorts much more than a classical error of the same width (Section~\ref{sec:theory:post}). Under the registered bound for classical error, \mRML{} gained more than the limit allows in 7 of the 8 wide cells at $N = 16$. Under the bound for Berkson error, the natural idealization for labels at the posterior-mean warp, it did so in 3 cells at the posterior width and in at most 1 at the measured warp error of \mPM{} (Section~\ref{sec:exp:p2r}). In most cells the bank gain is therefore no larger than removing a population sharpening of \mPM{} could give, but this rests on an error structure that was not tested. On synthetic data the covariance test of Section~\ref{sec:theory:post} can settle it (Section~\ref{sec:exp:mech}). Finite-sample effects can add to this population effect or outweigh it: the label error itself is of first order, and its effect on the conditional variance that a network must absorb is of second order, against the fourth-order population distortion (Section~\ref{sec:theory:post}). Part of the gap to the Oracle is not caused by registration at all. At $c = 0$, with SMC warp errors of 0.2--0.7\,ms, the Oracle was still 1--3\% better than \mPM{}, and it was trained twice as long. \mRML{} closed 27--46\% of the gap between \mPM{} and the Oracle at $c = 1$, and it did not reach the Oracle in any wide cell at $N = 16$. Beyond the population correction, three mechanisms could contribute to the bank gain. The bank acts as label augmentation, and the learned variance absorbs its spread. For $\lambda > 0$ the responsibilities re-register the labels during training (Remark~\ref{rem:lambda}). A multimodal posterior gives the mean warp a non-Gaussian error, against which a bank can gain more than the Gaussian bound allows (Corollary~\ref{cor:twomode}). Until the exploratory analysis of Section~\ref{sec:exp:mech} is done, the bank gain is an empirical regularity of this benchmark whose source is not identified.
\paragraph{When to use a bank rather than the posterior mean.}
Within this benchmark the answer depends on the posterior width. When the posterior is narrow ($\sigpost < 1.5$\,ms), \mRML{} and \mPM{} are equivalent within 1\% on average, so the bank costs little and brings nothing. When the posterior is wide, because of low SNR, sparse anchors or strong drift, \mRML{} passed in all eight wide cells at $N = 16$, and over all cells at $N = 16$ the gain grew with the width (Spearman $\rho = -0.85$). The bank is cheap: 64 labels per window add little to the cost of training. A practical rule is therefore to train with the bank whenever the tie posterior is wider than about 1.5\,ms. The largest gain at $c = 1$ came with sparse anchors (R10tb), where the posterior was overconfident and the bank was narrower than the error it was meant to represent, so in that regime the bank helped without being calibrated. On real data the width cannot be checked against a true warp, and it depends on $\sigma_a$.
\paragraph{The anchor uncertainty is the main risk.}
Every positive result of Experiment~2 assumes that $\sigma_a$ is known. Halving or doubling it removed the H2a advantage in every cell and miscalibrated the posterior in both directions (Table~\ref{tab:sigmaa}). On F3 the time--depth markers are horizon-tie picks on the same seismic. A type-II estimate treats them as exact (0.4\,ms), while the spread between markers and horizons suggests 7\,ms. The two values place F3 at opposite ends of the $\sigpost$ axis, at about 0.6\,ms (narrow, like R10) or 2.5--3.4\,ms (wide, close to Rm5), and the arms at 3.5 and 14\,ms did not change the F3 outcome (Appendix~\ref{sec:exp:f3}). The width that decides between \mPM{} and \mRML{} inherits this dependence. An estimate of $\sigma_a$ from independent time--depth data at wells outside the test set is therefore a precondition for using the tie posterior, not a refinement of it.
\paragraph{What a field test of registration needs.}
Proposition~\ref{prop:reference} and the detectability analysis (Section~\ref{sec:exp:detect}) turn the field failures into four requirements. They are derived under the simulator of the benchmark. First, the scoring reference must be independent of the seismic and accurate to about 1\,ms. To leading order, the measured advantage has the sign of the true one only if the reference error is below $1/\sqrt2$ times the tie error that the comparison is meant to detect (Corollary~\ref{cor:tolerance}), and power is lost well before that point. With an exact reference, a sign test reached a power of 0.8 with 5--18 blind wells in five of the six cells. At 1\,ms it needed 11--30 wells in four cells, and at 3\,ms or more no cell reached that power with 40 wells. Check shots or a vertical seismic profile can meet this requirement once their datum and statics are reconciled with the seismic. A reference tied by synthetic--seismic matching on the same seismic cannot, because its error is not independent of the predictions. Second, the number of blind wells should follow from a power analysis at the expected effect, and the pass rule should be a test. A rule of $k$ of $n$ wells is not one: with independent wells and no true difference, three of four passes with probability 0.31 and five of six with probability 0.11, and no one-sided sign test at $\alpha = 0.05$ can reject with four wells. Third, $\sigma_a$ must be estimated outside the test set (previous paragraph). Fourth, the networks must have skill in the seismic band at blind wells before registration can matter there. The two field cases that we tested meet none of the four. Teapot Dome, the one large dataset that we inventoried, has 152 wells but fails the first and the third: at most two of its wells have an independent time--depth reference, and the best reference that we could build from horizons and formation tops had a per-well error of 5--7\,ms (Section~\ref{sec:exp:scope}).
\paragraph{What the field cases show.}
Both field gates failed, but in neither case was the timing of the training labels what limited the error at the blind wells. On F3 the networks followed the low-frequency trend (total PCC about 0.5) but predicted little of the seismic band. The macro difference in band RMSE between \mRML{} and B3c-R, 0.016\,p.u., was an eighth of the variation between seeds (up to 0.13\,p.u.) and smaller than the shift produced by plausible alternative scoring references (up to 0.15\,p.u.). Two contrasts with the synthetic results suggest that the F3 band score was insensitive to the timing of the labels, although we did not test this. Without anchors, band RMSE nearly doubled in the synthetic test of H4 but fell slightly on F3 (1.247 against 1.272\,p.u.). The shift-bank losses B4a and B4b, 38--53\% worse than B3b in Experiment~1, had a lower band RMSE than every point tie on F3. The F3 label is, moreover, a linear function of the sonic at three of the four wells, so label and time axis share a source, which violates (A1). On Volve, whose label is density-driven, the error was dominated by the level of porosity, whose well means span 8.5\,p.u. The tie methods changed the macro RMSE by at most 0.25\,p.u.\ out of 6--7\,p.u., and a constant at the training-well mean beat every network (Appendix~\ref{sec:exp:volve}). Neither case is evidence against the synthetic results, and neither is evidence for them. They bound the scope of the paper: its claims about learning rest on the benchmark, and its claims about the field concern what a test there would need.
\paragraph{Limitations.}
\begin{itemize}
\item \textbf{One simulator.} Every confirmatory result comes from one generator, whose statistics and warp prior were estimated on F3. The registration methods use the warp family and the wavelet of the generator. They differ from it only in the prior hyperparameters, which are fitted to the training anchors or fixed, and in the estimated wavelet phase, so a misspecified warp family or wavelet has not been tested. \todo{S2 of \texttt{protocol\_bench} (three misspecification axes). If S2 is not locked and run before submission, call the study a controlled synthetic study, not a benchmark, throughout.}
\item \textbf{Experiment~2 is a deviation.} It was pre-registered and run on new realizations, but it was designed after Experiment~1 had failed, and re-running was not among the options registered for that failure (Section~\ref{sec:exp:diag}).
\item \textbf{Strong drift.} At $c = 2$ the SMC posterior was multimodal and its mean was unstable between runs. These cells are reported but are not evidence.
\item \textbf{Untested stresses.} The bulk-offset prior $\sigma_b$ was not varied, and the anchor-free losses B4a--B4d were not rerun with the SMC posterior. \todo{S3 (B4 under the SMC posterior) and S8 (controlled cycle-skip regime).}
\item \textbf{Monte Carlo variability.} At low SNR the SMC run-to-run stability criterion failed in one of four development cells at $c = 1$, mainly through the phase estimate. This variability is small relative to $\sigpost$, but it was not removed.
\item \textbf{Uncertainty quantification.} Seed ensembles under-covered for every method ($\xi$ of 0.19--0.66 at R10, $c = 1$, $N = 16$), and more so for better labels and longer training. Because training length and label source are confounded, parts (b) and (c) of Proposition~\ref{prop:coverage} remain untested. On F3 the macro 80\% coverage of every probabilistic method was 0.38--0.52, and on Volve 0.29--0.39. Carrying the tie posterior to predictive uncertainty at a new well needs a different mechanism, for example prediction in depth through the warp posterior. We did not attempt this.
\item \textbf{The tempering $\lambda$.} $\lambda = 1/\tau_c$ is a heuristic fixed in advance. We did not compare it with alternatives and make no claim about it.
\item \textbf{One backbone.} All learned methods share one CNN--GRU; only two F3 ablations used a second, purely convolutional backbone (Table~\ref{tab:f3abl}). Assumption (B) of Proposition~\ref{prop:ident} holds only approximately for it. \todo{S4 (second backbone).}
\item \textbf{Detectability.} Section~\ref{sec:exp:detect} rescored predictions with the skill of Experiment~2 against references whose errors are smooth and independent of the predictions. Its numbers of wells hold for predictors of comparable skill. A reference tied on the same seismic adds a covariance with the predictions that we did not model.
\end{itemize}

View File

@@ -0,0 +1,26 @@
\section{Conclusions}
\label{sec:conclusion}
A well tie is an uncertain estimate, yet learning workflows treat it as exact. Its error is an error in the time index of the label. Under an independence assumption, the error convolves the optimal predictor with its distribution and blurs the seismic band, and without time anchors the absolute timing of a network and its label alignment is not identified. An estimated tie can have the classical error structure, which blurs the learned predictor, or the Berkson structure, which sharpens it. A calibrated bank of posterior labels removes both biases in population, but its population gain over a point label is of fourth order in the tie error.
On a registration-aware synthetic benchmark calibrated to F3, the first pre-registered comparison failed because the anchor-only posterior was not informative. In the second, designed after that failure, labels at the mean of a sequential Monte Carlo tie posterior beat the best point tie by 8--22\% in seismic-band RMSE, provided that the anchor uncertainty was correctly specified. Training on the posterior bank gained further when the posterior was wide. Under the Berkson error structure that is natural for a posterior-mean tie, the gain stayed within the population limit in most cells. That structure was not tested, and the experiments do not separate the population effect from finite-sample effects of the bank.
Whether such gains hold on field data is a question that the public datasets we examined cannot answer. A blind-well comparison of tie methods needs a reference that is independent of the seismic and accurate to about 1\,ms, enough blind wells for a test with adequate power, an anchor uncertainty estimated outside the test set, and networks with skill in the seismic band. The F3 and Volve tests met none of these conditions and failed, and Teapot Dome has independent time--depth references at no more than two of its 152 wells. We claim no improvement on field data and no calibrated uncertainty. The benchmark, the locked protocols and the detectability analysis are the means to test such claims once a dataset that meets these conditions is available.
\paragraph{Data and code availability.}
The F3 Netherlands data are publicly available from dGB Earth Sciences under a CC BY-SA 3.0 licence. The Volve data are available from Equinor under a CC BY-NC-SA 4.0 licence. The Teapot Dome data (RMOTC, U.S.\ Department of Energy) are available from the Texas Data Repository \citep{bader2017teapot}. \todo{Verify the three licences on the providers' pages at submission (Teapot: recorded as CC0 in the project notes).} The code, locked protocols, synthetic generator configurations and the scripts that produce every table and figure are available at \todo{repository URL and archived DOI}.
\paragraph{Computer code availability.}
\todo{Required by Computers \& Geosciences. Fields in the journal's template (unverified against the current guide): name of the code; developers and contact (e-mail, phone); year first available; hardware requirements (development on an NVIDIA RTX 3060 12\,GB and an H200); software required (Python 3.12, PyTorch; give the versions of the environment locks); program language; program size; licence; repository link.}
\paragraph{CRediT authorship contribution statement.}
\todo{Author contributions.}
\paragraph{Declaration of competing interest.}
\todo{Competing interests.}
\paragraph{Declaration of generative AI and AI-assisted technologies.}
\todo{Elsevier requires authors to disclose the use of generative AI in preparing the manuscript. The authors must write this statement.}
\paragraph{Acknowledgements.}
\todo{Acknowledgements and funding.}

View File

@@ -0,0 +1,92 @@
\section{Proofs}
\label{app:proofs}
\subsection{Proposition~\ref{prop:blur}}
By (A1), $\E[y(t+\delta(t))\mid X, \delta(t) = d] = \E[y(t+d)\mid X] = m(t+d)$. Taking the expectation over $\delta(t) \sim p_t$, which is independent of $X$, and exchanging the order of integration (Fubini, using (A2)) gives $\hat y^\star(t) = \int p_t(d)\, m(t+d)\dd d$. If $p_t \equiv p$, the Fourier transform of $m(\cdot + d)$ is $e^{i2\pi f d}\hat m(f)$, so $\hat y^\star$ has transform $P(f)\hat m(f)$ with $P(f) = \E e^{i2\pi f\delta}$. For $\delta \sim \N(\mu_\delta, \sigma^2)$, $P$ is the Gaussian characteristic function evaluated at $2\pi f$. \hfill$\square$
If the marginal distribution changes slowly with $t$ (for example, drift that grows with depth), $\hat y^\star$ is a time-varying filter that is locally $P$ with $\sigma(t)$.
\subsection{Corollary~\ref{cor:band}}
Let $e = y - m$. Since $\E[e(t)\mid X] = 0$ and $m(t')$ is a function of $X$, $\Cov(e(t), m(t')) = 0$ for all $t, t'$. Hence $S_{ym} = S_m$ and $S_y = S_m + S_e$. The band operator $B$ commutes with the filter $P$. Because $\delta$ is real, $P(-f) = P(f)^*$. Therefore
\begin{equation*}
\Var \hat y_b = \int_{|f|\ge f_c} |P|^2 S_m \dd f, \qquad \Cov(\hat y_b, y_b) = \int_{|f|\ge f_c} \operatorname{Re}P\, S_m \dd f .
\end{equation*}
With $\langle\cdot\rangle$ the average weighted by $S_{m_b}$,
\begin{equation*}
\frac{\sd\hat y_b}{\sd y_b} = \sqrt{\langle|P|^2\rangle}\,\frac{\sd m_b}{\sd y_b} \le \sqrt{\langle|P|^2\rangle} \le \sup_{|f|\ge f_c}|P(f)|,
\qquad
\PCC_b(\hat y^\star) = \frac{\langle\operatorname{Re}P\rangle}{\sqrt{\langle|P|^2\rangle}}\,\frac{\sd m_b}{\sd y_b},
\end{equation*}
and $\PCC_b(m) = \sd m_b/\sd y_b \le 1$ because $\Cov(m_b, y_b) = \Var m_b$. By Cauchy--Schwarz, $\kappa(P) \le \langle|P|\rangle/\sqrt{\langle|P|^2\rangle} \le 1$, with equality if and only if $P$ is a positive constant on the support of $S_{m_b}$. At each frequency with $P(f) \ne 0$ the coherence is $|S_{\hat y y}|^2/(S_{\hat y}S_y) = S_m/S_y$, which does not depend on $P$. If $\mu_\delta \ne 0$, $\operatorname{Re}P = e^{-2\pi^2\sigma^2 f^2}\cos(2\pi f\mu_\delta)$, which lowers $\kappa$ further. \hfill$\square$
\subsection{Corollary~\ref{cor:var}}
Moments are averaged over $t$ in the window, and $h$ ranges over functions of $X$ with finite variance. Since $\hat y^\star = \E[\tilde y\mid X]$, $\E\|h - \tilde y\|^2 = \E\|h - \hat y^\star\|^2 + \E\|\hat y^\star - \tilde y\|^2$. Fix $\E h$ and $\Var h = v$. Then $\E\|h - \hat y^\star\|^2 = (\E h - \E\hat y^\star)^2 + v + \Var\hat y^\star - 2\Cov(h, \hat y^\star)$, which is smallest when the covariance is largest. By Cauchy--Schwarz, $\Cov(h, \hat y^\star) \le \sqrt{v\Var\hat y^\star}$, with equality if and only if $h - \E h = a(\hat y^\star - \E\hat y^\star)$ with $a = \sqrt{v/\Var\hat y^\star}$. Optimizing over $(\E h, v)$ then only selects $a$ and a constant. \hfill$\square$
For $a > 0$, $h^\star$ has the same PCC and band PCC as $\hat y^\star$, and its in-band spectrum is $a^2|P|^2 S_m$. The statement holds at the population level for a sufficiently rich model class.
\subsection{Proposition~\ref{prop:ident}}
Since $t_{u + \beta e_b}(z) = t_u(z) + \beta$, we have $z_{u+\beta e_b}(t) = z_u(t - \beta)$ and hence $y^{u + \beta e_b} = T_\beta y^u$. By (B), $\mu_{\theta'} = T_\beta\mu_\theta$ and $\sigma_{\theta'} = T_\beta\sigma_\theta$. The Gaussian log-likelihood on a window $I$ is $\sum_{i\in I}\log\N(y(t_i - \beta); \mu(t_i-\beta), \sigma^2(t_i-\beta))$, which is the log-likelihood on the window $I - \beta$. Summed over windows that tile the trace, the two objectives differ only at edge samples. The log-sum-exp of RML preserves this invariance, because every bank member is shifted by the same amount. The prior on $g$ is unchanged, because $g$ is unchanged. This proves (a). Parts (b) and (c) follow by direct computation from $t_{u+\beta e_b}(z_{wk}) = t_{u_w}(z_{wk}) + \beta$. The prior adds $-\sum_w (b_w + \beta)^2/(2\sigma_b^2)$, with curvature $N/\sigma_b^2$. The anchors add $-\sum_{w,k}(t_{wk} - t_{u_w}(z_{wk}) - \beta)^2/(2\sigma_a^2)$, with curvature $\sum_w K_w/\sigma_a^2$. The expression for $\sd(\beta)$ is the inverse square root of the total curvature, that is, a quadratic approximation along the ridge. \hfill$\square$
\subsection{Proposition~\ref{prop:tie}}
(a) Conditional on $X$ and $\delta(t) = d$, independence gives $\E[y(t+d)\mid X, \delta(t) = d] = m(t+d)$ and $\E[y(t+d)^2\mid X, \delta(t) = d] = \E[y(t+d)^2\mid X]$. Integrating over $p_t(\cdot\mid X)$ (Fubini, using (A2)) gives $\tilde m(t)$ and $\E[\tilde y(t)^2\mid X] = \int p_t(d\mid X)\{\Var(y(t+d)\mid X) + m(t+d)^2\}\dd d$. Subtracting $\tilde m(t)^2$ gives the variance.
(b) $\tilde y$ is a function of $D$ because $\hat u$ is. Since $\varepsilon(t)$ is independent of $D$ given $X$, $\E[y(t)\mid D] = \E[\tilde y(t + \varepsilon(t))\mid D] = \int q_t(e\mid X)\,\tilde y(t+e)\dd e$, and in the same way $\E[y(t)^2\mid D] = \int q_t(e\mid X)\,\tilde y(t+e)^2\dd e$. Because $X$ is a function of $D$, the tower property gives $m(t) = \E\big[\E[y(t)\mid D]\mid X\big] = \int q_t(e\mid X)\,\tilde m(t+e)\dd e$, and the same for the second moment. Subtracting $m(t)^2$ gives the variance.
If $p_t = p(\cdot\mid X)$ does not depend on $t$, the window average of $\int p(d\mid X)\Var(y(t+d)\mid X)\dd d$ is $\int p(d\mid X)\,|W|^{-1}\!\int_{W+d}\Var(y(s)\mid X)\dd s\dd d$, which equals the window average of $\Var(y\mid X)$ up to contributions from the edges of the window $W$. Since $\Var_p[m(t+d)] \ge 0$, the window average of $\Var(\tilde y\mid X)$ is at least that of $\Var(y\mid X)$. Case (b) is the same with $y$ and $\tilde y$ exchanged. The Fourier statements follow as in Proposition~\ref{prop:blur}. For zero-mean Gaussian $\varepsilon$, $Q = e^{-2\pi^2\sigma^2 f^2} > 0$, so the transform of $\tilde m$ is $\hat m/Q$. \hfill$\square$
\subsection{Proposition~\ref{prop:bank}}
(a) Take $G(u, D) = y^u(t)$, which depends on $D$ through the logs. Calibration gives $\bar y(t) = \E[y^{u^\star}(t)\mid D] = \E[y(t)\mid D]$, and the tower property gives $\E[\bar y(t)\mid X] = m(t)$.
(b) Take $G(u, D) = \ell\big(y^u; \mu_\theta(X), \sigma_\theta(X)\big)$, a function of $(u, D)$ because $X$ is a function of $D$. Calibration gives $\sum_s \pi_s\ell_s = \E[\ell^\star\mid D]$, and taking expectations gives the claim. By Lemma~\ref{lem:sandwich}, $\RML_\lambda \to -\frac1n\sum_s\pi_s\ell_s$ as $\lambda \to 0$, so for every $\theta$ the limit has the expectation of the Gaussian negative log-likelihood on the true labels. Over functions of $X$, the latter is minimized sample by sample at $\mu_i = \E[y(t_i)\mid X]$ and $\sigma_i^2 = \Var(y(t_i)\mid X)$. For the MSE, $\E[\bar y - m\mid X] = 0$ by (a), so $\E(h - \bar y)^2 = \E(h - m)^2 + \E(m - \bar y)^2$ for every function $h$ of $X$.
The expansion of $\bar y - y^{\bar u}$ in Section~\ref{sec:theory:post} is Taylor's theorem in $u$; the first-order term vanishes because $\sum_s \pi_s (u_s - \bar u) = 0$. \hfill$\square$
\subsection{Corollary~\ref{cor:twomode}}
The characteristic function of $\pm\Delta/2$ with equal probabilities is $\frac12\big(e^{i\pi f\Delta} + e^{-i\pi f\Delta}\big) = \cos(\pi f\Delta)$, which is negative for $\pi/2 < \pi|f|\Delta < 3\pi/2$. Under (a) the transfer from $m$ to $\tilde m$ is $P$; under (b) it is $1/Q$, which has the sign of $Q$. A zero-mean Gaussian with variance $\Delta^2/4$ has characteristic function $e^{-2\pi^2(\Delta^2/4)f^2}$. The calibrated bank is covered by Proposition~\ref{prop:bank}(a). For the shifted bank, $\bar y(t) = \frac12\big[\tilde y(t + \Delta/2) + \tilde y(t - \Delta/2)\big]$, so $\E[\bar y\mid X]$ is $\tilde m$ filtered by $\cos(\pi f\Delta)$, that is, $m$ filtered by $\cos^2(\pi f\Delta)$. \hfill$\square$
\subsection{Remark~\ref{rem:lambda} and Equation~\texorpdfstring{\eqref{eq:rhostar}}{(\ref{eq:rhostar})}}
For a finite bank, $\log\E_\pi e^{\lambda\ell} = \lambda\E_\pi\ell + \frac{\lambda^2}{2}\Var_\pi\ell + O(\lambda^3)$; dividing by $-\lambda n$ gives the expansion in Remark~\ref{rem:lambda}.
$B$ is linear, so $B(h - y) = B(h - m) + B(m - y)$. Here $B(h - m)$ is a function of $X$ and $\E[B(m - y)\mid X] = B\,\E[m - y\mid X] = 0$, so the cross term vanishes. Setting $h = \tilde m$ gives \eqref{eq:rhostar}. The transform of $\tilde m - m$ is $(P - 1)\hat m$ under (a) and $(1/Q - 1)\hat m$ under (b). For Gaussian errors let $x = 2\pi^2\sigma^2 f^2$. Then $(1 - e^{-x})^2 = x^2 + O(x^3)$, $(e^{x} - 1)^2 = x^2 + O(x^3)$, and their ratio is $e^{2x}$. At $\sigma = 2.5$\,ms and $f = 25$\,Hz, $e^{2x} = 1.167$. \hfill$\square$
\subsection{Proposition~\ref{prop:coverage}}
(a) $\xi_j - \xi_O = (v_j w_O - v_O w_j)/(w_j w_O)$, and $v_j w_O - v_O w_j = \Delta v\, w_O - v_O\, \Delta w$. Dividing by $w_j w_O$ gives the identity.
(b) Let $V = \E\Var(y\mid X)$. For the oracle, $v_O = w_O = V$. By (A1) and stationarity, $\E\tilde y^2 = \E y^2 = V + \E m^2$, so $v_j = \E\tilde y^2 - \E\tilde m^2 = V + \int(1 - P^2)S_m\dd f$. By the orthogonality used for \eqref{eq:rhostar}, without the band operator, $w_j = V + \E(\tilde m - m)^2 = V + \int(1 - P)^2S_m\dd f$. Hence $\Delta v - \Delta w = \int[(1 - P^2) - (1 - P)^2]S_m\dd f = 2\int P(1 - P)S_m\dd f$, and (a) with $\xi_O = 1$ gives the result.
(c) By orthogonality, $w_j = V + \E(\tilde m - m)^2 \ge V$. By Proposition~\ref{prop:tie}(b), $\Var(y(t)\mid X) \ge \int q(e\mid X)\Var(\tilde y(t+e)\mid X)\dd e$. Averaging over the window and taking expectations as in the proof of Proposition~\ref{prop:tie}, $V \ge \E\Var(\tilde y\mid X) = v_j$, so $\xi_j \le 1$. A calibrated bank has the population optimum of the oracle (Proposition~\ref{prop:bank}), so $\xi = 1$.
For the coverage statement, $\Pr(|y - \mu| \le zs) = \Pr(|Z| \le z\sqrt\xi) = 2\Phi(z\sqrt\xi) - 1$. \hfill$\square$
\subsection{Proposition~\ref{prop:reference}}
Because $B$ is linear and time-invariant and $\varepsilon_r$ is constant over the window, $By_{\mathrm{ref}}(t) = (By)(t + \varepsilon_r)$. By independence and stationarity, $\E|By_{\mathrm{ref}}|^2 = \E|By|^2$ and
\begin{equation*}
\E\big[B\hat y(t)\; By(t + \varepsilon_r)\big] = \E_{\varepsilon_r}\!\int_{|f|\ge f_c} S_{\hat y y}(f)\, e^{i2\pi f\varepsilon_r}\dd f = \int_{|f|\ge f_c} S_{\hat y y}(f)\, Q_r(f)\dd f .
\end{equation*}
Expanding both squares, the two MSEs differ only in the cross term, $-2\int S_{\hat y y}Q_r\dd f$ against $-2\int S_{\hat y y}\dd f$ over $|f| \ge f_c$. The difference is real, so it equals its real part. \hfill$\square$
\subsection{Corollary~\ref{cor:tolerance}}
The expression for $G_r - G$ is \eqref{eq:refbias} applied to both methods. As in the proof of Corollary~\ref{cor:band}, $S_{my} = S_m$, so $S_{\hat y_A y} = HS_m$ and $S_{\hat y_B y} = HPS_m$. For $\hat y = Lm$ with a real filter $L$, $\E|B(\hat y - y)|^2 = \int_{|f|\ge f_c}(L^2 - 2L)S_m\dd f + \E|By|^2$. The difference between $L = HP$ and $L = H$ is $G$, and adding $G_r - G = -2\int_{|f|\ge f_c} H(1 - P)(1 - Q_r)S_m\dd f$ gives $G_r$. Both factors of the integrand of $G$ are non-negative when $0 \le H, P \le 1$. For Gaussian errors, $P = 1 - 2\pi^2\sigma^2f^2 + O(f^4)$ and $Q_r = 1 - 2\pi^2\sigma_r^2f^2 + O(f^4)$. The over-sharp case follows by substituting $S_{\hat y_B y} = HKS_m$. \hfill$\square$
\subsection{Lemmas~\ref{lem:s1}--\ref{lem:sdtw}}
\paragraph{Lemma~\ref{lem:s1}.} If all $\ell_s = \ell$, then $\log\sum_s\pi_s e^{\lambda\ell} = \lambda\ell$. \hfill$\square$
\paragraph{Lemma~\ref{lem:sandwich}.} Let $\Lambda(\lambda) = \log\E_\pi e^{\lambda\ell} = \lambda M(\lambda)$, and let $r_\lambda \propto \pi e^{\lambda\ell}$ be the tilted distribution. Then $\Lambda' = \E_{r_\lambda}\ell$, and $\lambda\Lambda' - \Lambda = \E_{r_\lambda}[\lambda\ell - \Lambda] = \mathrm{KL}(r_\lambda\|\pi)$. Hence $M'(\lambda) = (\lambda\Lambda' - \Lambda)/\lambda^2 = \mathrm{KL}(r_\lambda\|\pi)/\lambda^2 \ge 0$. As $\lambda \to 0$, $\Lambda(\lambda) = \lambda\E_\pi\ell + O(\lambda^2)$. As $\lambda \to \infty$, $\Lambda(\lambda)/\lambda \to \max_s\ell_s$. Monotonicity gives the two inequalities. For uniform $\pi$, $\E_\pi e^{\lambda\ell} \ge e^{\lambda\max\ell}/S$, which gives the gap bound. The bound is attained in the limit where every $\ell_s$ except the largest tends to $-\infty$. \hfill$\square$
\paragraph{Lemma~\ref{lem:grad}.} Differentiating $-\frac{1}{\lambda n}\log\sum_s\pi_s e^{\lambda\ell_s}$ with respect to $\theta$ gives
\begin{equation*}
-\frac{1}{\lambda n}\sum_s \frac{\pi_s e^{\lambda\ell_s}}{\sum_{s'}\pi_{s'}e^{\lambda\ell_{s'}}}\,\lambda\nabla_\theta\ell_s . \tag*{$\square$}
\end{equation*}
\paragraph{Lemma~\ref{lem:shift}.} With the stated bank and uniform $\pi$, $\RML_\infty = -\frac1n\max_k \ell_k$, where $\ell_k$ is the window log-likelihood of the label shifted by $k$ samples. This is the hard-min over shifts of the Gaussian negative log-likelihood. The finite-$\lambda$ case is the corresponding soft minimum. \hfill$\square$
\paragraph{Lemma~\ref{lem:sdtw}.} By definition,
\begin{equation*}
\mathrm{sDTW}_\gamma(D) = -\gamma\log\sum_{A\in\mathcal P}e^{-\langle A,D\rangle_w/\gamma}.
\end{equation*}
Substituting $\ell_A = -\frac12\langle A,D\rangle_w$, $\pi_A = |\mathcal P|^{-1}$ and $\lambda = 2/\gamma$ into \eqref{eq:rml} gives
\begin{equation*}
\RML_{2/\gamma} = -\frac{\gamma}{2n}\log\sum_{A}|\mathcal P|^{-1}e^{-\langle A,D\rangle_w/\gamma} = \frac{\mathrm{sDTW}_\gamma(D)}{2n} + \frac{\gamma}{2n}\log|\mathcal P| .
\end{equation*}
With symmetric steps, every path has total weight $2n$, and on the diagonal path $\langle A, D\rangle_w = 2\sum_i D_{ii}$, so $\ell_A = \sum_i\log\N(y_i;\mu_i,\sigma_i^2)$. \hfill$\square$

272
paper/sections/B_field.tex Normal file
View File

@@ -0,0 +1,272 @@
\section{Field cases in detail}
\label{app:field}
This appendix reports the two field tests in full. Section~\ref{sec:exp:scope} summarizes them and states what they can and cannot show. Both protocols were locked before their main runs; both gates failed, and nothing was changed after the test wells were scored.
\subsection{F3 field data (gate G-C)}
\label{sec:exp:f3}
\paragraph{Baselines.}
Table~\ref{tab:p1} gives leave-one-well-out results for the baselines on F3. The label is $\mathrm{PHIE}_{\mathrm{DT}}$, and the reference is the marker-calibrated sonic of the test well. The test well contributes nothing to training, tie, hyperparameters or checkpoint selection. A depth--time trend fitted on the training wells (B0a) has the lowest RMSE. No learned model beats it in total RMSE, and its seismic-band PCC is negative. Seismic-attribute ridge regression (B0b) has the highest band PCC (0.24). Among networks, labels from the marker-calibrated tie (B3b) beat single-anchor sonic integration (B3a). With four wells these numbers are descriptive.
\begin{table}[t]
\centering
\caption{F3 leave-one-well-out baselines (label $\mathrm{PHIE}_{\mathrm{DT}}$, marker-calibrated reference, 600--1100\,ms). Macro over four wells; $\pm$: standard deviation over five seeds.}
\label{tab:p1}
\small
\begin{tabular}{lcccc}
\toprule
Method & RMSE (p.u.) & PCC & band PCC & skill vs B0a \\
\midrule
B0a (trend) & \textbf{2.48} & 0.81 & $-0.13$ & 0.00 \\
B0b ridge & 2.58 & \textbf{0.83} & \textbf{0.24} & $-0.09$ \\
B0b random forest & $2.67 \pm 0.01$ & 0.79 & $-0.03$ & $-0.22$ \\
B0b gradient boosting & 2.68 & 0.78 & 0.01 & $-0.20$ \\
B1 (impedance inversion) & 3.60 & 0.44 & $-0.02$ & $-1.29$ \\
B2 (composite loss) & $3.07 \pm 0.16$ & 0.52 & 0.15 & $-0.65$ \\
B3a & $2.93 \pm 0.24$ & 0.62 & $-0.02$ & $-0.47$ \\
B3b & $2.82 \pm 0.21$ & 0.68 & 0.15 & $-0.36$ \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Protocol and deviations.}
The field test was pre-registered in a third protocol. Its SHA-256 lock also covers the code, the input data and the software environment, and the scripts refuse to run if any of them changes. The lock file records that it was written one minute before the main run started (28 October 2026, 00:14 and 00:15 local time). The protocol was committed to version control and tagged only after the run, together with the results. The record that the lock preceded the run is therefore the time stamp inside the lock file, which is self-reported, not the version history. Before the lock we ran a timing pilot of the registration and a preflight of the classical baselines on F3. Neither computed a metric on a test well. No result on an F3 test well was used to design it. Two facts limit what the test can show. First, F3 is not an untouched field dataset. The same four wells gave the baselines of Table~\ref{tab:p1}, computed before the protocol was written, and they calibrated the synthetic benchmark (Section~\ref{sec:data:d2}). The field test is therefore a descriptive follow-up on wells we had already seen, not an independent replication. Second, the method under test comes from Experiment~2, whose protocol was itself designed after Experiment~1 had failed (Section~\ref{sec:exp:diag}). The field result therefore bears on the SMC variant only, and it leaves the verdict of Experiment~1 unchanged.
\paragraph{Design.}
We used nested leave-one-well-out validation. Each well is held out once as the outer test well. Within the three remaining wells, each is held out once as an inner validation well, and models are trained on the other two. Registration uses only the two training wells of each model: the warp-prior hyperparameters, the wavelet phase and the SMC posterior ($\sigma_a = 7$\,ms, $P = 1024$, $S = 64$) are all estimated from them. For each outer fold, method and seed, the iteration budget is chosen from $\{125, 250, 500, 1000, 2000\}$ by total validation MSE averaged over the three inner wells, with ties going to the smaller budget. This replaces the selection on development realizations used in the synthetic experiments (Section~\ref{sec:method:train}). The prediction at the outer well is a Gaussian with the mean and variance of the equally weighted mixture of 15 members (three inner models $\times$ five seeds). Nothing is refitted on the outer well, and its labels enter no choice. The primary label is $\mathrm{PHIE}_{\mathrm{DT}}$, and the reference is the marker-calibrated sonic of the test well, as in Table~\ref{tab:p1}.
Gate G-C required two conditions for \mRML{} in this configuration. (i) \emph{Direction}: lower band RMSE than the point tie chosen for that outer fold among B3b, B3c and B3c-R, by inner-validation MSE averaged over seeds, at no fewer than three of the four outer wells. Any reduction counts, so this rule is weaker than the 0.90 ratio of the synthetic experiments. (ii) \emph{Coverage}: macro coverage of the central 80\% and 90\% intervals within $\pm 0.05$ of nominal, that is, in $[0.75, 0.85]$ and $[0.85, 0.95]$. Coverage is the fraction of time samples in the window that fall inside the interval. These samples are strongly correlated, so coverage is a description, not a test. The protocol also states that better accuracy cannot compensate for failed coverage. Before the run we had recorded that the coverage condition would probably fail, because every ensemble had under-covered in the synthetic experiments. We kept the threshold.
\paragraph{Result: the gate failed.}
Both conditions failed (Table~\ref{tab:f3gc}). Inner validation chose B3c-R as the competitor at all four outer wells. \mRML{} had lower band RMSE only at F03-4, by 1.9\%. At F02-1 and F03-2 it was 0.8\% and 0.02\% worse, and at F06-1 it was 7.0\% worse. Its macro band RMSE was 1.272\,p.u., against 1.256\,p.u.\ for B3c-R. Macro coverage was 0.524 for the 80\% intervals and 0.609 for the 90\% intervals, far below the lower limits of 0.75 and 0.85. At F03-2 and F03-4 the 80\% and 90\% intervals covered 0.75 and 0.80 of the samples, just below and well below nominal. At F02-1 and F06-1 they covered 0.22--0.38 and 0.33--0.50. At these two wells most of the error lay below 6\,Hz: the low-band RMSE was 4.31 and 3.64\,p.u., out of a total RMSE of 4.56 and 3.82\,p.u., while the mean predicted standard deviation was 1.05 and 1.27\,p.u. Seed by seed (three-member ensembles), \mRML{} beat B3c-R at one to three of the four wells. The macro band RMSE of each method varied between seeds by up to 0.13\,p.u.\ (\mRML: 1.28--1.41\,p.u.; B3c-R: 1.29--1.41\,p.u.), eight times the gap between the combined ensembles. The competitor was not changed after the test wells were scored, and the intervals were not widened. Under this protocol, training on the SMC bank gave no band-RMSE gain over the best point tie on F3, and its predictive intervals were much too narrow. We make no claim of improvement on field data and no claim of calibrated uncertainty.
\begin{table}[t]
\centering
\caption{Gate G-C on F3 (label $\mathrm{PHIE}_{\mathrm{DT}}$, marker-calibrated reference, 600--1100\,ms, $\sigma_a = 7$\,ms, 15-member ensemble). Competitor: the point tie chosen by inner validation. Ratio: band RMSE of \mRML{} divided by that of the competitor; at F03-2 it is 1.0002. Coverage: fraction of the 126 time samples inside the central interval of \mRML; at F03-2 and F03-4 the same counts (94 and 101 samples) occur by coincidence.}
\label{tab:f3gc}
\small
\begin{tabular}{lccccc}
\toprule
Outer well & competitor & ratio & improved & cov$_{80}$ & cov$_{90}$ \\
\midrule
F02-1 & B3c-R & 1.008 & no & 0.222 & 0.333 \\
F03-2 & B3c-R & 1.000 & no & 0.746 & 0.802 \\
F03-4 & B3c-R & 0.981 & yes & 0.746 & 0.802 \\
F06-1 & B3c-R & 1.070 & no & 0.381 & 0.500 \\
\midrule
Macro & & & 1/4 & 0.524 & 0.609 \\
Required & & & $\ge 3/4$ & $[0.75, 0.85]$ & $[0.85, 0.95]$ \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Relation to Experiment~2.}
In the synthetic benchmark, \mRML{} beat the best point tie in all three full-anchor regimes, under a stricter rule (Section~\ref{sec:exp:p2r}). On F3 this direction held at one well of four. The field test does not show why, and we tested no explanation. Two features of F3 limit what it can detect. First, the synthetic gains required a correctly specified $\sigma_a$ (Table~\ref{tab:sigmaa}). On F3, $\sigma_a$ is not identified: 7\,ms comes from the marker--horizon spread (Section~\ref{sec:data:f3}), not from an independent measurement. Second, the reference is itself a point tie, the marker-calibrated sonic of B3b. Its registration error adds to the band RMSE of every method, which pulls ratios towards one, and it favours methods whose label errors resemble its own. Neither feature changes the verdict.
\begin{table}[t]
\centering
\caption{F3 nested leave-one-well-out, all methods (label $\mathrm{PHIE}_{\mathrm{DT}}$, marker-calibrated reference, $\sigma_a = 7$\,ms, combined ensembles). Macro over four wells; RMSE in p.u. Coverage is descriptive. Last row: a prediction with no content above $f_c$, whose band RMSE equals the RMS of the band component of the reference; computed after the run, for scale only.}
\label{tab:f3all}
\small
\begin{tabular}{lcccccc}
\toprule
Method & band RMSE & band PCC & RMSE & PCC & cov$_{80}$ & cov$_{90}$ \\
\midrule
B0a (trend) & 1.239 & $-0.13$ & \textbf{2.48} & 0.81 & -- & -- \\
B0b ridge & 1.271 & \textbf{0.24} & 2.58 & \textbf{0.83} & -- & -- \\
B0b random forest & 1.511 & $-0.03$ & 2.67 & 0.79 & -- & -- \\
B0b gradient boosting & 1.537 & 0.01 & 2.68 & 0.78 & -- & -- \\
B1 (impedance inversion) & 3.090 & $-0.02$ & 3.60 & 0.44 & -- & -- \\
B2 (composite loss) & 1.252 & 0.19 & 3.09 & 0.53 & 0.38 & 0.44 \\
\midrule
B3a & 1.348 & $-0.01$ & 3.13 & 0.44 & 0.47 & 0.57 \\
B3b & 1.284 & 0.16 & 3.07 & 0.52 & 0.50 & 0.59 \\
B3c & 1.282 & 0.20 & 3.14 & 0.45 & 0.48 & 0.58 \\
B3c-R & 1.256 & 0.20 & 2.98 & 0.59 & 0.51 & 0.59 \\
B3d & 1.266 & 0.16 & 3.05 & 0.52 & 0.51 & 0.60 \\
\mPM & 1.275 & 0.15 & 3.00 & 0.57 & 0.47 & 0.57 \\
\midrule
B4a & 1.232 & 0.18 & 3.24 & 0.39 & 0.49 & 0.58 \\
B4b & \textbf{1.211} & 0.22 & 3.17 & 0.43 & 0.49 & 0.60 \\
B4c & 1.237 & 0.22 & 3.12 & 0.57 & 0.42 & 0.52 \\
B4d & 1.254 & 0.21 & 3.14 & 0.57 & 0.47 & 0.58 \\
\midrule
M1 & 1.286 & 0.13 & 3.14 & 0.49 & 0.50 & 0.58 \\
\mRML & 1.272 & 0.18 & 3.12 & 0.49 & \textbf{0.52} & \textbf{0.61} \\
\midrule
No band content & 1.224 & -- & -- & -- & -- & -- \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{All methods.}
Table~\ref{tab:f3all} lists every method under the nested design. B0a, B0b and B1 use the code of Table~\ref{tab:p1} and reproduce its values. The networks have higher total RMSE than in Table~\ref{tab:p1} (B3b: 3.07 against 2.82\,p.u.); here each model is trained on two wells rather than three, and its budget is chosen by inner validation. Only B4b had a lower macro band RMSE than a prediction with no seismic-band content (1.211 against 1.224\,p.u.). B0a, which has almost no band content, came within 1.3\% of that value, and every point tie, \mPM{} and \mRML{} lay above it. Band PCC did not exceed 0.22 for any network. On F3 the networks therefore predicted little of the seismic-band variation of the label, and G-C compared methods whose band errors were nearly the same size: without B3a, the 13 networks span 1.211--1.286\,p.u. The ranking also differs from the synthetic experiments. All four anchor-free losses, B4a--B4d, had lower macro band RMSE than every point tie, \mPM{} and \mRML, by up to 0.06\,p.u. Every probabilistic method under-covered. Macro coverage was 0.38--0.52 for the 80\% intervals and 0.44--0.61 for the 90\% intervals, and \mRML{} had the highest values of both.
\paragraph{Same posterior, $\sigma_a$ and scoring reference.}
The protocol prescribes four further comparisons. None can replace a G-C condition, and none was used to choose a result. Table~\ref{tab:f3sens} gives the per-well ratios. In no row did the coverage condition hold.
(a) Against \mPM, which is trained on the mean of the same SMC posterior, \mRML{} had lower band RMSE at two wells (F02-1 and F03-4) and higher band RMSE at F03-2, by 9.3\%. Its macro band RMSE was 0.003\,p.u.\ lower.
(b) With $\sigma_a = 3.5$ or 14\,ms, B3c-R, \mPM{} and \mRML{} were registered and trained again, and \mRML{} was compared with B3c-R at the same $\sigma_a$. It had lower band RMSE at one and two of the four wells, and the wells that improved were not the same in the three arms. Macro coverage was 0.47--0.48 and 0.57--0.59.
(c) When the test well is scored against the OpendTect time--depth model instead of the marker-calibrated sonic, \mRML{} again improved only at F03-4. We also scored each method against 64 warps of the test well, drawn from an anchor-only posterior whose prior was fitted on the other three wells. The 5--95\% range of band RMSE over these references was 0.06--0.15\,p.u.\ wide for \mRML{} and for B3c-R, and the ranges of the two methods overlapped at F02-1, F03-2 and F03-4. At F06-1 they did not overlap (\mRML: 1.13--1.18\,p.u.; B3c-R: 1.04--1.11\,p.u.).
(d) Moving the band cutoff to 5 or 8\,Hz changed no ratio by more than 0.01. With the original PHIE label, \mRML{} improved at three wells, but coverage was lower (0.45 and 0.50). In the window the two labels differ by an RMS of 3.2\,p.u.\ at F02-1 and by less than 0.02\,p.u.\ at the other wells. F02-1 is a training well in three of the four outer folds, and the ratios at those three test wells moved by up to 0.13. This shows how much a ratio near one depends on the label of a single training well. The gate is defined on $\mathrm{PHIE}_{\mathrm{DT}}$, and this row does not change its result.
\begin{table}[t]
\centering
\caption{F3 sensitivity of the G-C comparison (combined ensembles, descriptive). Ratio: band RMSE of \mRML{} divided by that of B3c-R, except in the second row (\mRML{} divided by \mPM). In the $\sigma_a$ rows both methods use the stated $\sigma_a$. Coverage is that of \mRML{} and does not depend on $f_c$ (--). At F03-2 with $f_c = 5$\,Hz the ratio is 1.00002.}
\label{tab:f3sens}
\small
\begin{tabular}{lccccccc}
\toprule
Variant & F02-1 & F03-2 & F03-4 & F06-1 & improved & cov$_{80}$ & cov$_{90}$ \\
\midrule
Registered (Table~\ref{tab:f3gc}) & 1.008 & 1.000 & 0.981 & 1.070 & 1/4 & 0.52 & 0.61 \\
\mRML{} / \mPM & 0.970 & 1.093 & 0.941 & 1.012 & 2/4 & -- & -- \\
$\sigma_a = 3.5$\,ms & 1.010 & 0.939 & 1.003 & 1.034 & 1/4 & 0.48 & 0.59 \\
$\sigma_a = 14$\,ms & 0.989 & 0.959 & 1.020 & 1.035 & 2/4 & 0.47 & 0.57 \\
OpendTect reference & 1.022 & 1.018 & 0.974 & 1.071 & 1/4 & 0.50 & 0.60 \\
$f_c = 5$\,Hz & 1.002 & 1.000 & 0.980 & 1.079 & 1/4 & -- & -- \\
$f_c = 8$\,Hz & 1.014 & 0.997 & 0.979 & 1.060 & 2/4 & -- & -- \\
PHIE label & 0.992 & 0.911 & 1.025 & 0.943 & 3/4 & 0.45 & 0.50 \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Posterior width and anchors.}
At $\sigma_a = 7$\,ms, $\sigpost$ of the SMC posterior ranged from 1.7 to 3.6\,ms over the 12 training wells of the six training pairs (median 2.8\,ms). Seven of the 12 values lay in the range of 2.5--3.4\,ms estimated before the run from all four wells. By the rule of Experiment~2 every pair is therefore wide ($\sigpost \ge 1.5$\,ms), the regime in which RML helped at $N = 16$. Each F3 model, however, is trained on two wells, and \mRML{} beat \mPM{} at two of the four outer wells (Table~\ref{tab:f3sens}). The width followed $\sigma_a$: it was 1.2--2.3\,ms at $\sigma_a = 3.5$\,ms and 1.8--6.2\,ms at 14\,ms. Without anchors it was 17--38\,ms at F02-1, F03-2 and F03-4, and 1.4--2.0\,ms at F06-1. The wavelet phase was poorly identified. The six phases estimated at $\sigma_a = 7$\,ms spread over an arc of 214$^\circ$. Over the phases evaluated for each pair, a window 90--120$^\circ$ wide, the summed log evidence of the two wells changed by only 1.0--5.0\,nats.
Leave-one-anchor-out $z$-scores test the anchor prior on the outer wells. For each well, a linearized Gaussian process conditioned on the anchors alone, with hyperparameters fitted on the other three wells and pick noise $\sigma_a = 7$\,ms, predicts each anchor time from the remaining anchors of that well. Of 62 held-out anchors, 61 lay inside the 90\% interval. The mean $z^2$ was 0.21 (per well: 0.20, 0.01, 0.01 and 0.59), against an expected value of 1. The anchor prior is therefore too wide rather than too narrow, the same direction as the type-II estimate of $\sigma_a$ (0.4\,ms, Section~\ref{sec:method:prior}) and the opposite direction to the under-coverage of porosity. This check does not test the calibration of the SMC posterior, which also depends on the seismic likelihood and the wavelet phase.
\paragraph{Ablations (descriptive).}
The protocol lists twelve variants of \mRML{} on $\mathrm{PHIE}_{\mathrm{DT}}$ (Table~\ref{tab:f3abl}). They were scored like every other method, but none enters G-C. M2-anchor-only trains on the 64 anchor-only warps of M1 with the same weights, so it reproduces M1 exactly. Nine of the other eleven variants had lower macro band RMSE than \mRML. The variants spanned 1.242--1.309\,p.u., about four times the gap of 0.016\,p.u.\ between \mRML{} and B3c-R. Bank size had no consistent effect: with 1, 8, 64 and 256 SMC labels, band RMSE was 1.273, 1.256, 1.272 and 1.257\,p.u. A convolutional backbone without the GRU lowered band RMSE by about 2\% for both \mRML{} (M2-TCN) and \mPM{} (B3d-Sa-TCN), so it did not change their order. Removing the anchors (M2-no-anchors) lowered band RMSE to 1.247\,p.u.\ but gave the highest total RMSE of the variants (3.23\,p.u.). M2-fixed-sigma was the only variant with coverage close to nominal (0.87 and 0.92), and this is not calibration. Its predicted standard deviation is fixed at the standard deviation of the training labels, which gave 2.9--4.3\,p.u.\ after mixing, against 1.0--2.1\,p.u.\ for \mRML. Its 80\% intervals covered every sample at F03-2 and F03-4 and 0.74 and 0.73 of the samples at F02-1 and F06-1. The macro value is an average of these, not evidence of correct width. M2-LFM adds the low-pass mean label of the training wells as an input channel. It had the lowest total RMSE of any network (2.62\,p.u., against 2.48\,p.u.\ for B0a) and the highest band RMSE of the variants (1.309\,p.u.). Its gain lies below $f_c$, where the gate does not score.
\begin{table}[t]
\centering
\caption{Ablations of \mRML{} on F3 (label $\mathrm{PHIE}_{\mathrm{DT}}$, marker-calibrated reference, $\sigma_a = 7$\,ms, combined ensembles; descriptive). Macro over four wells; RMSE in p.u. M2-anchor-only is identical to M1 by construction.}
\label{tab:f3abl}
\small
\begin{tabular}{l>{\raggedright\arraybackslash}p{6.4cm}cccc}
\toprule
Variant & change from \mRML & band RMSE & RMSE & cov$_{80}$ & cov$_{90}$ \\
\midrule
\mRML & registered method: 64 SMC labels, CNN--GRU backbone & 1.272 & 3.12 & 0.52 & 0.61 \\
\midrule
M2-anchor-only & 64 anchor-only warps (= M1) & 1.286 & 3.14 & 0.50 & 0.58 \\
M2-no-anchors & no anchor conditioning; prior hyperparameters at the pre-declared medians & 1.247 & 3.23 & 0.48 & 0.56 \\
M2-bulk & sonic integration plus a constant shift, resampled by the seismic likelihood & 1.251 & 3.16 & 0.49 & 0.58 \\
M2-lambda1 & $\lambda = 1$ instead of $1/\tau_c$ & 1.257 & 3.09 & 0.52 & 0.62 \\
M2-S1 & 1 SMC label & 1.273 & 3.08 & 0.48 & 0.57 \\
M2-S8 & 8 SMC labels & 1.256 & 3.11 & 0.48 & 0.59 \\
M2-S256 & 256 SMC labels & 1.257 & 3.10 & 0.50 & 0.58 \\
M2-fixed-sigma & $\sigma$ fixed at the training-label standard deviation & 1.242 & 3.08 & 0.87 & 0.92 \\
M2-legacy-loss & composite loss of B2 on the bank mean added & 1.243 & 3.11 & 0.41 & 0.49 \\
M2-TCN & four dilated convolutions, no GRU & 1.245 & 3.10 & 0.38 & 0.48 \\
B3d-Sa-TCN & \mPM{} with the M2-TCN backbone & 1.250 & 3.13 & 0.40 & 0.49 \\
M2-LFM & low-pass mean training label as an extra input & 1.309 & 2.62 & 0.40 & 0.50 \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Predicted volume (descriptive).}
A deployment ensemble of \mRML{} predicted all 649 interior inlines of the survey (Fig.~\ref{fig:f3vol}). It has 20 members: four three-well training sets $\times$ five seeds. The map shows sonic-derived porosity and its ensemble standard deviation. Away from the wells there is no ground truth, and three of the four training sets include any given well, so the prediction at a well is not blind. The same kind of ensemble under-covered at the outer wells, so its standard deviation is not a calibrated error bar. Over the $649 \times 949$ interior traces and the 600--1100\,ms window, the median of the predicted mean was 29.6\,p.u.\ (5--95\% of samples: 27.9--31.5\,p.u.). The median standard deviation was 1.3\,p.u.\ (5--95\%: 0.8--2.5\,p.u.). It was larger above 700\,ms (median 2.0\,p.u.) than below (1.2\,p.u.). Even the median standard deviation is less than half the total RMSE of \mRML{} at the outer wells (3.12\,p.u.).
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{f3_volume.pdf}
\caption{Descriptive prediction of sonic-derived porosity ($\mathrm{PHIE}_{\mathrm{DT}}$) on F3 inline 442, through F03-4 (dashed line): (a) mean and (b) standard deviation of the 20-member \mRML{} deployment ensemble. Colour limits: 1st--99th percentile of the section for (a), 0 to the 99th percentile for (b). Three of the four training sets include F03-4, so the prediction at the well is not blind. Intervals from this kind of ensemble under-covered at the outer wells (Table~\ref{tab:f3gc}).}
\label{fig:f3vol}
\end{figure}
\paragraph{Execution.}
The run stopped once, after 132 of 649 volume inlines, when the operating system refused to replace a progress-display file. By then the gate had been computed. Only volume inference was resumed, with the locked code and models. Registration, training and scoring were not rerun, and the 132 inlines written before the stop were verified to be unchanged.
\subsection{Volve field data (gate G-D)}
\label{sec:exp:volve}
\paragraph{Protocol and deviations.}
The Volve test was designed on 28 October 2026, after the F3 gate had failed and before any porosity metric, prediction or training run on Volve. Its protocol follows the F3 protocol, and the lock again covers the code, the input data and the software environment. The lock file records that it was written at 01:17:42 UTC on 29 October 2026, before the primary run started; as on F3, this record is the time stamp inside the lock file. Before the lock, a timing pilot ran the registration on training wells only. Two design choices used Volve data, and neither used a porosity value: the target window, taken from the positions of the labelled samples of the six wells, and the member-support rule (ii) below, taken from a CPU smoke test on training wells. The protocol records eleven deviations from F3, of which four matter for reading the result. (i) The label runs are 16--37 samples long, shorter than the 64-sample training windows and the 6\,Hz band split of F3, so the primary metric is total RMSE on the labelled samples, and the loss uses a single 126-sample window with a mask over the label support of each bank member. (ii) Each bank member trains on its own label support. The first draft intersected the supports of all members, which reduced F-11 A to 7 samples, below the minimum of 8; the intersection is kept as a diagnostic. (iii) Under the slot scheme the inner validation is leave-one-well-out rather than slot-blind, because three slots leave too few groups, so inner validation can be optimistic there. (iv) The anchor uncertainty $\sigma_a = 7$\,ms is inherited from F3, not estimated on Volve. One deviation occurred after the lock. The protocol listed the $\sigma_a$ arms after the primary arm on one GPU; they ran concurrently on a second GPU of the same type. The device is not part of the job fingerprint, every job seeds itself, and the primary-arm gate recomputed with all arms present was identical. Like F3, this is a post-failure design on a dataset we had inspected, not an independent replication.
\paragraph{Design.}
The six wells are held out under two schemes (Section~\ref{sec:data:volve}). Under \emph{lowo}, each well is the outer test well once and the other five train. Under \emph{slot}, the whole slot group of the test well is held out, so F-1 trains on F-11 A, F-11 T2 and F-12 only; for F-12, which is alone in its slot, the two schemes coincide and its rows are identical. Within the outer training wells, each is held out once as an inner validation well. The held-out well never supplies its picks, sonic or logs to its own input. Its path is placed in time by the mean TVDSS--TWT relation of the wells it is held out from, which also moves the 3$\times$3 patch laterally along the deviated trajectory (by up to 76\,m, F-1 A under slot). Registration ($\sigma_a = 7$\,ms, $P = 1024$, $S = 64$) uses the training wells of each model only. Budgets are chosen from $\{125, 250, 500, 1000, 2000\}$ by inner-validation MSE on the labelled samples, and the prediction at the outer well is the moment-matched mixture of the inner models at the selected budget and five seeds (25 members under lowo, 15--25 under slot). The reference is the marker-calibrated vertical sonic of the test well. Gate G-D is descriptive. ``Consistent improvement'' needs \mRML{} below the selected point tie (B3b, B3c or B3c-R, by inner validation) at no fewer than five of six wells under both schemes, the F3 rule of three of four scaled up. ``Calibrated'' needs macro coverage of the 80\% and 90\% intervals within $[0.75, 0.85]$ and $[0.85, 0.95]$ under both schemes. Neither wording can override the F3 result.
\paragraph{Result: neither condition held.}
Table~\ref{tab:volvegd} gives the per-well comparison. Under lowo, inner validation chose B3b at every well, and \mRML{} had lower RMSE at two wells (F-1 B by 1.1\% and F-11 T2 by 1.5\%). At the other four it was 0.4--4.6\% worse. Its macro RMSE was 6.50\,p.u.\ against 6.36\,p.u.\ for B3b. Under slot, inner validation chose B3c in the F-1 slot and B3b in the others, and \mRML{} improved at three wells. The two large ratios in that scheme, 0.85 at F-1 and 0.90 at F-1 B, are against B3c, which had the lowest inner-validation MSE in that fold but was worse than B3b at both test wells (8.04 against 7.27\,p.u.\ and 5.35 against 5.17\,p.u.); against B3b, \mRML{} is 5.8\% better at F-1 and 7.1\% better at F-1 B. Its macro RMSE under slot was 7.13\,p.u.\ against 7.32\,p.u.\ for the selected ties. Against \mPM, trained on the mean of the same posterior, \mRML{} was lower at three of six wells under lowo and four of six under slot, with macro differences of 0.02 and 0.13\,p.u. Macro coverage was 0.39 and 0.48 (lowo) and 0.35 and 0.47 (slot) for the 80\% and 90\% intervals, lower than on F3 and far below the bands. No well reached nominal coverage; the highest values were 0.68 and 0.72 at F-1 B. Nothing was changed after the test wells were scored. We make no claim of improvement and no claim of calibrated uncertainty on Volve.
\begin{table}[t]
\centering
\caption{Gate G-D on Volve (label PHIF, marker-calibrated vertical-sonic reference, labelled samples in 2400--2900\,ms, $\sigma_a = 7$\,ms, combined ensembles). Competitor: the point tie chosen by inner validation. Ratio: RMSE of \mRML{} divided by that of the competitor. $n$: labelled 4\,ms samples. Coverage: fraction of those samples inside the central interval of \mRML. F-12 is alone in its slot, so its two rows are identical.}
\label{tab:volvegd}
\small
\setlength{\tabcolsep}{4pt}
\begin{tabular}{llcccccc}
\toprule
Scheme & Outer well & $n$ & competitor & ratio & improved & cov$_{80}$ & cov$_{90}$ \\
\midrule
lowo & F-1 & 37 & B3b & 1.035 & no & 0.459 & 0.541 \\
& F-1 A & 20 & B3b & 1.004 & no & 0.450 & 0.550 \\
& F-1 B & 25 & B3b & 0.989 & yes & 0.680 & 0.720 \\
& F-11 A & 16 & B3b & 1.046 & no & 0.188 & 0.313 \\
& F-11 T2 & 23 & B3b & 0.985 & yes & 0.261 & 0.435 \\
& F-12 & 29 & B3b & 1.043 & no & 0.276 & 0.310 \\
& Macro & & & & 2/6 & 0.386 & 0.478 \\
\midrule
slot & F-1 & 37 & B3c & 0.852 & yes & 0.270 & 0.432 \\
& F-1 A & 20 & B3c & 1.034 & no & 0.450 & 0.600 \\
& F-1 B & 25 & B3c & 0.897 & yes & 0.600 & 0.720 \\
& F-11 A & 16 & B3b & 1.002 & no & 0.188 & 0.375 \\
& F-11 T2 & 23 & B3b & 0.988 & yes & 0.304 & 0.391 \\
& F-12 & 29 & B3b & 1.043 & no & 0.276 & 0.310 \\
& Macro & & & & 3/6 & 0.348 & 0.472 \\
\midrule
\multicolumn{5}{l}{Required, under both schemes} & $\ge 5/6$ & $[0.75, 0.85]$ & $[0.85, 0.95]$ \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{No method had blind-well skill.}
Table~\ref{tab:volveall} lists the five registered methods. Every macro $R^2$ was negative under both schemes ($-0.84$ to $-1.71$): each method predicted the held-out well worse than that well's own label mean, which it cannot know. The macro PCC was 0.12--0.24. After the run we added one row for scale: a constant prediction at the pooled label mean of the outer training wells, with no seismic input. Its macro RMSE was 6.03\,p.u.\ (lowo) and 6.59\,p.u.\ (slot), below every network. Networks beat it only at F-1 and F-1 B; at the other four wells every network was worse than the constant under both schemes. The reason is the between-well variation of the label. The well means of PHIF span 8.5\,p.u.\ (F-1) to 17.0\,p.u.\ (F-12), while the within-well standard deviation is 3.3--6.0\,p.u. A held-out well therefore differs from the training mean by up to 6.4\,p.u.\ before any seismic information is used, and the networks reproduced this offset rather than correcting it: the mean error of \mRML{} at each well tracked the constant's (lowo: $+3.9$ against $+4.9$\,p.u.\ at F-1, $-5.4$ against $-4.3$ at F-11 A, $-6.8$ against $-6.0$ at F-12). After removing the per-well mean error, the standard deviation of the residual of \mRML{}, averaged over wells, was 5.2\,p.u.\ (lowo) and 5.1\,p.u.\ (slot), against an average within-well label standard deviation of 4.8\,p.u., and the standard deviation of its prediction along a well was 1.1--4.1\,p.u. The predictions varied less than the label and did not follow it. Allowing a free time shift of up to $\pm 64$\,ms between prediction and label (a diagnostic that never alters a score) raised the PCC of \mRML{} to 0.40--0.82. At three (lowo) and four (slot) of the six wells, however, the chosen shift was 56--64\,ms, at or near the search limit and far outside the tie posterior ($\sigpost$ below 10\,ms; see below). With 16--37 samples, the maximum over 33 lags is an optimistic statistic, and we read this diagnostic as uninformative. The differences between tie methods, up to 0.25\,p.u.\ in macro RMSE, are therefore differences between predictions that are all dominated by an error the tie does not control. The G-D comparison had no power on these wells, and its outcome is not evidence about RML in either direction.
\begin{table}[t]
\centering
\caption{Volve nested blind folds, all registered methods (label PHIF, marker-calibrated vertical-sonic reference, $\sigma_a = 7$\,ms, combined ensembles). Macro over six wells; RMSE in p.u. Coverage is descriptive. Last row: a constant prediction at the pooled label mean of the outer training wells, with no seismic input; computed after the run, for scale only.}
\label{tab:volveall}
\small
\begin{tabular}{lcccccccc}
\toprule
& \multicolumn{4}{c}{lowo} & \multicolumn{4}{c}{slot} \\
\cmidrule(lr){2-5}\cmidrule(lr){6-9}
Method & RMSE & $R^2$ & cov$_{80}$ & cov$_{90}$ & RMSE & $R^2$ & cov$_{80}$ & cov$_{90}$ \\
\midrule
B3b & 6.36 & $-0.84$ & 0.38 & 0.46 & 7.29 & $-1.64$ & 0.32 & 0.43 \\
B3c & 6.55 & $-0.97$ & 0.32 & 0.40 & 7.32 & $-1.71$ & 0.33 & 0.40 \\
B3c-R & 6.61 & $-1.02$ & 0.32 & 0.39 & 7.24 & $-1.61$ & 0.29 & 0.35 \\
\mPM & 6.52 & $-0.96$ & 0.39 & 0.45 & 7.26 & $-1.59$ & 0.33 & 0.44 \\
\mRML & 6.50 & $-0.92$ & 0.39 & 0.48 & 7.13 & $-1.48$ & 0.35 & 0.47 \\
\midrule
Constant (training mean) & \textbf{6.03} & $-0.70$ & -- & -- & \textbf{6.59} & $-1.14$ & -- & -- \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Anchor uncertainty.}
B3c-R, \mPM{} and \mRML{} were registered and trained again at $\sigma_a = 3.5$ and 14\,ms (Table~\ref{tab:volvesens}). The macro RMSE of \mRML{} moved by at most 0.06\,p.u.\ (lowo: 6.49, 6.50 and 6.55\,p.u.; slot: 7.13, 7.13 and 7.09\,p.u.), and coverage stayed between 0.35 and 0.52. The number of wells at which \mRML{} beat B3c-R varied between two and four of six, with no pattern across the arms. In Experiment~2 the H2a advantage depended on $\sigma_a$, and on F3 the arms changed the per-well ratios but not the outcome. On Volve they barely changed the macro error, which is consistent with the previous paragraph: when the error is set by the between-well level, the tie has little to act on.
\begin{table}[t]
\centering
\caption{Volve sensitivity to $\sigma_a$ (combined ensembles, descriptive). Macro RMSE in p.u.\ of \mRML{} and of B3c-R at the same $\sigma_a$; improved: wells at which \mRML{} is below B3c-R; coverage of \mRML. The registered comparison of Table~\ref{tab:volvegd} is against the tie chosen by inner validation, which is B3b at most wells, so its counts differ.}
\label{tab:volvesens}
\small
\begin{tabular}{lcccccccc}
\toprule
& \multicolumn{4}{c}{lowo} & \multicolumn{4}{c}{slot} \\
\cmidrule(lr){2-5}\cmidrule(lr){6-9}
$\sigma_a$ (ms) & \mRML & B3c-R & improved & cov$_{90}$ & \mRML & B3c-R & improved & cov$_{90}$ \\
\midrule
3.5 & 6.49 & 6.65 & 4/6 & 0.48 & 7.13 & 7.28 & 3/6 & 0.42 \\
7 & 6.50 & 6.61 & 4/6 & 0.48 & 7.13 & 7.24 & 2/6 & 0.47 \\
14 & 6.55 & 6.52 & 3/6 & 0.52 & 7.09 & 7.27 & 4/6 & 0.46 \\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Posterior width and phase.}
Over the 78 training-well registrations of the primary arm, $\sigpost$ of the SMC posterior was 1.9--9.3\,ms over the main window (median 4.3\,ms) and 3.0\,ms over the labelled samples. It was narrowest at F-11 T2 (1.9--2.6\,ms) and widest at F-12 (4.3--9.3\,ms). Unlike F3, the width barely followed $\sigma_a$: the medians were 3.8, 4.3 and 4.1\,ms at 3.5, 7 and 14\,ms. This is consistent with the seismic likelihood rather than the anchor prior setting the width over the logged interval, but we did not test it. By the rule of Experiment~2 every training set was wide. The wavelet phase was better identified than on F3: the 22 phases of the primary arm lay within an arc of 43$^\circ$, against 214$^\circ$ on F3. A well-identified phase and a width set by the data rather than by $\sigma_a$ suggest that registration was not the limiting step, although on field data this cannot be checked against a true warp. The limiting step was the predictive task itself: with 150 labelled samples in six wells, between-well level differences of up to 8.5\,p.u.\ and a target window 2.4--2.9\,s deep in a deviated-well field, the seismic input did not carry the information needed to predict PHIF at a blind well by any of the methods tested.

View File

@@ -16,10 +16,12 @@ dependencies = [
"lasio>=0.31", "lasio>=0.31",
"PyYAML>=6.0", "PyYAML>=6.0",
"torch>=2.2", "torch>=2.2",
"numba>=0.60",
] ]
[project.optional-dependencies] [project.optional-dependencies]
test = ["pytest>=8"] test = ["pytest>=8"]
f3 = ["scikit-learn>=1.4", "pylops>=2.5", "tabulate>=0.9", "psutil>=5.9"]
[tool.setuptools.packages.find] [tool.setuptools.packages.find]
include = ["ml_porosity*"] include = ["ml_porosity*"]

View File

@@ -1,9 +1,13 @@
# Tài liệu không có toàn văn trong refs/ (cập nhật 26/10/2026) # Tài liệu không có toàn văn trong refs/ (cập nhật 26/10/2026)
P03 (Xu et al. 2024) đã được tải tay ngày 26/10/2026. Các bài open access từng bị chặn tải tự động (P01, P06, P11, P12, P13, Tschannen 2022, AI Review 2024, Wu & Caumon 2017) đã được tải tay và nằm trong thư mục này. Gunning & Glinsky 2006 (C&G 32, 681–695) có toàn văn từ 26/10/2026 (`j.cageo.2005.10.001.pdf`). Còn lại: Quy ước (28/10/2026): mỗi PDF trong `refs/` được đặt tên theo key BibTeX của nó trong `paper/refs.bib`, ví dụ `refs/buland2003bayesianwavelet.pdf`.
P03 (Xu et al. 2024) đã được tải tay ngày 26/10/2026. Các bài open access từng bị chặn tải tự động (P01, P06, P11, P12, P13, Tschannen 2022, AI Review 2024, Wu & Caumon 2017) đã được tải tay và nằm trong thư mục này. Gunning & Glinsky 2006 (C&G 32, 681–695) có toàn văn từ 26/10/2026 (`gunning2006waveletextractor.pdf`). Còn lại:
## Bỏ qua (không tải được, quyết định không theo đuổi) ## Bỏ qua (không tải được, quyết định không theo đuổi)
Ngày 28/10/2026 đã xác nhận lần cuối là không lấy được toàn văn của P04, P05, P07, P09. Bản thảo trích các bài này dựa trên abstract và có chú thích "assessed from the abstract only" (xem `docs/plan.md` mục 2.2). P03 không thuộc nhóm này: toàn văn nằm ở `refs/xu2024sts.pdf`.
| Mã | Bài | DOI | | Mã | Bài | DOI |
| --- | --- | --- | | --- | --- | --- |
| P04 | Chen et al. 2024, IEEE TGRS | 10.1109/TGRS.2024.3460184 | | P04 | Chen et al. 2024, IEEE TGRS | 10.1109/TGRS.2024.3460184 |
@@ -13,6 +17,10 @@ P03 (Xu et al. 2024) đã được tải tay ngày 26/10/2026. Các bài open ac
| — | White & Simm 2003, First Break 21(10) | 10.3997/1365-2397.21.10.25640 | | — | White & Simm 2003, First Break 21(10) | 10.3997/1365-2397.21.10.25640 |
| — | Herrera & van der Baan 2014, Geophysics 79(3) | 10.1190/GEO2013-0248.1 (chỉ có preprint arXiv 2012) | | — | Herrera & van der Baan 2014, Geophysics 79(3) | 10.1190/GEO2013-0248.1 (chỉ có preprint arXiv 2012) |
## Chỉ có abstract: quét SEG/EAGE ngày 28/10/2026
Không có PDF vì EarthDoc và SEG Library chặn tải tự động. Abstract lấy từ OpenAlex; trích trong bài với chú thích "assessed from the abstract only". Key BibTeX: `lim2025awsm`, `lim2025bootnet`, `quesada2024faultlabels` (chưa có DOI), `huff2024anglestack`, `thiebaud2024lfc`, `rizzuti2024waveletflows`, `cordoba2025porosity`, `mirza2025labelquality`, `rizzuti2025uhr`, `guillon2020gtmetrics`. Nếu tải tay được bài nào, đặt tên PDF theo key. Nên ưu tiên `lim2025awsm`.
## Chưa xác định được bài ## Chưa xác định được bài
- Muñoz & Hale (2015) và RING 2025: không tìm thấy, bỏ qua. - Muñoz & Hale (2015) và RING 2025: không tìm thấy, bỏ qua.

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">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">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: 26/10 đến hết thứ 7, 14/11/2026 (Pivot 1 mức B, dời ngày 29/10 từ 31/10) · 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">
@@ -115,12 +115,36 @@ footer{margin-top:32px;color:var(--mute);font-size:12px}
<div class="card gantt" id="gantt"></div> <div class="card gantt" id="gantt"></div>
<h2>Công việc theo pha</h2> <h2>Công việc theo pha</h2>
<div class="card" id="p3-live" style="margin-bottom:14px" aria-live="polite">P3 đã hoàn tất lúc 06:50 ngày 28/10, gồm volume đầy đủ 649 inline. G-C KHÔNG ĐẠT. Chi tiết và tiến độ được nạp tự động từ outputs/p3/progress.js.</div>
<div class="card" style="margin-bottom:14px">
<b>Kết quả P3 F3 ngày 28/10: G-C KHÔNG ĐẠT</b>
<p>Đã hoàn tất LOWO, ablation và diagnostics. M2-Sa chỉ cải thiện tại F03-4; kết quả trên synthetic P2r chưa chuyển thành lợi ích ổn định trên bốn giếng F3 theo protocol này.</p>
<div class="tw"><table><thead><tr><th>Tiêu chí đã khóa</th><th>Kết quả</th><th>Kết luận</th></tr></thead><tbody>
<tr><td>Band RMSE tốt hơn point tie được chọn bằng validation ở ≥ 3/4 giếng</td><td>1/4 giếng; đối thủ B3c-R ở cả bốn vòng ngoài</td><td>Không đạt</td></tr>
<tr><td>Coverage 80% trong 75–85%</td><td>52,38%</td><td>Không đạt</td></tr>
<tr><td>Coverage 90% trong 85–95%</td><td>60,91%</td><td>Không đạt</td></tr>
</tbody></table></div>
<p>Band RMSE macro của M2-Sa là 1,272 p.u., so với B3c-R 1,256 p.u. Khoảng dự đoán chưa bao phủ đủ nhãn tham chiếu; không claim calibration hoặc ưu thế trên field. Giữ nguyên ngưỡng, không chọn lại phương pháp theo test. Volume chỉ có tính mô tả.</p>
<p class="sub">Hoàn tất toàn bộ lúc 06:50 ngày 28/10. Lượt đầu dừng lúc 03:57 vì Windows khóa file dashboard sau 132/649 inline. Đã phục hồi riêng volume; một lần khóa file tái diễn được retry thành công. Giữ nguyên code khoa học, mô hình, G-C và byte của 132 inline cũ. <a href="outputs/p3/volume_recovery.json">Nhật ký phục hồi</a> · <a href="outputs/p3/completion_checks.json">Kiểm tra hoàn tất</a> · <a href="outputs/p3/summary/summary.md">Bảng kết quả</a> · <a href="outputs/p3/summary/wells.png">Hình bốn giếng</a>.</p>
</div>
<div class="card" style="margin-bottom:14px">
<b>Kết quả P4 Volve ngày 29/10: G-D không đạt tiêu chí claim nào</b>
<p>Sáu giếng nghiêng, nhãn PHIF (dẫn xuất từ density, không phụ thuộc sonic), hai scheme blind: <i>lowo</i> (bỏ một giếng) và <i>slot</i> (bỏ cả nhóm giếng chung lỗ khoan). G-D chỉ mô tả; tham chiếu calibrated, σ_a = 7 ms, ensemble gộp.</p>
<div class="tw"><table><thead><tr><th>Tiêu chí đã khóa</th><th>lowo</th><th>slot</th><th>Kết luận</th></tr></thead><tbody>
<tr><td>M2-Sa có RMSE thấp hơn B3 được chọn bằng inner validation ở ≥ 5/6 giếng</td><td>2/6 (đối thủ B3b ở cả 6)</td><td>3/6 (B3c ở nhóm F-1, B3b ở còn lại)</td><td>Không đạt</td></tr>
<tr><td>Coverage 80% trong 75–85%</td><td>38,6%</td><td>34,8%</td><td>Không đạt</td></tr>
<tr><td>Coverage 90% trong 85–95%</td><td>47,8%</td><td>47,2%</td><td>Không đạt</td></tr>
</tbody></table></div>
<p>RMSE macro của M2-Sa là 6,50 p.u. (lowo) và 7,13 p.u. (slot), so với 6,36 và 7,32 của B3 được chọn, 6,52 và 7,26 của B3d-Sa. R² macro âm với mọi phương pháp (−0,84 đến −1,71), PCC 0,12–0,24. Nhánh σ_a = 3,5 và 14 ms làm RMSE macro của M2-Sa đổi tối đa 0,06 p.u.</p>
<p><b>Post hoc (chỉ để so thang, <code>scripts/25_p4_posthoc.py</code>):</b> dự đoán hằng số bằng trung bình PHIF của các giếng train có RMSE macro 6,03 (lowo) và 6,59 p.u. (slot), thấp hơn mọi mạng. Sai số do mức trung bình khác nhau giữa giếng (8,5–17,0 p.u.) chi phối; khác biệt giữa các phương pháp tie (≤ 0,25 p.u.) nhỏ so với sai số tổng 6–7 p.u. Phép so sánh G-D vì vậy không có lực phân biệt; Volve không phải bằng chứng ủng hộ hay chống RML.</p>
<p class="sub">Deviation sau khóa (chỉ lịch chạy): nhánh σ_a chạy song song trên cuda:0 thay vì sau nhánh chính trên cuda:1; G-D của nhánh chính tính lại khi có đủ các nhánh trùng hệt. Không chạy lại, không đổi thiết kế. Chi tiết: <code>docs/plan.md</code> §12 ý 20–21.</p>
</div>
<div id="phases"></div> <div id="phases"></div>
<h2>Các mục cần xác minh [XM]</h2> <h2>Các mục cần xác minh [XM]</h2>
<div class="tw"><table id="xm"><thead><tr><th>Mục</th><th>Vị trí trong plan</th><th>Trạng thái</th><th>Kết quả hoặc việc còn lại</th></tr></thead><tbody></tbody></table></div> <div class="tw"><table id="xm"><thead><tr><th>Mục</th><th>Vị trí trong plan</th><th>Trạng thái</th><th>Kết quả hoặc việc còn lại</th></tr></thead><tbody></tbody></table></div>
<h2>Quyết định (chốt 26/10/2026, bỏ bước chờ GVHD)</h2> <h2>Quyết định (D-1 đến D-4 chốt 26/10/2026; D-5 đến D-12 chốt 29/10/2026)</h2>
<div class="tw"><table id="dec"><thead><tr><th>Mã</th><th>Quyết định</th><th>Chốt</th><th>Căn cứ</th></tr></thead><tbody></tbody></table></div> <div class="tw"><table id="dec"><thead><tr><th>Mã</th><th>Quyết định</th><th>Chốt</th><th>Căn cứ</th></tr></thead><tbody></tbody></table></div>
<h2>Phát hiện đã kiểm chứng (từ dữ liệu)</h2> <h2>Phát hiện đã kiểm chứng (từ dữ liệu)</h2>
@@ -176,7 +200,7 @@ footer{margin-top:32px;color:var(--mute);font-size:12px}
<h2>Chốt P2 (27/10/2026)</h2> <h2>Chốt P2 (27/10/2026)</h2>
<div class="card" style="font-size:13.5px" id="p2close"> <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. <b>P2 đã đóng về thí nghiệm.</b> Lưới chính P2r (realization 8–15) đã hoàn tất; H2a và H2b đạt theo protocol_p2r, nhánh sai σ_a không đạt, H3 chỉ mô tả. Kết luận G-B của P2 ban đầu giữ nguyên. 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>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>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>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.
@@ -201,7 +225,7 @@ footer{margin-top:32px;color:var(--mute);font-size:12px}
<script> <script>
/* ===================== DATA (sửa ở đây) ===================== */ /* ===================== DATA (sửa ở đây) ===================== */
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 START = "2026-10-26", END = "2026-11-14"; // END tính cả ngày; mục tiêu: nộp bài thứ 7 14/11/2026 (dời ngày 29/10 từ 31/10, Pivot 1 mức B)
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 = [
@@ -211,10 +235,10 @@ const PHASES = [
{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-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 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-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 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-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 (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-out", t:"Bổ sung và kiểm tra outputs_thesis/ của luận văn", s:"done", n:"27/10: đã có 7 artifact trong outputs_thesis/, gồm checkpoint/dự đoán v2 và volume 278756708 byte, shape 651 × 951 × 126, mọi giá trị hữu hạn. SHA-256 ở data_manifest/thesis_outputs.json; chi tiết ở docs/research/thesis-output-audit.md. Chưa chạy lại checkpoint do môi trường hiện chưa có Python/PyTorch."},
{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-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:"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-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 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-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 code_thesis/ (code luận văn) giữ nguyên."},
{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-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 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-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:"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:"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."}
@@ -244,36 +268,62 @@ const PHASES = [
{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-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-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-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:"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) đã đăng ký (cận classical; sửa 29/10: với cận Berkson post hoc chỉ 3/8 ô rộng vượt, hai ô sát cận, và tối đa 1/8 tại sai số warp; xem FINDS). H3 chỉ mô tả: mọi ensemble, kể cả Oracle, under-cover."}
]}, ]},
{id:"P3", name:"P3 F3 thật", start:"2026-10-28", end:"2026-10-28", weeks:"T4 28/10", {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 cho F3", out:"bảng và hình cho F3",
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%."}, 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%.", res:"KHÔNG ĐẠT: cải thiện 1/4 giếng; coverage 80/90% là 52,38% / 60,91%."},
tasks:[ tasks:[
{id:"p3-lowo", t:"Nested LOWO đầy đủ, ensemble, calibration", s:"todo"}, {id:"p3-env", t:"Chuẩn bị máy Windows / RTX 3060 và dữ liệu F3", s:"done", n:"27/10: RTX 3060 12 GB, RAM 24 GB; Python 3.12.16 và PyTorch 2.11.0+cu128 trong .venv. Đã dựng f3_wells.npz bằng script 01. Cube và 7 horizon khôi phục từ bản Thesis khớp SHA-256 gốc. Không chạy lại script 04 hoặc 09."},
{id:"p3-abl", t:"Ablation (bỏ từng thành phần), leave-one-anchor-out", s:"todo"}, {id:"p3-review", t:"Pull Gitea và rà code P3 theo agent skills", s:"done", n:"Đã pull main lên a22f9d9 và áp dụng scientific-critical-thinking, scikit-learn, statistical-analysis, scientific-visualization. 129 test đạt, 13 bỏ qua (dữ liệu tùy chọn/khác nền tảng). Đã sửa ranh giới train/test, SMC không anchor, resume/checkpoint, logging Windows, phương sai volume và trạng thái smoke. Chi tiết: <a href=\"docs/research/p3-code-review.md\">review P3</a>. Trạng thái chạy chính xem thẻ trực tiếp phía trên."},
{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:"p3-protocol", t:"Triển khai và khoá protocol_f3 trước khi chạy LOWO", s:"done", n:"Đã khóa lúc 00:14 ngày 28/10 trước smoke và lưới chính. SHA-256 bắt đầu 0c756d2825d9. <a href=\"configs/protocol_f3.lock.json\">Bản khóa</a> lưu code, môi trường và dữ liệu. G-C giữ nguyên: ≥ 3/4 giếng và coverage 80/90% trong ±5%."},
{id:"p3-bench", t:"Đo tốc độ RTX 3060, ước lượng thời gian và lưu tiến độ", s:"done", n:"Benchmark 1/2/3/4/6 tiến trình: 4 nhanh nhất, khoảng 319 bước/s. 1.320 trajectory, tối đa 2.000 bước/trajectory: riêng train khoảng 1,6–3,3 giờ. Registration hai giếng: có anchor 122 s, không anchor 257 s. Toàn bộ dự kiến 2,6–6,4 giờ, không phải khoảng tin cậy. <a href=\"outputs/p3/benchmark.json\">Số đo train</a>, <a href=\"outputs/p3/registration_benchmark.json\">registration</a>. Smoke toàn tuyến đạt nhưng không chấm G-C."},
{id:"p3-lowo", t:"Nested LOWO đầy đủ, ensemble, calibration", s:"done", n:"4 vòng ngoài × 3 vòng trong, 5 seed; chỉ vòng trong chọn checkpoint. G-C không đạt. Kết quả: <a href=\"outputs/p3/summary/summary.md\">tổng hợp</a>, <a href=\"outputs/p3/summary/gate_gc.json\">G-C</a>, <a href=\"outputs/p3/summary/metrics.csv\">theo giếng/seed</a>. Không mở rộng khoảng bất định sau khi xem test."},
{id:"p3-abl", t:"Ablation (bỏ từng thành phần), leave-one-anchor-out", s:"done", n:"Đã chạy 12 ablation, nhánh σ_a và LOAO. LOAO là xấp xỉ GP chỉ có anchor, không phải kiểm định calibration của posterior SMC. <a href=\"outputs/p3/diagnostics/loao.csv\">LOAO</a>; kết quả ablation trong bảng tổng hợp."},
{id:"p3-vol", t:"Dự đoán cả khối kèm bất định", s:"done", n:"Đã xong full volume 649 inline bên trong, ensemble 20 mô hình; shape 651×951×126 gồm viền NaN. <a href=\"outputs/p3/volume/mean.npy\">Mean</a>, <a href=\"outputs/p3/volume/sigma.npy\">sigma</a>, <a href=\"outputs/p3/volume/metadata.json\">metadata</a>, <a href=\"outputs/p3/volume/F03-4_inline.png\">inline F03-4</a>. Không giảm phạm vi. M3 (RML-EM) vẫn hoãn."}
]}, ]},
{id:"P4", name:"P4 Field thứ hai (Volve)", start:"2026-10-28", end:"2026-10-29", weeks:"T4–T5 28–29/10", {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 kết quả field 2", out:"bảng kết quả field 2",
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ả."}, 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ả. Claim \"cải thiện nhất quán\" cần ≥ 5/6 giếng ở cả lowo và slot; \"hiệu chuẩn\" cần coverage 80/90% trong [75, 85]% và [85, 95]% ở cả hai scheme.", res:"KHÔNG ĐẠT tiêu chí claim: cải thiện 2/6 (lowo) và 3/6 (slot) giếng; coverage 80/90% là 38,6/47,8% (lowo) và 34,8/47,2% (slot). Không phương pháp nào có kỹ năng ở giếng blind (R² < 0)."},
tasks:[ tasks:[
{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-roi", t:"Vùng quan tâm (ROI) của Volve, tie, pipeline", s:"done", n:"28/10: lớp dữ liệu giếng nghiêng (survey minimum curvature, TDR thời gian thẳng đứng hiệu chỉnh theo marker, patch 3×3 dọc đường giếng; scripts/23 → outputs/volve/volve_wells.npz) và pipeline ml_porosity/volve/ (fold lồng lowo/slot, bank loss có mask, chống rò nhãn bằng view). 6 giếng, PHIF 16–37 mẫu/giếng (tổng 150), cửa sổ 2400–2900 ms. Protocol <a href=\"configs/protocol_volve.yaml\">protocol_volve</a> khóa 01:17:42 UTC 29/10 (<a href=\"configs/protocol_volve.lock.json\">bản khóa</a>)."},
{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:"p4-run", t:"Chạy tập con B1, B3, B4, B5, M2", s:"done", n:"Xong 02:21 UTC 29/10 trên server Linux (H200): nhánh chính cuda:1 (22 registration + 550 job), nhánh σ_a 3,5/14 ms song song trên cuda:0 (44 + 660 job), không job nào lỗi. Theo scope cut 5: B3b, B3c, B3c-R, B3d-Sa, M2-Sa (bỏ B1, B4, B5). <a href=\"outputs/p4/summary/summary.md\">Tổng hợp</a>, <a href=\"outputs/p4/summary/gate_gd.json\">G-D</a>, <a href=\"outputs/p4/posthoc/macro.csv\">post hoc</a>."},
{id:"p4-x", t:"Exploratory P4x: biến thể mô hình trên Volve (post hoc, không claim)", s:"done", n:"Khai báo trước ở <a href=\"docs/research/p4-exploratory.md\">p4-exploratory.md</a> (02:40 UTC, trước mọi lần train P4x). V0 tái lập P4 khớp tới 1,8e-15; V1a, V1b, V2a, V2b chạy dở. Bỏ hẳn ngày 29/10 (D-10), xem task kế tiếp."},
{id:"p4-p4x", t:"P4x exploratory (biến thể chọn sau khi thấy nhãn test)", s:"done", n:"Bỏ hẳn ngày 29/10/2026 (quyết định D-10): không tổng hợp, không vào bài, không chạy V3. Job exploratory/run_p4x.sh trên cuda:0 ở 560/921 khi chốt; sau đó dừng ở 670/921 (khoảng 04:05 UTC) và kill để trả GPU, nhánh B3d-Sa và V3 chưa chạy; kết quả không dùng. exploratory/ và outputs/p4x/ giữ làm hồ sơ."}
]}, ]},
{id:"P5", name:"P5 Viết bài", start:"2026-10-29", end:"2026-10-30", weeks:"T5–T6 29–30/10", {id:"P5", name:"P5 Viết bài", start:"2026-10-29", end:"2026-10-31", weeks:"T5–T7 29–31/10",
out:"draft v1 (cuối 29/10), v2 (cuối 30/10); gói tái lập", gate:null, out:"mức A của Pivot 1: khung bài mới, các mệnh đề rẻ, T3/T4 trên số liệu đã có (xong 29/10); trích dẫn dataset 30–31/10 (lượt rút gọn độ dài đã bỏ, D-12)", gate:null,
tasks:[ tasks:[
{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-d1", t:"Draft v1 và quyết định Pivot 1", s:"done", n:"29/10: đã viết đủ các mục Volve (dữ liệu, G-D, bảng tab:volvegd/volveall/volvesens, thảo luận, abstract, mở đầu, kết luận); bài build sạch, 42 trang. Trục bài đặt vào lý thuyết (Mệnh đề 1–2) và benchmark synthetic P2r; F3 và Volve là kiểm tra thực tế giới hạn phạm vi claim. Còn: citation dữ liệu, tác giả, rà văn phong. 29/10: chốt Pivot 1 (D-5 đến D-10), dời hạn sang 14/11; khảo sát dataset field public (docs/research/field-dataset-survey.md): chưa có dataset nào xác nhận đủ điều kiện cho field test có power, không thêm field test trong bài này."},
{id:"p5-d2", t:"Draft v2, phụ lục chứng minh", s:"todo", n:"Cuối T6 30/10."}, {id:"p5-a1", t:"Viết lại abstract, mở đầu, đóng góp, thảo luận, kết luận theo trục lý thuyết + benchmark", s:"done", n:"Xong sớm ngày 29/10 (plan §12 ý 24). Tiêu đề theo Pivot 1 (kèm TODO: đổi benchmark thành controlled synthetic study nếu S2 không kịp), abstract 292 từ (sau lượt tự sửa A6), keywords, paper/highlights.txt, đóng góp C1–C4. F3 và Volve thành mục phạm vi 6.6; chi tiết sang Phụ lục B (B.1 F3, B.2 Volve). Bài 55 trang (sau A6), build sạch; còn TODO đỏ cho S1–S8, T2 và các khai báo của tác giả."},
{id:"p5-repro", t:"Gói tái lập (code, config, dữ liệu dẫn xuất)", s:"todo"} {id:"p5-a2", t:"T1, T4, T8 viết thành mệnh đề (hệ quả của Mệnh đề 1 và Bổ đề 2)", s:"done", n:"29/10. T1 thành Mệnh đề 3 (sai số classical làm mờ, Berkson làm sắc; tie trung bình posterior gần Berkson) và Mệnh đề 4 (bank hiệu chỉnh; lợi ích quần thể so với nhãn điểm bậc bốn theo σ). T4 thành Mệnh đề 5 (coverage qua tỉ số ξ). T8 thành Hệ quả 3 (hai mode, đảo dấu trong băng). Thêm Nhận xét 1 (λ > 0), Mệnh đề 6 và Hệ quả 4 (reference lệch; dung sai σ_r < σ/√2). Bản tiếng Việt ở docs/theory.md mục 6; chứng minh ở Phụ lục A."},
{id:"p5-a3", t:"T4: tách σ_aleatoric và Var_seed từ outputs/p2r/train/*/cells/*.npz", s:"done", n:"29/10, post hoc: scripts/30_t4_coverage.py → outputs/t4/ (bài mục 6.3, bảng tab:t4). Mọi ensemble quá hẹp (ξ 0,19 ở Oracle, tối đa 0,66). Độ dài huấn luyện lẫn với nguồn nhãn, nên phần (b), (c) của Mệnh đề 5 chưa kiểm. Không claim hiệu chỉnh."},
{id:"p5-a4", t:"T3: khả năng phát hiện của field test (giải tích + mô phỏng trên dự đoán P2r)", s:"done", n:"29/10, exploratory, khai báo trước ở docs/research/applicability-teapot.md (Deviation 1: mở rộng lưới σ_ref). scripts/27_t3_power.py → outputs/t3/ (bài mục 6.5, bảng tab:t3). Khác phác thảo: reference là nhãn thật đọc tại warp nhiễu loạn cỡ σ_ref, luật đánh giá là sign test một phía. Cần 5–18 giếng blind với reference chính xác; từ 3 ms không ô nào đạt với 40 giếng."},
{id:"p5-a5", t:"T10: related work về label noise / errors-in-variables", s:"done", n:"29/10: đoạn Label noise and errors in variables ở bài mục 2 (Berkson 1950, Fuller 1987, Carroll et al. 2006, Frénay & Verleysen 2014, Song et al. 2023, Mnih & Hinton 2012 đọc toàn văn, Balakrishnan 1962 chỉ có metadata Crossref). Bảng định vị thêm Mnih & Hinton."},
{id:"p5-app", t:"Điều kiện áp dụng C1–C4 và thử Teapot Dome (exploratory)", s:"done", n:"29/10, plan §12 ý 23. Khai báo trước ở docs/research/applicability-teapot.md; kết quả ở docs/research/applicability-results.md. C1/C2 hồi cứu (scripts/26): F3, Volve trượt C1, đạt C2. Teapot: T0 trượt (tối đa 2 giếng TD độc lập), pilot P-a trượt (σ̂_knot 6,75 ms so với 1,5 ms). Dừng Teapot, quay về lịch mức B (D-11). data/Teapot/ (1,7 GB) đã vào .gitignore."},
{id:"p5-cite", t:"Trích dẫn dataset F3 và Volve", s:"todo", n:"30–31/10: thêm vào paper/refs.bib và mục 3 của bài. Lượt rút gọn độ dài cho venue đã bỏ theo quyết định của người dùng ngày 29/10 (D-12)."},
{id:"p5-d2", t:"Draft v2, phụ lục chứng minh", s:"todo", n:"Dời sang 8–10/11 theo lịch mức B."},
{id:"p5-repro", t:"Gói tái lập (code, config, dữ liệu dẫn xuất)", s:"todo", n:"Dời sang 11–12/11."}
]}, ]},
{id:"P6", name:"P6 Review và nộp", start:"2026-10-31", end:"2026-10-31", weeks:"T7 31/10", {id:"P6", name:"P6 Benchmark mức B", start:"2026-11-01", end:"2026-11-10", weeks:"CN 1/11 – T3 10/11",
out:"protocol_bench khoá trước khi chạy; lưới đầy; trục misspec; phân tích cơ chế; gói benchmark", gate:null,
tasks:[
{id:"p6-t2", t:"T2 cơ chế của lợi ích bank (exploratory, realization 8–15)", s:"todo", n:"CN 1/11. Khai báo trước ở docs/research/t2-mechanism.md. Câu hỏi (đổi ngày 29/10): còn lợi ích nào vượt hiệu chỉnh quần thể của cấu trúc Berkson không. Năm phép kiểm theo todoblock bài mục 6.4: (i) warp error có trọng số responsibility so với warp trung bình; (ii) bank nhiễu GP đối chứng; (iii) tách ô posterior đa mode; (iv) kiểm Berkson hay classical bằng hiệp phương sai của offset (quyết định cận nào áp dụng); (v) B3d-Sa huấn luyện lại với số vòng lặp của Oracle. Phải khai rằng tỉ số post hoc và cả hai cận (tại σ_post, tại sai số warp, biến thể 60 Hz và phổ chéo) đã được xem ngày 29/10. Không confirmatory (D-8)."},
{id:"p6-gen", t:"Sửa generator cho S2 (misspec rock physics, wavelet, σ_b/drift); dev trên realization 902–905", s:"todo", n:"T2 2/11 – T3 3/11. Đường mặc định của D2 phải tái lập đúng P2r."},
{id:"p6-lock", t:"Viết và khoá configs/protocol_bench.yaml (S1, S2, S3, S4, S8)", s:"todo", n:"T3 3/11, trước lần chạy chính đầu tiên; kèm .sha256 và .lock.json. Ghi rõ là thiết kế sau khi đã thấy P2r."},
{id:"p6-s1", t:"S1: lấp lưới c ∈ {0.5, 1.5}, N ∈ {2, 8}", s:"todo", n:"T4 4/11 – T5 5/11, hai GPU."},
{id:"p6-s3s4", t:"S3: B4 dưới posterior SMC; S4: backbone thứ hai", s:"todo", n:"T4 4/11 – T5 5/11."},
{id:"p6-s2", t:"S2: ba trục misspec ở R10, Rm5, c = 1, N ∈ {4, 16}", s:"todo", n:"T6 6/11 – T7 7/11. Bắt buộc (D-7): thiếu S2 thì bài gọi là controlled synthetic study, không gọi là benchmark."},
{id:"p6-s8", t:"S8/T8: regime cycle-skip có kiểm soát", s:"todo", n:"T7 7/11."},
{id:"p6-s7", t:"S7: đóng gói benchmark (một lệnh sinh, một lệnh chấm, bảng tham chiếu, README, hash, Zenodo)", s:"todo", n:"CN 8/11 – T3 10/11."},
{id:"p6-write", t:"Viết lại các mục kết quả theo số liệu mới", s:"todo", n:"CN 8/11 – T3 10/11."}
]},
{id:"P7", name:"P7 Review và nộp", start:"2026-11-11", end:"2026-11-14", weeks:"T4–T7 11–14/11",
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ý đọc góp ý", s:"todo"}, {id:"p7-rev", t:"Review nội bộ; hình; phụ lục chứng minh; gói tái lập", s:"todo", n:"T4 11/11 – T5 12/11."},
{id:"p6-nov", t:"Kiểm tra tính mới lần cuối, tra quartile của venue", s:"todo"}, {id:"p7-nov", t:"Kiểm tra tính mới lần cuối, tra quartile, đăng preprint", s:"todo", n:"T6 13/11."},
{id:"p6-sub", t:"Đăng preprint và nộp", s:"todo"} {id:"p7-sub", t:"Nộp Computers & Geosciences", s:"todo", n:"T7 14/11."}
]} ]}
]; ];
@@ -286,12 +336,12 @@ const XM = [
{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:"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 (dữ liệu thời gian–độ sâu 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ạ độ, 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:"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ừ khoá: well tie uncertainty, misalignment, label noise, porosity, impedance."}, {name:"Quét SEG/EAGE 2024–2026", where:"mục 2.4 (4)", s:"done", r:"Xong ngày 28/10/2026. Thêm 10 bài chỉ có abstract (AWSM, BootNet, Quesada, Mirza, Guillon, Cordoba, Thiebaud, Rizzuti ×2, Huff) vào paper/refs.bib và §2. Không bài nào đưa posterior của tie vào huấn luyện; câu 'to our knowledge' giữ nguyên. Còn mở: abstract IMAGE 2026 của Palavicini Gurria et al., DOI của Quesada 2024."},
{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 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:"5 bài mới đọc được abstract (P03, P04, P05, P07, P09)", where:"mục 2.2", s:"done", r:"Đóng ngày 28/10/2026. P03 có toàn văn (refs/xu2024sts.pdf). P04, P05, P07, P09 không lấy được toàn văn; mọi chỗ trích trong bản thảo đã đối chiếu với abstract và đều khớp; giữ chú thích abstract-only."},
{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 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:"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/gunning2006waveletextractor.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:"Bỏ ngày 26/10/2026 vì 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."}
]; ];
@@ -299,7 +349,15 @@ const DECISIONS = [
{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-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 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-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.", 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-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 cổng", p:"Geophysical Prospecting hoặc J. Applied Geophysics (giữ đề xuất).", n:"Chưa tra quartile."} {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. 29/10: thay bằng D-9."},
{id:"D-5", q:"Hướng bài sau khi G-C và G-D không đạt", p:"Pivot 1: bài lý thuyết + benchmark synthetic. Tên làm việc: Label registration error in sparse-well seismic property learning: theory, a registration-aware benchmark, and the limits of field validation. F3 và Volve là hai trường hợp giới hạn phạm vi, không phải bằng chứng ủng hộ hay chống RML.", n:"Phần đứng được là lý thuyết (Mệnh đề 1 khớp trong 1%, Mệnh đề 2) và P2r (H2a, H2b, nhánh σ_a). Hai field test không có lực phân biệt: F3 chênh 0,016 p.u. giữa phương pháp so với 0,13 p.u. giữa seed; Volve hằng số thắng mọi mạng. Phân tích ở docs/research/pivot-theory-benchmark.md; plan mục 12 ý 22."},
{id:"D-6", q:"Hạn nộp", p:"Mức B: dời sang thứ 7, 14/11/2026. Ngưỡng và luật của mọi cổng không đổi.", n:"Mức A (31/10) chỉ cho một controlled study chưa đầy lưới. Lịch theo ngày ở plan mục 6.1. Người dùng chốt."},
{id:"D-7", q:"Trục misspecification (S2) có bắt buộc không?", p:"Bắt buộc, phạm vi hẹp: ba trục (rock physics sai hệ số; wavelet sai pha và băng thông; σ_b / prior drift sai) × regime R10, Rm5 × c = 1 × N ∈ {4, 16}, realization 8–15, dev trên 902–905, phương pháp Oracle, B3c-R, B3d-Sa, M2-Sa. Khoá trong configs/protocol_bench.yaml trước lần chạy đầu.", n:"Rủi ro lớn nhất của bài benchmark là cùng simulator với phương pháp. Nếu đến 10/11 chưa xong S2 thì bài gọi là controlled synthetic study."},
{id:"D-8", q:"T2 (cơ chế lợi ích của bank) là confirmatory hay exploratory?", p:"Exploratory, trên realization 8–15 với bank P2r đã có; khai báo trước ở docs/research/t2-mechanism.md. Trong bài là mechanism analysis kèm Mệnh đề 3. Không sinh realization 16–23 cho T2.", n:"Giả thuyết tái đăng ký ngầm hình thành sau khi thấy H2b; một lượt SMC riêng cho T2 không vừa hai tuần. (29/10: đánh số lúc lập kế hoạch; trong bài, giả thuyết tái đăng ký ngầm là Nhận xét 1, còn Mệnh đề 3 của bài là hai cấu trúc sai số của tie.)"},
{id:"D-9", q:"Venue", p:"Computers & Geosciences; dự phòng Geophysical Prospecting.", n:"Nhận bài benchmark kèm code, yêu cầu code/data availability (khớp S7). Quartile tra lại khi nộp [XM]."},
{id:"D-10", q:"Số phận P4x", p:"Bỏ hẳn. Không dùng trong bài, không chạy V3, không tổng hợp; exploratory/ và outputs/p4x/ giữ làm hồ sơ.", n:"Không phục vụ bài mới; biến thể chọn sau khi thấy nhãn test. Người dùng chốt."},
{id:"D-11", q:"Teapot Dome làm field test thứ ba?", p:"Không. Dừng Teapot, giữ Pivot 1 và lịch mức B; T3 và C1–C4 vào bài như phân tích exploratory về điều kiện cần của một field test, không phải claim.", n:"T0: chỉ 4 bảng TD, tối đa 2 giếng độc lập (cần ≥ 3 cho C3 cộng 11–18 cho C4). Pilot P-a (knot horizon–top, 37 giếng dev, chưa mở porosity): σ̂_knot 6,75 ms (CI 90% 4,1–9,4) so với dung sai 1,5 ms. Người dùng chốt: quay về lịch mức B."},
{id:"D-12", q:"Bản thảo dài hơn giới hạn của venue", p:"Bỏ lượt rút gọn độ dài cho venue. Rủi ro độ dài vẫn ghi lại (plan R9), chưa có biện pháp.", n:"Thân bài khoảng 14.750 từ (đếm thô sau A6); giới hạn Research Article khoảng 5.500 từ theo nguồn thứ cấp (trang chính thức không tải được). Agent đã đề xuất rút gọn ngày 30–31/10 (chứng minh, Thí nghiệm 1, H1 và Phụ lục B sang Supplementary); người dùng bỏ phương án này ngày 29/10 (plan §12 ý 25). Người dùng chốt."}
]; ];
const FINDS = [ const FINDS = [
@@ -309,8 +367,8 @@ const FINDS = [
{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:"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:"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:"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:"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:"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:"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:"Dataset trong outputs_thesis/ 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:"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:"Bộ v2 đã có; metric lưu không khớp số trong luận văn", p:"27/10: outputs_thesis/ có open_loop_patch_best_v2.pt (metadata có GRU tầng 2, head_skip, bias) và dự đoán F06-1 v2. Tính trực tiếp trên 126 cặp, không dịch thời gian: <b>PCC 0.0295</b>, MSE 0.0018715, R² −0.3460; best-shift +16 mẫu chỉ cho PCC 0.1068. Code v2 giữ nguyên nhãn test. Volume đọc được, nhưng code vẽ vẫn dùng min–max thay cho Z-score. Chưa chạy lại checkpoint. Chi tiết: <a href='docs/research/thesis-output-audit.md'>audit output</a>. Nhận định cũ về checkpoint v1 và volume rỗng thuộc bộ file ngày 26/10."},
{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:"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:"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:"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:"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:"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."},
@@ -328,7 +386,15 @@ const FINDS = [
{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:"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:"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:"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."} {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."},
{h:"Volve: không phương pháp nào có kỹ năng ở giếng blind", p:"29/10, P4: R² macro âm với mọi phương pháp ở cả lowo và slot. Hằng số bằng trung bình PHIF của giếng train (post hoc, không dùng seismic) có RMSE <b>6,03 / 6,59 p.u.</b>, thấp hơn mọi mạng (6,36–7,32). Mức trung bình PHIF giữa các giếng lệch nhau tới 8,5 p.u.; độ lệch trung bình của mạng ở mỗi giếng bám độ lệch của hằng số (F-12: −6,8 so với −6,0 p.u.). Khác biệt giữa các tie ≤ 0,25 p.u."},
{h:"Volve: posterior tie hẹp hơn và pha xác định tốt hơn F3", p:"σ_post trung vị 4,3 ms (1,9–9,3 ms) và gần như không theo σ_a (3,8 / 4,3 / 4,1 ms ở 3,5 / 7 / 14 ms), khác F3. Pha wavelet của 22 tập train nằm trong cung 43° (F3: 214°). Gợi ý registration không phải nút thắt trên Volve; không kiểm tra được với warp thật."},
{h:"Tie trung bình posterior làm sắc, không làm mờ", p:"Mệnh đề 3 của bài: sai số classical (độc lập với nhãn thật) làm mờ predictor và nới phương sai học được; sai số <b>Berkson</b> (độc lập với dữ liệu, như tie trung bình posterior) làm sắc và thu hẹp. Bank hiệu chỉnh có cùng nghiệm quần thể với nhãn thật (Mệnh đề 4), nhưng lợi ích quần thể so với nhãn điểm chỉ là <b>bậc bốn</b> theo σ. Cận 1/B(σ_post) dùng cho H2b là ρ* dưới cấu trúc classical. Dưới Berkson, cận thấp hơn nhiều. Hệ số e^{4π²σ²f²} giữa hai tích phân là 1,10 ở 25 Hz nhưng 1,77 ở 60 Hz (σ = 2 ms), và méo có trọng số f⁴ nằm ở 67–72 Hz. Ở σ = 2 ms, tích phân Berkson vì thế gấp <b>2,1–2,6</b> lần. Nhận định trước đó \"hệ số dưới 1,17, cấu trúc gần như không đổi cận\" sai (chỉ xét ≤ 25 Hz) và đã được sửa ngày 29/10."},
{h:"Lợi ích của bank: vượt cận classical, phần lớn trong cận Berkson (post hoc)", p:"scripts/31_p2r_posthoc.py, 8 ô rộng ở N = 16. Với cận classical đã đăng ký, M2-Sa/B3d-Sa thấp hơn cận ở <b>7/8</b> ô khi tính tại σ_post và <b>6/8</b> khi tính tại sai số warp RMS. R10tb c = 2 vượt mép lưới blur 6 ms, nên cận bị kẹp ở 1/B(6 ms) = 0,634; tính đúng tại σ_post là 0,481. Cận Berkson, cấu trúc tự nhiên cho nhãn tại warp trung bình, được tính post hoc. Với cận này chỉ <b>3/8</b> ô vượt tại σ_post (R0, R0h, R10tb ở c = 1; hai ô sau lề < 0,004), và tối đa 1/8 tại sai số warp. Hai biến thể (giữ hệ số ở 60 Hz; phổ chéo) cho cùng kết quả. Nhận định \"vượt cận\" ghi trước đó đã bị rút lại; chưa kiểm sai số thật có kiểu Berkson không (T2 test iv). M2-Sa không đạt Oracle ở ô rộng nào (kém 4–6% ở R0, R0h, Rm5 với c = 1; 17% ở R10tb c = 1; 63% ở R10tb c = 2) và chỉ đóng 27–46% khoảng cách tới Oracle ở c = 1, 39–65% ở c = 2. Nguồn lợi ích còn mở (T2)."},
{h:"Coverage: độ dài huấn luyện lẫn với nguồn nhãn (T4, post hoc)", p:"Mọi ensemble quá hẹp: tỉ số ξ = E s²/E(y − μ)² chỉ <b>0,19</b> ở Oracle và tối đa 0,66 (B5) ở R10, c = 1, N = 16. B3c-R học 500 vòng lặp như Oracle và đạt cùng ξ với B3d-Sa ở 250 vòng. Trên dev, coverage90 của Oracle đơn lẻ giảm 0,47 → 0,23 → 0,10 sau 125/500/2000 vòng. Phần (b), (c) của Mệnh đề 5 chưa kiểm; không claim hiệu chỉnh."},
{h:"Reference ở giếng blind phải chính xác cỡ 1 ms (T3, exploratory)", p:"Chấm lại dự đoán P2r với reference lệch σ_ref: tỉ số band RMSE trung vị cắt 1 ở <b>3,6–4,3 ms</b> (Hệ quả 4 dự báo σ/√2 = 3,0/4,1/5,1 ms). Sign test α = 0,05 cần 5–18 giếng blind nếu reference chính xác (5/6 ô), 11–30 giếng ở 1 ms (4 ô); ở 2 ms chỉ R0 còn trong 40 giếng; từ 3 ms không ô nào. Luật k-of-n của G-C, G-D không phải phép kiểm: đạt ngẫu nhiên với xác suất 0,31 (n = 4) và 0,11 (n = 6)."},
{h:"F3 và Volve trượt điều kiện C1; Teapot không có reference TD độc lập", p:"Hồi cứu (scripts/26): band PCC ở giếng blind 0,15 (F3) và 0,13/0,04 (Volve), dưới ngưỡng 0,47 suy từ D2; cả hai đạt C2 (σ_post trung vị 2,8 và 4,3 ms). Teapot Dome: 152 giếng có density trong survey 3-D nhưng tối đa <b>2</b> giếng có TD độc lập; knot horizon–top cho σ̂_knot <b>6,75 ms</b> (CI 90% 4,1–9,4) so với dung sai 1,5 ms (D-11)."},
{h:"Bản thảo dài gấp khoảng 2,7 lần giới hạn của venue", p:"Thân bài (mục 1–8) khoảng <b>14.750</b> từ (đếm thô sau A6); giới hạn Research Article của Computers & Geosciences khoảng 5.500 từ theo nguồn thứ cấp, chưa kiểm trên trang chính thức. Người dùng bỏ lượt rút gọn (D-12); rủi ro vẫn mở."}
]; ];
const DATA = [ const DATA = [
@@ -341,7 +407,7 @@ const DATA = [
{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: 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à quỹ đạo", 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: 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:"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, 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."} {n:"outputs_thesis/ của luận văn", s:"done", note:"Bổ sung 27/10: 7 artifact, có dataset, checkpoint/dự đoán v2, volume 278756708 byte và 3 hình PNG. Manifest SHA-256: data_manifest/thesis_outputs.json. Metric dự đoán và giới hạn kiểm tra ở docs/research/thesis-output-audit.md; chưa chạy lại checkpoint."}
]; ];
// 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…)
@@ -446,8 +512,8 @@ const LOG = [
["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","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 plan 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, 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","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. Tại thời điểm đó còn thiếu bộ output luận văn (đã bổ sung trong outputs_thesis/ ngày 27/10)."],
["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","Kiểm tra bộ output cũ ngày 26/10: dataset xác nhận giếng đặt sai chỗ; checkpoint và dự đoán khi đó 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 khi đó rỗng. Bộ này đã được thay bằng outputs_thesis/ có v2 ngày 27/10."],
["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","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 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","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 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","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)."],
@@ -458,7 +524,23 @@ const LOG = [
["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","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","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","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."] ["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."],
["2026-10-27","Đổi tham chiếu thư mục code luận văn thành code_thesis/; bổ sung outputs_thesis/ và manifest 7 artifact. Volume đọc được (651 × 951 × 126), checkpoint có metadata v2. Tính lại dự đoán F06-1 đã lưu: PCC 0.0295, MSE 0.0018715, R² −0.3460, không dịch thời gian. Cập nhật plan, README và audit; chưa chạy lại checkpoint vì môi trường hiện chưa có Python/PyTorch."],
["2026-10-28","P3 F3 hoàn tất 06:50 (+07:00): 1.320 trajectory nested LOWO, ablation, diagnostics, 20 mô hình triển khai, volume 649 inline. G-C KHÔNG ĐẠT (1/4 giếng; coverage 52,38/60,91%). Lượt đầu dừng ở 132/649 inline vì Windows khóa progress.js; phục hồi riêng phần inference, qua kiểm tra."],
["2026-10-28","Bản thảo bài (paper/) với kết quả F3; scripts/22_paper_figures.py. Quét SEG/EAGE 2024–2026; đóng mục kiểm tra abstract P04/P05/P07/P09."],
["2026-10-28","P4 Volve: lớp dữ liệu giếng nghiêng (ml_porosity/data/deviated.py, volve_wells.py, scripts/23), pipeline ml_porosity/volve/ và scripts/24, nháp protocol_volve; smoke CPU 22/22 registration, 110/110 job. Deviation member_support phát hiện ở smoke, sửa trước khóa."],
["2026-10-29","P4 trên server Linux: benchmark 01:16 UTC, khóa protocol_volve 01:17:42 UTC, chạy nhánh chính (cuda:1) và nhánh σ_a (cuda:0) song song, xong 02:21 UTC. G-D: 2/6 và 3/6 giếng, coverage90 ≈ 0,47–0,48; không claim cải thiện, không claim hiệu chuẩn."],
["2026-10-29","Post hoc P4 (scripts/25_p4_posthoc.py → outputs/p4/posthoc/): hằng số trung bình train thắng mọi mạng; sai số do mức giữa giếng chi phối. Bắt đầu exploratory P4x (khai báo trước ở docs/research/p4-exploratory.md; chỉ mô tả)."],
["2026-10-29","P5: viết các mục Volve của bài và đặt trục bài vào lý thuyết + benchmark synthetic; F3 và Volve là kiểm tra thực tế giới hạn phạm vi. Cập nhật report.html, plan.md, README, AGENTS.md, technical_overview.md."],
["2026-10-29","Khảo sát dataset field public (docs/research/field-dataset-survey.md): 12 ứng viên theo 7 tiêu chí; chưa có dataset nào xác nhận đủ điều kiện (điểm nghẽn là checkshot ở giếng test); Teapot Dome và Groningen là ứng viên cần kiểm kê sau. Không thêm field test trong bài này."],
["2026-10-29","Chốt Pivot 1 (D-5 đến D-10): bài lý thuyết + benchmark; dời hạn sang 14/11 (mức B); S2 bắt buộc dưới protocol_bench khoá trước; T2 exploratory; venue Computers & Geosciences; bỏ hẳn P4x (job đang chạy để tự kết thúc, kết quả không dùng). Cập nhật plan.md mục 0, 6.1, 8, 9, 12 ý 22; AGENTS.md; docs/research/pivot-theory-benchmark.md mục 6."],
["2026-10-29","Dừng job P4x ở 670/921 (khoảng 04:05 UTC) và kill để trả cuda:0; nhánh B3d-Sa và V3 chưa chạy. Theo D-10, phần output train dở chỉ giữ làm hồ sơ, không dùng; bản tổng hợp dở tạo lúc 04:07 UTC đã xóa."],
["2026-10-29","Điều kiện áp dụng C1–C4 (khai báo trước ở docs/research/applicability-teapot.md, exploratory): F3 và Volve trượt C1, đạt C2 (scripts/26). T3 power (scripts/27): cần 5–18 giếng blind với reference chính xác; σ_ref ≥ 3 ms thì 40 giếng không đủ. Teapot Dome: T0 trượt (tối đa 2 giếng TD độc lập), pilot P-a trượt (σ̂_knot 6,75 ms so với 1,5 ms); dừng Teapot, quay về lịch mức B (D-11). Thêm data/Teapot/ (1,7 GB) vào .gitignore."],
["2026-10-29","Viết xong mức A sớm (A1–A5, plan §12 ý 24): khung bài Pivot 1; Mệnh đề 3–6, Hệ quả 3–4, Nhận xét 1; sửa cách đọc cận 1/B(σ_post) (tie trung bình posterior gần Berkson); T4 (scripts/30) và kiểm cận post hoc (scripts/31) ở mục 6.3; T3 ở mục 6.5; F3, Volve sang Phụ lục B; related work về label noise. Bài 54 trang, build sạch. Rủi ro độ dài (D-12)."],
["2026-10-29","Đồng bộ tài liệu (A6): plan §0, §6, §6.1, §8, §9 (R9), §12 ý 23–24; AGENTS.md; README.md (scripts 26–31); paper/README.md (nguồn số liệu theo mục mới); docs/theory.md mục 6 và ghi chú sửa mục 1.4; tài liệu pivot. Chưa commit."],
["2026-10-29","Tự sửa hai nhận định của chính mình (plan §12 ý 24). (1) Câu \"hai cấu trúc sai số gần như cho cùng cận (hệ số < 1,17)\" sai: méo nằm ở 67–72 Hz, nơi tích phân Berkson gấp 1,5–4,6 lần ở σ = 1,5–2,5 ms. (2) Câu \"lợi ích của bank vượt cận quần thể\" chỉ đúng với cận classical đã đăng ký (7/8 ô). Với cận Berkson tính post hoc, chỉ 3/8 ô vượt (cả ba ở c = 1) và tối đa 1/8 tại sai số warp. scripts/31 viết lại để tính cận (a), (b), b60 và phổ chéo (đọc npz của Oracle, khoảng 6 phút; tái lập đúng số đã đăng ký). Đã sửa bài mục 4.3, 6.3 (cột 1/B_b ở Bảng tab:h2b), 6.4, 7, tóm tắt, mở bài, kết luận, cùng tài liệu. Câu hỏi của T2 đổi thành: còn lợi ích nào vượt hiệu chỉnh Berkson không. Bài build sạch, 55 trang; thân bài khoảng 14.750 từ (đếm thô), tóm tắt 292 từ. Chưa commit."],
["2026-10-29","Người dùng bỏ lượt rút gọn độ dài cho venue (D-12, plan §12 ý 25). Thẻ p5-len thay bằng p5-cite (trích dẫn dataset F3, Volve; 30–31/10). Rủi ro độ dài (R9) vẫn ghi lại, chưa có biện pháp."],
["2026-10-29","Commit và push lên main mọi thay đổi từ P4 đến A6 (code P4, configs/protocol_volve.*, scripts 26–31, docs/research, bản ghi P4x, bài và tài liệu), kèm tag protocol-volve. Hash code tính lại từ cây commit khớp configs/protocol_volve.lock.json. 190 test pass, 1 skip. logs/*.out vẫn không theo dõi như trước (plan §12 ý 25)."]
]; ];
/* ===================== HẾT DATA ===================== */ /* ===================== HẾT DATA ===================== */
@@ -468,7 +550,7 @@ 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) {} }
// A manual override is stored with the status in DATA at the time it was made ({s, base}); once DATA changes, the // 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". // 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]; const stateOf = t => { const live = window.ML_POROSITY_P3?.tasks?.[t.id]; if (live) return live; const v = saved[t.id];
if (v && typeof v === "object") return v.base === t.s ? v.s : t.s; if (v && typeof v === "object") return v.base === t.s ? v.s : t.s;
return (typeof v === "string" && t.s === "todo") ? v : 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 TASK = Object.fromEntries(PHASES.flatMap(p => p.tasks).map(t => [t.id, t]));
@@ -561,7 +643,38 @@ function renderStatic(){
$("#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("");
} }
function renderAll(){ renderTiles(); renderGantt(); renderPhases(); } function renderP3(){
const p = window.ML_POROSITY_P3, el = $("#p3-live");
if (!p || !el) return;
el.replaceChildren();
const title = document.createElement("b"); title.textContent = "P3 trên RTX 3060 · " + (p.status || "đang chuẩn bị"); el.append(title);
const note = document.createElement("p"); note.textContent = p.message || ""; el.append(note);
const info = document.createElement("div"); info.className = "sub";
const jobs = p.total ? ` · ${p.completed || 0}/${p.total} job` : "";
const eta = p.eta_seconds != null ? ` · còn khoảng ${(p.eta_seconds/3600).toFixed(1)} giờ` : "";
info.textContent = "Cập nhật: " + (p.updated || "chưa có") + jobs + eta + (p.error ? " · Lỗi: " + p.error : ""); el.append(info);
const link = document.createElement("a"); link.href = "outputs/p3/progress.json"; link.textContent = "Chi tiết tiến độ"; el.append(link);
if (p.full_runtime_range_seconds) {
const runtime = document.createElement("p"); runtime.className = "sub";
runtime.textContent = "Ước lượng toàn bộ lần chạy mới: " + p.full_runtime_range_seconds.map(x => (x/3600).toFixed(1)).join("–") + " giờ. ETA từng giai đoạn ở trên được cập nhật theo số job thực tế."; el.append(runtime);
}
if (p.gate?.evaluated) {
const result = document.createElement("p");
result.textContent = `G-C: ${p.gate.pass ? "ĐẠT" : "KHÔNG ĐẠT"} · cải thiện ${p.gate.improved_wells}/4 giếng · coverage 80%: ${(100*p.gate.coverage_80).toFixed(1)}% · coverage 90%: ${(100*p.gate.coverage_90).toFixed(1)}%.`; el.append(result);
const summary = document.createElement("a"); summary.href = "outputs/p3/summary/summary.md"; summary.textContent = "Đọc kết quả LOWO và giới hạn diễn giải"; el.append(summary);
}
}
function renderAll(){
const gate = window.ML_POROSITY_P3?.gate;
if (gate?.evaluated) PHASES.find(p => p.gate?.label === "G-C").gate.res = `${gate.pass ? "ĐẠT" : "KHÔNG ĐẠT"}; cải thiện ${gate.improved_wells}/4 giếng; coverage 80/90%: ${(100*gate.coverage_80).toFixed(1)}% / ${(100*gate.coverage_90).toFixed(1)}%.`;
renderTiles(); renderGantt(); renderPhases(); renderP3();
}
function pollP3(){
const script = document.createElement("script"); script.src = "outputs/p3/progress.js?t=" + Date.now();
script.onload = () => { renderAll(); script.remove(); };
script.onerror = () => script.remove(); document.body.append(script);
}
pollP3(); setInterval(pollP3, 10000);
$("#reset").addEventListener("click", () => { if (confirm("Đặt lại tất cả trạng thái công việc về giá trị ban đầu?")) { saved = {}; persist(); renderAll(); } }); $("#reset").addEventListener("click", () => { if (confirm("Đặt lại tất cả trạng thái công việc về giá trị ban đầu?")) { saved = {}; persist(); renderAll(); } });
$("#theme").addEventListener("click", () => { $("#theme").addEventListener("click", () => {

View File

@@ -0,0 +1,45 @@
# Validated on Windows, Python 3.12.16, NVIDIA driver 577.00, RTX 3060 12 GB.
# Linux requirements-lock.txt is retained separately. Install this then -e . --no-deps.
--extra-index-url https://download.pytorch.org/whl/cu128
cloudpickle==3.1.2
colorama==0.4.6
contourpy==1.4.0
cycler==0.12.1
filelock==3.32.3
fonttools==4.67.0
fsspec==2026.7.0
iniconfig==2.3.1
jinja2==3.1.6
joblib==1.6.0
kiwisolver==1.5.1
lasio==0.32
llvmlite==0.50.0
markupsafe==3.0.3
matplotlib==3.11.2
mpmath==1.3.0
narwhals==2.28.0
networkx==3.6.1
numba==0.68.0
numpy==2.5.4
packaging==26.3
pandas==3.1.0
pillow==13.0.0
pluggy==1.7.0
psutil==7.2.2
pygments==2.21.0
pylops==2.8.0
pyparsing==3.3.3
pytest==9.1.1
python-dateutil==3.0.0
pyyaml==6.0.3
scikit-learn==1.9.1
scipy==1.18.1
segyio==1.9.14
setuptools==78.1.0
six==1.17.0
sympy==1.14.0
tabulate==0.10.0
threadpoolctl==3.7.0
torch==2.11.0+cu128
typing-extensions==4.16.0
tzdata==2026.5

View File

@@ -4,6 +4,7 @@
python scripts/00_data_manifest.py --check # check only; exit 1 on mismatch python scripts/00_data_manifest.py --check # check only; exit 1 on mismatch
python scripts/00_data_manifest.py --dataset volve # same for data/Volve python scripts/00_data_manifest.py --dataset volve # same for data/Volve
python scripts/00_data_manifest.py --dataset nlog # same for data/NLOG python scripts/00_data_manifest.py --dataset nlog # same for data/NLOG
python scripts/00_data_manifest.py --dataset thesis # same for outputs_thesis
""" """
from __future__ import annotations from __future__ import annotations
@@ -22,6 +23,7 @@ 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), HRS licence / 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), public LAS and TD data for the F3 wells; URLs in 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"),
"thesis": (lambda: REPO_ROOT / "outputs_thesis", "thesis_outputs.json", "Thesis outputs archived in outputs_thesis; source code in code_thesis"),
} }
@@ -55,7 +57,7 @@ def main() -> int:
current = scan(root) current = scan(root)
if args.check: if args.check:
ref = json.loads(manifest.read_text())["files"] ref = json.loads(manifest.read_text(encoding="utf-8"))["files"]
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))
@@ -74,7 +76,7 @@ def main() -> int:
"files": current, "files": current,
} }
manifest.parent.mkdir(parents=True, exist_ok=True) manifest.parent.mkdir(parents=True, exist_ok=True)
manifest.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n") manifest.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"{out['n_files']} file, {out['total_bytes'] / 1e9:.2f} GB -> {manifest.relative_to(REPO_ROOT)}") print(f"{out['n_files']} file, {out['total_bytes'] / 1e9:.2f} GB -> {manifest.relative_to(REPO_ROOT)}")
return 0 return 0

View File

@@ -2,7 +2,7 @@
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]
Differences from `test 2/train_open_patch_v2.py`: correct well locations, selectable TDR, validation well Differences from `code_thesis/train_open_patch_v2.py`: correct well locations, selectable TDR, validation well
separate from the train wells, no label clipping, no lag estimated from seismic–PHIE correlation, separate from the train wells, no label clipping, no lag estimated from seismic–PHIE correlation,
metrics computed on the true scale. Outputs: outputs/runs/<config name>_s<seed>/. metrics computed on the true scale. Outputs: outputs/runs/<config name>_s<seed>/.
""" """

75
scripts/19_run_f3.py Normal file
View File

@@ -0,0 +1,75 @@
"""P3 on Windows/Linux: prepare -> benchmark -> lock -> register -> train -> diagnostics -> summarize.
Full run: python scripts/19_run_f3.py all --device cuda:0 --workers 4
CPU and reduced smoke results are never presented as the registered P3 experiment.
"""
from __future__ import annotations
import argparse
import os
import traceback
os.environ.setdefault('OMP_NUM_THREADS', '2')
os.environ.setdefault('MKL_NUM_THREADS', '2')
os.environ.setdefault('OPENBLAS_NUM_THREADS', '2')
os.environ.setdefault('NUMBA_NUM_THREADS', '2')
os.environ.setdefault('PYTHONHASHSEED', '0')
os.environ.setdefault('PYTHONUTF8', '1')
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
def main() -> None:
from ml_porosity.f3.progress import update
from ml_porosity.f3.protocol import freeze, load_protocol
from ml_porosity.f3.runner import benchmark, benchmark_registration, prepare, run
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('stage', choices=['status', 'prepare', 'benchmark', 'benchmark-registration', 'lock', 'register', 'train', 'diagnostics', 'summarize', 'all'])
ap.add_argument('--device', default='cuda:0')
ap.add_argument('--workers', type=int, default=4)
ap.add_argument('--smoke', action='store_true')
ap.add_argument('--sections', action='store_true', help='Explicitly reduce volume scope; never selected automatically')
ap.add_argument('--skip-volume', action='store_true', help='Stop after LOWO summary; leaves the volume task incomplete')
ap.add_argument('--benchmark-steps', type=int, default=100)
ap.add_argument('--benchmark-workers', type=int, nargs='+', default=[1, 2, 3])
args = ap.parse_args()
if args.workers < 1:
ap.error('--workers must be positive')
p = load_protocol()
if os.name == 'nt':
import ctypes
# Prevent automatic system sleep only while this process is alive.
ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
try:
if args.stage == 'status':
from ml_porosity.paths import outputs_dir
progress = outputs_dir()/'p3/progress.json'
print(progress.read_text(encoding='utf-8') if progress.exists() else 'P3 has not started.')
elif args.stage == 'prepare':
prepare()
elif args.stage == 'benchmark':
print(benchmark(p, args.device, args.benchmark_steps, args.benchmark_workers))
elif args.stage == 'benchmark-registration':
print(benchmark_registration(p, args.device))
elif args.stage == 'lock':
print(freeze())
update(tasks={'p3-protocol': 'done'}, status='Protocol F3 đã khoá', message='Mã băm protocol, code và dữ liệu được kiểm tra trước mọi giai đoạn P3.')
else:
stages = ['register', 'train', 'diagnostics', 'summarize'] if args.stage == 'all' else [args.stage]
for stage in stages:
run(stage, p, args.device, args.workers, args.smoke)
if args.stage == 'all' and not args.smoke and not args.skip_volume:
from ml_porosity.f3.volume import fit_deployment, predict_volume
fit_deployment(p, args.device, args.workers)
predict_volume(p, args.device, args.sections)
except Exception as exc:
update(status='Có lỗi cần xử lý', error=str(exc), message=f'Giai đoạn {args.stage} chưa hoàn tất; các job đã ghi đủ vẫn có thể resume.')
traceback.print_exc()
raise SystemExit(1)
finally:
if os.name == 'nt':
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,8 @@
"""Summarize the frozen P3 run; use 19_run_f3.py summarize for all options."""
from ml_porosity.f3.protocol import freeze, load_protocol
from ml_porosity.f3.evaluation import summarize
from ml_porosity.paths import outputs_dir
if __name__ == '__main__':
freeze(check=True)
print(summarize(load_protocol(), outputs_dir()/'p3'))

25
scripts/21_predict_f3.py Normal file
View File

@@ -0,0 +1,25 @@
"""Fit deployment models or stream the descriptive full F3 volume after P3 LOWO."""
from __future__ import annotations
import argparse
def main():
from ml_porosity.f3.protocol import load_protocol
from ml_porosity.f3.volume import fit_deployment, predict_volume
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('stage', choices=['fit', 'predict'])
ap.add_argument('--device', default='cuda:0')
ap.add_argument('--workers', type=int, default=3)
ap.add_argument('--sections', action='store_true')
ap.add_argument('--limit-inlines', type=int)
args = ap.parse_args()
p = load_protocol()
if args.stage == 'fit':
print(fit_deployment(p, args.device, args.workers))
else:
print(predict_volume(p, args.device, args.sections, args.limit_inlines))
if __name__ == '__main__':
main()

302
scripts/22_paper_figures.py Normal file
View File

@@ -0,0 +1,302 @@
"""Journal-style figures for the manuscript (paper/figures/*.pdf), drawn from the locked summaries only.
python scripts/22_paper_figures.py [--only td_drift,h1,p2_phase,h2b,p2r_grid,f3_volume]
Reads: F3 wells (TD QC), outputs/p2/h1/, outputs/p2/summary/main/cells.csv, outputs/p2r/summary/{h2b,band_rmse}.csv,
outputs/p3/volume/{metadata.json,mean.npy,sigma.npy}, outputs/f3_wells.npz (well inline/crossline).
No titles or verdicts inside the figures (captions carry them); Computer Modern text to match the manuscript;
palette of ml_porosity.eval.figstyle (validated, colour-blind safe) on a white surface.
"""
from __future__ import annotations
import argparse
import importlib.util
import matplotlib
matplotlib.use("Agg")
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap, Normalize
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from ml_porosity.eval import figstyle as fs
from ml_porosity.paths import REPO_ROOT, outputs_dir
FIG = REPO_ROOT / "paper" / "figures"
WIDTH = 6.3 # in; \textwidth of the manuscript (A4, 2.5 cm margins)
WHITE = "#ffffff"
SEQ_BLUE = LinearSegmentedColormap.from_list("seq_blue", ["#f0f5fc", "#86b6ef", "#2a78d6", "#104281"])
RAMP4 = ["#86b6ef", "#5598e7", "#256abf", "#104281"] # ordinal ramp for σ (as in scripts/13)
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
METHODS = [("B3b", "B3b"), ("B3c", "B3c"), ("B3c-R", "B3c-R"), ("B3d", "B3d"), ("B3d-Sa", "B3d-Sa"), ("M2-Sa", "M2-Sa")]
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 style() -> None:
fs.apply()
mpl.rcParams.update({
"figure.facecolor": WHITE, "axes.facecolor": WHITE, "savefig.facecolor": WHITE,
"font.family": "serif", "font.serif": ["cmr10"], "mathtext.fontset": "cm", "axes.unicode_minus": False,
"axes.formatter.use_mathtext": True, "font.size": 8, "axes.labelsize": 8, "xtick.labelsize": 7.5,
"ytick.labelsize": 7.5, "legend.fontsize": 7.5, "axes.titlesize": 8.5, "axes.titlelocation": "left",
"pdf.fonttype": 42, "lines.linewidth": 1.4,
})
def panel(ax, letter: str) -> None:
ax.set_title(f"({letter})", loc="left", fontsize=8.5, color=fs.INK, pad=4)
def text_on(rgba) -> str:
return fs.INK if 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2] > 0.55 else WHITE
def save(fig, name: str) -> None:
FIG.mkdir(parents=True, exist_ok=True)
fig.savefig(FIG / f"{name}.pdf", bbox_inches="tight", pad_inches=0.02)
plt.close(fig)
print("wrote", FIG / f"{name}.pdf")
# ---------------------------------------------------------------- Fig. TD drift (Section 3)
def td_drift() -> None:
from ml_porosity.data.las_io import F3_WELLS, load_td_source, load_well
from ml_porosity.data.tdr import TDR, legacy_sonic_tdr, misfit_at_anchors
src = [("legacy", "Integrated DT", fs.ORANGE, "o"), ("wlt", "OpendTect TD model", fs.BLUE, "s"),
("dt_model", "DT model", fs.AQUA, "^")]
fig, axes = plt.subplots(1, len(F3_WELLS), figsize=(WIDTH, 2.9), sharey=True, sharex=True)
for ax, name in zip(axes, F3_WELLS):
w = load_well(name)
cs = w.checkshot
tdrs = {"legacy": legacy_sonic_tdr(w.md, w.curve("DT")),
"wlt": TDR.from_pairs(load_td_source(name, "wlt"), drop_flat=True),
"dt_model": TDR.from_pairs(load_td_source(name, "dt_model"))}
ax.axhspan(600, 1100, color=fs.GRID, alpha=0.55, lw=0, zorder=0)
ax.axvline(0, color=fs.AXIS, lw=0.8, zorder=1)
for key, lab, col, mk in src:
ax.plot(misfit_at_anchors(tdrs[key], cs.md, cs.twt_ms), cs.twt_ms, marker=mk, ms=3, lw=1.1, color=col,
label=lab, zorder=3)
ax.set_title(name, loc="center", fontsize=8, color=fs.INK)
ax.set_xlabel("offset from marker (ms)")
axes[0].set_ylabel("marker TWT (ms)")
axes[0].set_ylim(1300, 400)
fig.legend(*axes[0].get_legend_handles_labels(), loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.06))
fig.tight_layout(rect=(0, 0.06, 1, 1), w_pad=0.6)
save(fig, "td_drift")
# ---------------------------------------------------------------- Fig. H1 (Section 4)
def h1() -> None:
s11, s12, s13 = load_script("11_run_d2.py"), load_script("12_h1_blur.py"), load_script("13_summarize_p2.py")
P = s11.load_protocol(check=True)
h = s13.h1_summary(P, s12)
f, tab = h["f"], h["table"]
fig, (ax, bx) = plt.subplots(1, 2, figsize=(WIDTH, 2.6), gridspec_kw={"width_ratios": [1.55, 1]})
sig = [s for s in sorted(h["use"]) if s > 0]
for s, col in zip(sig, RAMP4):
th, H, u = np.array(h["theory"][s]), np.array(h["H"][s]), h["use"][s]
ax.plot(f, th, color=col, lw=0.9, ls="--")
ax.plot(f[u], H[u], color=col, lw=1.5, marker="o", ms=2.2)
left = s == max(sig)
i = int(u.sum()) // 2 if left else -1
ax.annotate(rf"$\sigma = {s:g}$ ms", (f[u][i], H[u][i]), xytext=(7, 4) if left else (4, 0), textcoords="offset points",
va="center", ha="left", fontsize=7, color=fs.INK2, zorder=4,
bbox=dict(fc=WHITE, ec="none", pad=0.6, alpha=0.9))
ax.axvspan(0, 6, color=fs.GRID, alpha=0.7, lw=0)
ax.set(xlim=(0, 60), ylim=(-0.1, 1.15), xlabel="frequency (Hz)", ylabel="transfer function")
ax.legend(handles=[Line2D([], [], color=fs.INK2, lw=1.5, marker="o", ms=2.2, label=r"estimated $\hat H_\sigma(f)$"),
Line2D([], [], color=fs.INK2, lw=0.9, ls="--", label=r"$e^{-2\pi^2\sigma^2 f^2}$")],
loc="upper right")
panel(ax, "a")
s = tab.index[tab.index > 0]
bx.axhspan(0.5, 2.0, color=fs.GRID, alpha=0.7, lw=0)
bx.axhline(1.0, color=fs.AXIS, lw=0.9)
bx.vlines(s, tab.loc[s, "r_lo"], tab.loc[s, "r_hi"], color=fs.BLUE, lw=1.4)
bx.plot(s, tab.loc[s, "r"], "o", color=fs.BLUE, ms=4.5)
for x, r, n in zip(s, tab.loc[s, "r"], tab.loc[s, "n_freq"]):
bx.annotate(f"{r:.3f}\n({n} freq.)", (x, r), xytext=(0, 7), textcoords="offset points", ha="center",
va="bottom", fontsize=6.5, 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.5, 1, 2], ["0.5", "1", "2"])
bx.minorticks_off()
bx.set(xlim=(3, 45), ylim=(0.4, 2.5), xlabel=r"$\sigma$ (ms)", ylabel=r"$r(\sigma)$")
panel(bx, "b")
fig.tight_layout(w_pad=1.5)
save(fig, "p2_h1")
# ---------------------------------------------------------------- Fig. Experiment 1 (Section 6.1)
def p2_phase() -> None:
cells = pd.read_csv(outputs_dir() / "p2" / "summary" / "main" / "cells.csv")
cs, Ns = sorted(cells.c.unique()), sorted(cells.n_train.unique())
ix = cells.set_index(["c", "n_train"])
fig, axes = plt.subplots(1, 2, figsize=(WIDTH, 0.75 + 0.62 * len(cs)), layout="constrained")
panels = [("ratio", fs.diverging_norm(0.8, 1.0, 1.2), fs.DIVERGING, "{:.3f}", "{:.2f}", [0.90, 1.0], "band RMSE ratio"),
("dpcc", fs.diverging_norm(-0.1, 0.0, 0.1), fs.DIVERGING.reversed(), "{:+.3f}", "{:+.2f}", [0.0, 0.05],
"band PCC difference")]
for ax, (k, norm, cmap, fmt, fci, ticks, clabel), letter in zip(axes, panels, "ab"):
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):
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=7.5, color=col)
ax.text(j, i - 0.12, f"[{fci.format(r[k + '_lo'])}, {fci.format(r[k + '_hi'])}]", ha="center",
va="center", fontsize=6, color=col)
if k == "ratio":
ax.text(j, i - 0.36, f"{r.best}, {'pass' if r.cell_pass else 'fail'}", ha="center", va="center",
fontsize=5.5, color=col)
ax.set_xticks(range(len(Ns)), [str(n) for n in Ns])
ax.set_yticks(range(len(cs)), [f"{c:g}" for c in cs])
ax.set(xlabel=r"training wells $N$", ylabel=r"drift factor $c$")
ax.grid(False)
for sp in ax.spines.values():
sp.set_visible(False)
ax.tick_params(length=0)
if 1.0 in cs:
ax.add_patch(Rectangle((-0.5, cs.index(1.0) - 0.5), len(Ns), 1, fill=False, ec=fs.INK, lw=1.2))
cb = fig.colorbar(im, ax=ax, shrink=0.9, extend="both", pad=0.02)
for t in ticks:
cb.ax.axhline(t, color=fs.INK, lw=0.9)
cb.set_label(clabel, color=fs.INK2)
cb.outline.set_visible(False)
panel(ax, letter)
save(fig, "p2_phase")
# ---------------------------------------------------------------- Fig. H2b (Section 6.3)
def h2b() -> None:
d = pd.read_csv(outputs_dir() / "p2r" / "summary" / "h2b.csv")
shapes = {0.0: "o", 1.0: "s", 2.0: "^"}
cols = {16: fs.BLUE, 4: fs.ORANGE}
fig, (ax, bx) = plt.subplots(1, 2, figsize=(WIDTH, 2.8))
for (N, c), g in d.groupby(["n_train", "c"]):
kw = dict(marker=shapes[c], s=26, zorder=3)
kw |= dict(color=cols[N], lw=0) if N == 16 else dict(facecolor="none", edgecolor=cols[N], lw=1.0)
ax.errorbar(g.sigma_post_ms, g.ratio, yerr=[g.ratio - g.ratio_lo, g.ratio_hi - g.ratio], fmt="none",
ecolor=cols[N], elinewidth=0.7, alpha=0.6, zorder=2)
ax.scatter(g.sigma_post_ms, g.ratio, **kw)
bx.scatter(g["bound_1/B"], g.ratio, **kw)
ax.axvline(1.5, color=fs.INK2, lw=0.8, ls="--")
ax.text(1.55, 0.62, "1.5 ms", fontsize=7, color=fs.INK2)
ax.axhline(1.0, color=fs.AXIS, lw=0.9)
ax.set_xscale("log")
ax.set_xticks([0.3, 0.5, 1, 2, 5, 10], ["0.3", "0.5", "1", "2", "5", "10"])
ax.minorticks_off()
ax.set(xlabel=r"posterior width $\sigma_{\mathrm{post}}$ (ms)", ylabel="band RMSE ratio, M2-Sa / B3d-Sa",
ylim=(0.6, 1.05))
panel(ax, "a")
lo, hi = 0.6, 1.05
bx.plot([lo, hi], [lo, hi], color=fs.AXIS, lw=0.9)
bx.text(0.74, 0.695, "ratio = bound", rotation=45, rotation_mode="anchor", fontsize=7, color=fs.INK2)
bx.set(xlim=(lo, hi), ylim=(lo, hi), aspect="equal", xlabel=r"population bound $1/B(\sigma_{\mathrm{post}})$",
ylabel="band RMSE ratio, M2-Sa / B3d-Sa")
panel(bx, "b")
handles = [Line2D([], [], ls="", marker="o", color=fs.BLUE, mew=0, label=r"$N = 16$"),
Line2D([], [], ls="", marker="o", mfc="none", mec=fs.ORANGE, label=r"$N = 4$")]
handles += [Line2D([], [], ls="", marker=m, color=fs.INK2, mfc="none", label=rf"$c = {c:g}$")
for c, m in shapes.items()]
fig.legend(handles=handles, loc="lower center", ncol=5, bbox_to_anchor=(0.5, -0.04))
fig.tight_layout(rect=(0, 0.06, 1, 1), w_pad=2.0)
save(fig, "p2r_h2b")
# ---------------------------------------------------------------- Fig. Experiment 2 overview (Section 6.3)
def p2r_grid() -> None:
d = pd.read_csv(outputs_dir() / "p2r" / "summary" / "band_rmse.csv")
d = d[d.setting.isin(REGIMES)]
cs = sorted(d.c.unique())
cols = [(r, c) for r in REGIMES for c in cs]
vals = []
for N in (4, 16):
t = d[d.n_train == N].set_index(["setting", "c"])
vals.append(np.array([[t.loc[(r, c), m] / t.loc[(r, c), "Oracle"] for r, c in cols] for m, _ in METHODS]))
norm = Normalize(1.0, 2.0) # R10tb at c = 2 reaches 3.2; clipped so that 1.0-1.6 stays readable
fig, axes = plt.subplots(2, 1, figsize=(WIDTH, 4.3), layout="constrained")
for ax, V, N, letter in zip(axes, vals, (4, 16), "ab"):
im = ax.imshow(V, cmap=SEQ_BLUE, norm=norm, aspect="auto")
for i in range(V.shape[0]):
for j in range(V.shape[1]):
ax.text(j, i, f"{V[i, j]:.2f}", ha="center", va="center", fontsize=6,
color=text_on(SEQ_BLUE(norm(V[i, j]))))
ax.set_yticks(range(len(METHODS)), [lab for _, lab in METHODS])
ax.set_xticks(range(len(cols)), [f"{c:g}" for _, c in cols])
sec = ax.secondary_xaxis("top")
sec.set_xticks([len(cs) * k + (len(cs) - 1) / 2 for k in range(len(REGIMES))], REGIMES)
sec.tick_params(length=0, labelsize=7.5, labelcolor=fs.INK)
sec.spines["top"].set_visible(False)
for k in range(1, len(REGIMES)):
ax.axvline(len(cs) * k - 0.5, color=WHITE, lw=2.5)
ax.grid(False)
for sp in ax.spines.values():
sp.set_visible(False)
ax.tick_params(length=0)
ax.set_xlabel(r"drift factor $c$")
ax.set_title(f"({letter}) $N = {N}$", loc="left", fontsize=8.5, color=fs.INK, pad=14)
cb = fig.colorbar(im, ax=axes, shrink=0.8, pad=0.01, extend="max")
cb.set_label("band RMSE / Oracle", color=fs.INK2)
cb.outline.set_visible(False)
save(fig, "p2r_grid")
# ---------------------------------------------------------------- Fig. F3 volume (Section 6.4)
def f3_volume(well: str = "F03-4") -> None:
import json
root = outputs_dir() / "p3" / "volume"
meta = json.loads((root / "metadata.json").read_text(encoding="utf-8"))
il, xl, t = (np.asarray(meta[k], float) for k in ("ilines", "xlines", "times_ms"))
with np.load(outputs_dir() / "f3_wells.npz") as z:
w_il, w_xl = int(z[f"{well}/il"]), int(z[f"{well}/xl"])
i = int(np.flatnonzero(il == w_il)[0])
fields = [100 * np.asarray(np.load(root / f"{k}.npy", mmap_mode="r")[i]) for k in ("mean", "sigma")] # (xline, t), p.u.
dt = t[1] - t[0]
extent = [xl[0] - 0.5, xl[-1] + 0.5, t[-1] + dt / 2, t[0] - dt / 2]
fig, axes = plt.subplots(1, 2, figsize=(WIDTH, 2.5), sharey=True, layout="constrained")
specs = [("viridis", np.nanpercentile(fields[0], [1, 99]), "both", "mean (p.u.)"),
(SEQ_BLUE, (0.0, np.nanpercentile(fields[1], 99)), "max", "standard deviation (p.u.)")]
for ax, v, (cmap, (lo, hi), ext, lab), letter in zip(axes, fields, specs, "ab"):
cm = (mpl.colormaps[cmap] if isinstance(cmap, str) else cmap).with_extremes(bad=WHITE)
im = ax.imshow(v.T, cmap=cm, vmin=lo, vmax=hi, aspect="auto", interpolation="nearest", extent=extent)
ax.axvline(w_xl, color=fs.INK, lw=0.8, ls=(0, (4, 2)))
ax.text(w_xl, t[0] - dt, well, ha="center", va="bottom", fontsize=7, color=fs.INK)
ax.grid(False)
ax.set_xlabel(f"crossline (inline {w_il})")
panel(ax, letter)
cb = fig.colorbar(im, ax=ax, pad=0.01, extend=ext)
cb.set_label(lab, color=fs.INK2)
cb.outline.set_visible(False)
axes[0].set_ylabel("TWT (ms)")
save(fig, "f3_volume")
FIGURES = {"td_drift": td_drift, "h1": h1, "p2_phase": p2_phase, "h2b": h2b, "p2r_grid": p2r_grid,
"f3_volume": f3_volume}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--only", default="", help="comma-separated subset of " + ",".join(FIGURES))
args = ap.parse_args()
style()
for k in (args.only.split(",") if args.only else FIGURES):
FIGURES[k]()
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,282 @@
"""Build the P4 Volve well dataset (6 deviated wells) in the seismic time domain.
python scripts/23_build_volve_wells.py [--config configs/d3_volve.yaml]
Outputs (outputs/volve/):
volve_wells.npz flat keys "<well>/<item>", no allow_pickle needed. Time series lie on `ext_window_ms`;
`main_mask` marks the main window.
Public for a held-out well (built without its logs or picks):
times_ms, main_mask, kb_msl, survey/{md,inc,azi,tvd,x,y}
blind/<key>/{seismic_patch,md,il,xl,beyond}
input along the well path placed in time by the mean TVDSS–TWT relation of the calibrated
TDRs of the wells in <key> (`blind_key`), for every non-empty set of other wells
Private (the well's own logs and picks):
il, xl, x, y nearest bin and position at the middle of the label interval (display only)
log/md, log/<curve> depth-domain logs over the valid DT range (DT µs/m, RHOB kg/m³)
anchors_{md,tvd,twt_ms,surface,in_dt}
tdr/<name>/{md,twt_ms}, support/<name> TDR and the MD range [lo, hi] over which it places logs
<name>/<curve> log in time under TDR <name>, NaN outside its support
reference/{seismic_patch,md,tvd,il,xl,beyond}
input along the path placed by the calibrated TDR: training wells, and the
calibration-assisted setting of plan §5.2 for a test well
volve_wells_summary.json configuration and per-well QC. No statistic of the label values is computed.
"""
from __future__ import annotations
import argparse
import itertools
import json
import numpy as np
import yaml
from ml_porosity.data.deviated import (anchor_tdr, calibrated_vertical_tdr, composite_patch, path_at_times,
tdr_from_tvdss, tvdss_td_model, vertical_sonic_tdr)
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.seismic_io import SeismicCube
from ml_porosity.data.tdr import TDR, calibrate_to_anchors, sonic_tdr
from ml_porosity.data.volve_io import read_checkshot, read_horizon, read_well_picks
from ml_porosity.data.volve_wells import VolveWell, blind_key, blind_training_wells, load_volve_well
from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root
def r_(v, nd: int = 2):
"""Rounded float or list of floats for the JSON summary."""
a = np.round(np.asarray(v, dtype=float), nd)
return a.tolist() if a.ndim else float(a)
def rel_rms(a: np.ndarray, b: np.ndarray) -> float:
"""RMS(a − b) / RMS(b)."""
return float(np.sqrt(np.mean((a - b) ** 2) / np.mean(b ** 2)))
def build_tdrs(w: VolveWell, cfg: dict) -> tuple[dict[str, TDR], dict[str, tuple[float, float]]]:
"""TDRs of `w` and the MD range over which each places logs (no extrapolation of a TDR carries a log)."""
p4 = cfg["p4"]
lo, hi = w.valid_range("DT")
seg = w.logs.loc[lo:hi]
md, dt = seg.index.to_numpy(), seg["DT"].to_numpy()
za, ta = w.anchors.md.to_numpy(), w.anchors.twt_ms.to_numpy()
k = np.flatnonzero((za >= lo) & (za <= hi))[0]
tdrs, support = {}, {}
for name in p4["tdrs"]:
if name == "calibrated":
tdrs[name], support[name] = calibrated_vertical_tdr(w.traj, md, dt, za, ta, p4["edge_m"]), (lo, hi)
elif name == "sonic":
tdrs[name], support[name] = vertical_sonic_tdr(md, w.traj.at(md)[0], dt, za[k], ta[k]), (lo, hi)
elif name == "anchors":
tdrs[name], support[name] = anchor_tdr(w.traj, za, ta), (za[0], za[-1])
else:
raise ValueError(f"unsupported TDR: {name}")
for kind in p4["wells"][w.name].get("checkshots", []):
cs = read_checkshot(volve_root() / cfg["well_logs_dir"] / cfg["checkshots"][w.pick_name][kind])
tdrs[kind] = TDR.from_pairs(cs[["md", "twt_ms"]].to_numpy(), kind, drop_flat=True)
support[kind] = (float(cs.md.min()), float(cs.md.max()))
return tdrs, support
def survey_qc(w: VolveWell, picks, support: tuple[float, float]) -> dict:
tr, head = w.traj, w.header
r = tr.recompute()
s = np.linspace(*support, 200)
inc = np.interp(s, tr.md, tr.inc)
p = picks[(picks.well == w.pick_name) & picks.md.between(tr.md[0], tr.md[-1]) & picks.x.notna()]
tvd, x, y = tr.at(p.md)
return {"stations": len(tr.md), "md": r_([tr.md[0], tr.md[-1]]), "bh_tvd": r_(tr.tvd[-1]),
"header_bh_md_tvd": [head.get("Bottom Hole MD"), head.get("Bottom Hole TVD")],
"drilled_from": head.get("Drilled From"), "kick_off": head.get("Kick Off Depth"),
"recompute_max_dtvd_m": r_(np.abs(r[:, 2] - tr.tvd).max(), 3),
"recompute_max_dxy_m": r_(np.hypot(r[:, 0] - tr.x, r[:, 1] - tr.y).max(), 3),
"min_tvd_step_m": r_(np.diff(tr.tvd).min(), 3), "max_inc_deg": r_(tr.inc.max(), 1),
"inc_over_label_deg": r_([inc.min(), inc.max()], 1), "max_dls_deg_30m": r_(tr.dls().max()),
"picks_vs_survey": {"n": len(p), "max_dtvd_m": r_(np.abs(p.tvd - tvd).max(), 3),
"max_dxy_m": r_(np.hypot(p.x - x, p.y - y).max(), 3)}}
def anchor_qc(w: VolveWell, tdrs: dict[str, TDR], support: tuple[float, float]) -> dict:
"""Drift and stretch of the vertical sonic at the anchors, against the MD-integrated sonic of the F3 code."""
lo, hi = w.valid_range("DT")
seg = w.logs.loc[lo:hi]
A = w.anchors
za, ta = A.md.to_numpy(), A.twt_ms.to_numpy()
inside = (za >= lo) & (za <= hi)
zi, ti = za[inside], ta[inside]
cal, son = tdrs["calibrated"], tdrs["sonic"]
md_son = sonic_tdr(seg.index.to_numpy(), seg["DT"].to_numpy(), zi[0], ti[0])
md_cal = calibrate_to_anchors(md_son, zi, ti)
s = seg.index.to_numpy()[(seg.index >= support[0]) & (seg.index <= support[1])]
tvd_a = w.traj.at(za)[0]
fp = w.excluded[w.excluded.qlf.eq("FP") & w.excluded.md.between(lo, hi)]
return {"kept": [{"surface": r.surface, "qlf": r.qlf, "md": r.md, "twt_ms": r.twt_ms, "in_dt": bool(i)}
for r, i in zip(A.itertuples(), inside)],
"excluded": [{"surface": r.surface, "qlf": r.qlf, "md": r.md, "twt_ms": r.twt_ms, "reason": r.reason}
for r in w.excluded.itertuples()],
"calibrated_max_abs_misfit_ms": r_(np.abs(cal.time_at(za) - ta).max(), 4),
"sonic_drift_ms": r_(son.time_at(zi) - ti),
"stretch_vertical": r_(np.diff(ti) / np.diff(son.time_at(zi)), 3),
"stretch_md_sonic": r_(np.diff(ti) / np.diff(md_son.time_at(zi)), 3),
"vint_between_anchors_m_s": r_(2000.0 * np.diff(tvd_a) / np.diff(ta), 0),
"fp_misfit_ms": {r.surface: r_(cal.time_at(r.md) - r.twt_ms) for r in fp.itertuples()},
"md_minus_vertical_calibrated_ms": r_([np.min(md_cal.time_at(s) - cal.time_at(s)),
np.max(md_cal.time_at(s) - cal.time_at(s))]),
"label_below_last_anchor_m": r_(max(support[1] - za[-1], 0.0), 1),
"anchors_above_dt": A.surface[za < lo].tolist()}
def checkshot_qc(w: VolveWell, cfg: dict, cal: TDR, support: tuple[float, float]) -> dict:
out = {}
for kind, rel in cfg["checkshots"].get(w.pick_name, {}).items():
cs = read_checkshot(volve_root() / cfg["well_logs_dir"] / rel)
cs = cs[cs.md.between(w.traj.md[0], w.traj.md[-1])]
d = cal.time_at(cs.md) - cs.twt_ms.to_numpy()
lab = cs.md.between(*support).to_numpy()
upper = cs.twt_ms.between(2000, 2300).to_numpy()
za, ta = w.anchors.md.to_numpy(), w.anchors.twt_ms.to_numpy()
ok = (za >= cs.md.min()) & (za <= cs.md.max())
out[kind] = {"n": len(cs), "md": r_([cs.md.min(), cs.md.max()]),
"max_tvdss_vs_survey_m": r_(np.abs(cs.tvdss - w.traj.tvdss(cs.md)).max()),
"calibrated_minus_cs_label_ms": r_([d[lab].min(), d[lab].max()]) if lab.any() else None,
"calibrated_minus_cs_2000_2300ms": r_([d[upper].min(), d[upper].max()]) if upper.any() else None,
"picks_minus_cs_ms": r_(ta[ok] - np.interp(za[ok], cs.md, cs.twt_ms))}
return out
def path_qc(path: dict, il: np.ndarray, xl: np.ndarray, sel: np.ndarray, dt: float) -> dict:
"""Lateral extent and drift rate of the path over the samples `sel` (steps across gaps in `sel` excluded)."""
step = np.hypot(np.diff(il), np.diff(xl))[sel[:-1] & sel[1:]]
return {"extent_bins": r_(np.hypot(np.ptp(il[sel]), np.ptp(xl[sel]))),
"max_bins_per_10ms": r_(step.max() * 10.0 / dt, 3) if step.size else 0.0,
"beyond_td_frac": r_(path["beyond"][sel].mean(), 3)}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--config", default=str(REPO_ROOT / "configs" / "d3_volve.yaml"))
cfg = yaml.safe_load(open(ap.parse_args().config))
p4, root = cfg["p4"], volve_root()
names, label, rad = list(p4["wells"]), p4["label"], p4["patch_radius"]
centre = (2 * rad + 1) ** 2 // 2
picks = read_well_picks(root / cfg["picks"])
geom = read_horizon(root / cfg["horizons_twt"] / cfg["grid_horizon"]).geometry()
wells = {n: load_volve_well(n, cfg, picks) for n in names}
built = {n: build_tdrs(w, cfg) for n, w in wells.items()}
cal = {n: built[n][0]["calibrated"] for n in names}
z = np.arange(np.floor(min(w.traj.tvdss(w.traj.md[0]) for w in wells.values())),
np.ceil(max(w.traj.tvdss(w.traj.md[-1]) for w in wells.values())) + 1.0)
arrays: dict[str, np.ndarray] = {}
summary = {"config": {k: cfg[k] for k in ("cube", "picks", "grid_horizon", "anchor_exclude_surfaces")} | {"p4": p4},
"grid": {"x_coef": geom.x_coef, "y_coef": geom.y_coef, "bin_m": geom.bin_spacing()}, "wells": {}}
cache: dict = {}
with SeismicCube(root / cfg["cube"]) as cube:
win = cube.window(*p4["ext_window_ms"])
t = cube.times_ms[win]
main = (t >= p4["main_window_ms"][0]) & (t <= p4["main_window_ms"][1])
summary["samples"] = {"ext": int(t.size), "main": int(main.sum()), "dt_ms": cube.dt_ms}
for n, w in wells.items():
tdrs, support = built[n]
lab = w.label_support(label)
tr = w.traj
_, x0, y0 = tr.at(0.5 * (lab[0] + lab[1]))
il0, xl0 = geom.nearest_bin(float(x0), float(y0))
lo, hi = w.valid_range("DT")
seg = w.logs.loc[lo:hi]
A = w.anchors
a = {"times_ms": t, "main_mask": main, "kb_msl": np.float64(tr.kb_msl),
"il": np.int32(il0), "xl": np.int32(xl0), "x": np.float64(x0), "y": np.float64(y0),
"log/md": seg.index.to_numpy(dtype=float),
"anchors_md": A.md.to_numpy(), "anchors_tvd": A.tvd.to_numpy(), "anchors_twt_ms": A.twt_ms.to_numpy(),
"anchors_surface": A.surface.to_numpy(dtype=str), "anchors_in_dt": A.md.between(lo, hi).to_numpy()}
a |= {f"survey/{k}": getattr(tr, k) for k in ("md", "inc", "azi", "tvd", "x", "y")}
a |= {f"log/{c}": seg[c].to_numpy(dtype=float) for c in p4["curves"]}
labels = {}
for name, tdr in tdrs.items():
a[f"tdr/{name}/md"], a[f"tdr/{name}/twt_ms"] = tdr.md, tdr.twt_ms
a[f"support/{name}"] = np.asarray(support[name], dtype=float)
part = w.logs.loc[support[name][0]:support[name][1]]
for c in p4["curves"]:
a[f"{name}/{c}"] = log_to_time(part.index.to_numpy(), part[c].to_numpy(), tdr, t, **p4["resample"])
ok = np.isfinite(a[f"{name}/{label}"])
labels[name] = {"n_main": int(ok[main].sum()), "n_outside_main": int(ok[~main].sum()),
"t_ms": r_([t[ok].min(), t[ok].max()], 0) if ok.any() else None}
# input along the calibrated path (reference) and along the blind paths
ref = path_at_times(tr, cal[n], t)
il, xl = geom.xy_to_bin(ref["x"], ref["y"])
patch = composite_patch(cube, il, xl, t, rad, p4["patch_method"], cache)
a |= {"reference/seismic_patch": patch, "reference/md": ref["md"], "reference/tvd": ref["tvd"],
"reference/il": il, "reference/xl": xl, "reference/beyond": ref["beyond"]}
nearest = composite_patch(cube, il, xl, t, rad, "nearest", cache)
vertical = cube.patch(il0, xl0, rad)[:, win]
sel_lab = np.isfinite(a[f"calibrated/{label}"])
others = [v for v in names if v != n]
for k in range(1, len(others) + 1):
for S in itertools.combinations(others, k):
tb = tdr_from_tvdss(tr, z, tvdss_td_model([wells[v].traj for v in S], [cal[v] for v in S], z))
pb = path_at_times(tr, tb, t)
ib, jb = geom.xy_to_bin(pb["x"], pb["y"])
key = f"blind/{blind_key(S)}"
a |= {f"{key}/seismic_patch": composite_patch(cube, ib, jb, t, rad, p4["patch_method"], cache),
f"{key}/md": pb["md"], f"{key}/il": ib, f"{key}/xl": jb, f"{key}/beyond": pb["beyond"]}
blind = {}
za, ta = A.md.to_numpy(), A.twt_ms.to_numpy()
s = seg.index.to_numpy()[(seg.index >= lab[0]) & (seg.index <= lab[1])]
for scheme in p4["blind_schemes"]:
S = blind_training_wells(n, scheme, p4)
key = f"blind/{blind_key(S)}"
tb = tdr_from_tvdss(tr, z, tvdss_td_model([wells[v].traj for v in S], [cal[v] for v in S], z))
pb = path_at_times(tr, tb, t)
off = np.hypot(pb["x"] - ref["x"], pb["y"] - ref["y"])[sel_lab]
blind[scheme] = {"training_wells": list(S),
"td_misfit_at_anchors_ms": r_([np.mean(tb.time_at(za) - ta),
np.abs(tb.time_at(za) - ta).max()]),
"minus_calibrated_over_label_ms": r_([np.min(tb.time_at(s) - cal[n].time_at(s)),
np.max(tb.time_at(s) - cal[n].time_at(s))]),
"max_offset_from_reference_m": r_(off.max(), 1),
"rel_rms_vs_reference_main": r_(rel_rms(a[f"{key}/seismic_patch"][centre][main],
patch[centre][main]), 3)}
dt_lab = w.logs.loc[lab[0]:lab[1], "DT"]
ok_dt = dt_lab.notna().to_numpy()
# beyond this range the calibrated TDR (and so the reference path) is an extension at constant velocity
constrained = [min(lo, za[0]), max(hi, za[-1])]
info = {"survey": survey_qc(w, picks, lab),
"logs": w.qc | {"dt_md": r_([lo, hi], 1), "label_md": r_(lab, 1),
"label_twt_ms": r_(cal[n].time_at(np.asarray(lab)), 1),
"calibrated_constrained_twt_ms": r_(cal[n].time_at(np.asarray(constrained)), 1),
"dt_nan_frac_in_label": r_(1 - ok_dt.mean(), 3),
"dt_longest_gap_in_label_m": r_(np.diff(dt_lab.index.to_numpy()[ok_dt]).max(), 2)},
"anchors": anchor_qc(w, tdrs, lab),
"checkshots": checkshot_qc(w, cfg, cal[n], lab),
"label_samples": labels,
"bin": [il0, xl0], "xy": r_([x0, y0], 1),
"path": {"label": path_qc(ref, il, xl, sel_lab, cube.dt_ms),
"main": path_qc(ref, il, xl, main, cube.dt_ms),
"ext": path_qc(ref, il, xl, np.ones_like(main), cube.dt_ms)},
"seismic": {"rel_rms_bilinear_vs_nearest_main": r_(rel_rms(nearest[centre][main],
patch[centre][main]), 3),
"rel_rms_vertical_vs_composite_main": r_(rel_rms(vertical[centre][main],
patch[centre][main]), 3),
"rel_rms_vertical_vs_composite_label": r_(rel_rms(vertical[centre][sel_lab],
patch[centre][sel_lab]), 3)},
"blind": blind}
summary["wells"][n] = info
arrays |= {f"{n}/{k}": v for k, v in a.items()}
q = info["anchors"]
print(f"{n}: {len(A)} anchors ({sum(r['in_dt'] for r in q['kept'])} in DT), label {lab[0]:.1f}–{lab[1]:.1f} m"
f" = {labels['calibrated']['n_main']} samples, {q['label_below_last_anchor_m']:.0f} m below last"
f" anchor; path {info['path']['label']['extent_bins']:.1f} bins over the label;"
f" blind lowo/slot misfit {blind['lowo']['td_misfit_at_anchors_ms'][1]:.1f}/"
f"{blind['slot']['td_misfit_at_anchors_ms'][1]:.1f} ms max")
out = outputs_dir() / "volve"
out.mkdir(parents=True, exist_ok=True)
np.savez_compressed(out / "volve_wells.npz", **arrays)
(out / "volve_wells_summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False, default=float))
print(f"-> {out / 'volve_wells.npz'} ({len(arrays)} arrays)")
if __name__ == "__main__":
main()

69
scripts/24_run_volve.py Normal file
View File

@@ -0,0 +1,69 @@
"""P4 Volve: lock -> register -> train -> summarize (configs/protocol_volve.yaml).
Full run on the run machine: python scripts/24_run_volve.py all --device cuda:0 --workers 4
Then the σ_a arms: python scripts/24_run_volve.py all --arms sensitivity, then summarize --arms all
Smoke (CPU, reduced settings, outputs/p4/smoke): register/train only until the protocol is locked; never a result.
"""
from __future__ import annotations
import argparse
import os
import traceback
os.environ.setdefault("OMP_NUM_THREADS", "2")
os.environ.setdefault("MKL_NUM_THREADS", "2")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "2")
os.environ.setdefault("NUMBA_NUM_THREADS", "2")
os.environ.setdefault("PYTHONHASHSEED", "0")
os.environ.setdefault("PYTHONUTF8", "1")
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
def main() -> None:
from ml_porosity.paths import outputs_dir
from ml_porosity.volve.protocol import freeze, load_protocol
from ml_porosity.volve.runner import benchmark, progress, run
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("stage", choices=["status", "benchmark", "lock", "register", "train", "summarize", "all"])
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--arms", choices=["primary", "sensitivity", "all"], default="primary")
ap.add_argument("--smoke", action="store_true")
ap.add_argument("--benchmark-steps", type=int, default=100)
args = ap.parse_args()
if args.workers < 1:
ap.error("--workers must be positive")
p = load_protocol()
root = outputs_dir() / "p4" / ("smoke" if args.smoke else "")
if os.name == "nt":
import ctypes
# Prevent automatic system sleep only while this process is alive.
ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
try:
if args.stage == "status":
path = root / "progress.json"
print(path.read_text(encoding="utf-8") if path.exists() else "P4 has not started.")
elif args.stage == "benchmark":
print(benchmark(p, args.device, args.benchmark_steps))
elif args.stage == "lock":
print(freeze())
else:
stages = ["register", "train", "summarize"] if args.stage == "all" else [args.stage]
if args.smoke and args.stage == "all":
stages = ["register", "train"] # summarize needs the lock, see runner.run
for stage in stages:
run(stage, p, args.device, args.workers, args.smoke, args.arms)
except Exception as exc:
if args.stage not in ("status", "lock", "benchmark"):
progress(root, status=f"error in {args.stage}; completed jobs can resume", error=str(exc))
traceback.print_exc()
raise SystemExit(1)
finally:
if os.name == "nt":
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
if __name__ == "__main__":
main()

62
scripts/25_p4_posthoc.py Normal file
View File

@@ -0,0 +1,62 @@
"""P4 Volve post hoc description (not part of protocol_volve; computed after G-D, for scale only).
Reads the registered combined-ensemble predictions (outputs/p4/summary/predictions.npz) and the calibrated reference,
and writes outputs/p4/posthoc/:
wells.csv per scheme and outer well: label statistics, a constant prediction at the pooled label mean of the outer
training wells (no seismic), and, per method (σ_a = 7 ms), RMSE split into mean bias and the SD of the error.
macro.csv the same, unweighted mean over wells per scheme.
Nothing here chooses a method, budget or setting, and no G-D number is changed.
"""
from __future__ import annotations
import json
import numpy as np
import pandas as pd
from ml_porosity.paths import outputs_dir
from ml_porosity.volve.data import VolveData, load_arrays
from ml_porosity.volve.folds import outer_folds
from ml_porosity.volve.protocol import load_protocol, source_config
def main() -> None:
p = load_protocol()
ref, sa = p["data"]["primary_reference"], p["registration"]["sigma_a_ms"]
full = VolveData(p, arrays=load_arrays())
summary = outputs_dir() / "p4" / "summary"
index = json.loads((summary / "prediction_index.json").read_text(encoding="utf-8"))
with np.load(summary / "predictions.npz") as z:
mu = {i: 100 * z[f"{i}/mu"] for i, e in enumerate(index)
if str(e["seed"]) == "ensemble" and e["sigma_a_ms"] == sa}
rows = []
for scheme in p["split"]["schemes"]:
for test, train in outer_folds(p["data"]["wells"], scheme, source_config(p)["p4"]):
y = 100 * full.y(test, ref)
ok = np.isfinite(y)
pooled = np.concatenate([100 * full.y(w, ref) for w in train])
const = float(np.nanmean(pooled))
row = dict(scheme=scheme, well=test, n=int(ok.sum()), label_mean=float(y[ok].mean()),
label_sd=float(y[ok].std()), train_mean=const,
const_rmse=float(np.sqrt(np.mean((const - y[ok]) ** 2))), const_bias=const - float(y[ok].mean()))
for i, e in enumerate(index):
if i in mu and e["scheme"] == scheme and e["test_well"] == test:
err = mu[i][ok] - y[ok]
m = e["method"]
row |= {f"{m}/rmse": float(np.sqrt(np.mean(err ** 2))), f"{m}/bias": float(err.mean()),
f"{m}/err_sd": float(err.std()), f"{m}/pred_sd": float(mu[i][ok].std())}
rows.append(row)
wells = pd.DataFrame(rows)
out = outputs_dir() / "p4" / "posthoc"
out.mkdir(parents=True, exist_ok=True)
wells.to_csv(out / "wells.csv", index=False, float_format="%.4f")
numeric = wells.drop(columns=["well"])
macro = numeric.groupby("scheme").mean()
abs_bias = wells.filter(like="bias").abs().groupby(wells.scheme).mean().add_prefix("abs_")
macro.join(abs_bias).to_csv(out / "macro.csv", float_format="%.4f")
print(macro.join(abs_bias).T.to_string(float_format="%.3f"))
if __name__ == "__main__":
main()

168
scripts/26_applicability.py Normal file
View File

@@ -0,0 +1,168 @@
"""Applicability conditions C1 and C2 (docs/research/applicability-teapot.md), retrospective on F3 and Volve.
Reads only frozen outputs (outputs/p2r, outputs/p3, outputs/p4); trains nothing and never reads an outer-test label:
labels are loaded through the data view of each outer fold's training wells (F3Data / VolveData with
training_wells=T_out), which raises on any held-out well.
C1 thresholds come from the D2 cells that confirmed H2a (c = 1, R10/R0/Rm5, N = 4/16, cell_pass): minimum over
those cells of the best competitor's mean band PCC and R².
python scripts/26_applicability.py # -> outputs/applicability/
"""
from __future__ import annotations
import json
import os
os.environ.setdefault("OMP_NUM_THREADS", "2")
os.environ.setdefault("MKL_NUM_THREADS", "2")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "2")
import numpy as np
import pandas as pd
import yaml
from ml_porosity.eval.metrics import band_metrics, point_metrics
from ml_porosity.paths import REPO_ROOT, outputs_dir
OUT = outputs_dir() / "applicability"
H2A_REGIMES = ("R10", "R0", "Rm5")
WIDE_MS = 1.5
def d2_thresholds() -> tuple[dict, pd.DataFrame]:
h2a = pd.read_csv(outputs_dir() / "p2r/summary/h2a.csv")
cells = h2a[(h2a.c == 1.0) & h2a.regime.isin(H2A_REGIMES) & h2a.n_train.isin([4, 16]) & h2a.cell_pass]
rows = []
for c in cells.itertuples():
r = pd.read_csv(outputs_dir() / f"p2r/train/{c.regime}/results.csv")
r = r[(r.c == c.c) & (r.n_train == c.n_train) & (r.method == c.best)]
rows.append(dict(regime=c.regime, c=c.c, n_train=c.n_train, best=c.best, band_pcc=r.band_pcc.mean(),
r2=r.r2.mean(), pcc=r.pcc.mean(), n_rows=len(r)))
t = pd.DataFrame(rows)
return dict(tau_band_pcc=float(t.band_pcc.min()), tau_r2=float(t.r2.min()), n_cells=len(t)), t
def summarize_pairs(rows: list[dict], keys: list[str]) -> pd.DataFrame:
df = pd.DataFrame(rows)
return df.groupby(keys)[["r2", "band_pcc", "ss_const", "rmse", "rmse_const"]].mean().reset_index()
def f3_c1() -> list[dict]:
from ml_porosity.f3.data import F3Data
from ml_porosity.f3.protocol import inner_folds
from ml_porosity.f3.runner import job_path, load_bundle
p = yaml.safe_load((REPO_ROOT / "configs/protocol_f3.yaml").read_text(encoding="utf-8"))
root = outputs_dir() / "p3"
label, sa, seeds = p["data"]["primary_label"], float(p["registration"]["sigma_a_ms"]), p["split"]["seeds"]
f_c = float(p["metrics"]["f_c_hz"])
gate = json.loads((root / "summary/gate_gc.json").read_text())
competitor = {w["well"]: w["competitor"] for w in gate["per_well"]}
sel = pd.read_csv(root / "summary/selection.csv")
rows = []
for u in p["data"]["wells"]:
outer_train = tuple(w for w in p["data"]["wells"] if w != u)
view = F3Data(p, training_wells=outer_train)
for method in (competitor[u], "M2-Sa"):
s = sel[(sel.test_well == u) & (sel.method == method) & (sel.label == label) & (sel.sigma_a_ms == sa)]
budget = {int(r.seed): int(r.budget) for r in s.itertuples()}
for v, t_in in inner_folds(p["data"]["wells"], u):
assert u not in t_in and v not in t_in
y = view.y(v, "calibrated", label)
y_tr = np.concatenate([view.y(w, "calibrated", label) for w in t_in])
mu = np.mean([(z := load_bundle(job_path(root, t_in, method, label, seed, sa)))
[f"{budget[seed]}/mu"][list(z["wells"]).index(v)] for seed in seeds], axis=0)
yp, mp, cst = 100 * y, 100 * mu, 100 * y_tr.mean()
m = point_metrics(yp, mp)
rmse_c = float(np.sqrt(np.mean((yp - cst) ** 2)))
rows.append(dict(dataset="F3", scheme="lowo", test_well=u, validation=v, method=method,
role="competitor" if method != "M2-Sa" else "M2-Sa", r2=m["r2"], rmse=m["rmse"],
band_pcc=band_metrics(yp, mp, f_c, view.dt)["band_pcc"], rmse_const=rmse_c,
ss_const=1 - m["rmse"] / rmse_c))
return rows
def volve_c1() -> list[dict]:
from ml_porosity.data.volve_wells import blind_key
from ml_porosity.volve.data import VolveData, load_arrays
from ml_porosity.volve.evaluation import desc_band
from ml_porosity.volve.folds import inner_folds, outer_folds, target_name
from ml_porosity.volve.protocol import load_protocol, source_config
from ml_porosity.volve.runner import job_path, load_bundle
p = load_protocol()
p4, root = source_config(p)["p4"], outputs_dir() / "p4"
label, ref, sa, seeds = p["data"]["label"], p["data"]["primary_reference"], float(p["registration"]["sigma_a_ms"]), p["split"]["seeds"]
m_cfg = p["metrics"]
gate = json.loads((root / "summary/gate_gd.json").read_text())
sel = pd.read_csv(root / "summary/selection.csv")
arrays = load_arrays()
rows = []
for scheme in p["split"]["schemes"]:
competitor = {w["well"]: w["competitor"] for w in gate["schemes"][scheme]["per_well"]}
for u, outer_train in outer_folds(p["data"]["wells"], scheme, p4):
view = VolveData(p, training_wells=outer_train, arrays=arrays)
for method in (competitor[u], "M2-Sa"):
s = sel[(sel.scheme == scheme) & (sel.test_well == u) & (sel.method == method) & (sel.sigma_a_ms == sa)]
budget = {int(r.seed): int(r.budget) for r in s.itertuples()}
for v, t_in in inner_folds(outer_train):
assert u not in t_in and v not in t_in
y = view.y(v, ref)
ok = np.isfinite(y)
y_tr = np.concatenate([view.y(w, ref) for w in t_in])
mus = []
for seed in seeds:
z = load_bundle(job_path(root, t_in, method, label, seed, sa))
mus.append(z[f"{budget[seed]}/mu"][list(z["targets"]).index(target_name(v, blind_key(t_in)))])
mu = np.mean(mus, axis=0)
yp, mp, cst = 100 * y, 100 * mu, 100 * np.nanmean(y_tr)
m = point_metrics(yp[ok], mp[ok])
rmse_c = float(np.sqrt(np.mean((yp[ok] - cst) ** 2)))
band = desc_band(yp, mp, m_cfg["f_c_hz"], view.dt, m_cfg["desc_band_min_samples"])
rows.append(dict(dataset="Volve", scheme=scheme, test_well=u, validation=v, method=method,
role="competitor" if method != "M2-Sa" else "M2-Sa", r2=m["r2"], rmse=m["rmse"],
band_pcc=band["band_pcc"], rmse_const=rmse_c, ss_const=1 - m["rmse"] / rmse_c))
return rows
def c2() -> list[dict]:
rows = []
for f in sorted((outputs_dir() / "p3/registration").glob("*_sa7.json")):
j = json.loads(f.read_text())
if j.get("no_anchors"):
continue
rows += [dict(dataset="F3", training_set=";".join(j["training_wells"]), well=d["well"],
sigma_post_ms=d["sigma_post_ms"]) for d in j["diagnostics"]]
r = pd.read_csv(outputs_dir() / "p4/summary/registration.csv")
r = r[r.sigma_a_ms == 7.0]
rows += [dict(dataset="Volve", training_set=t.training_wells, well=t.well, sigma_post_ms=t.sigma_post_ms)
for t in r.itertuples()]
return rows
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
tau, cells = d2_thresholds()
cells.to_csv(OUT / "d2_threshold_cells.csv", index=False)
pairs = pd.DataFrame(f3_c1() + volve_c1())
pairs.to_csv(OUT / "c1_pairs.csv", index=False)
sp = pd.DataFrame(c2())
sp.to_csv(OUT / "c2_sigma_post.csv", index=False)
verdict = dict(declaration_sha256=(REPO_ROOT / "docs/research/applicability-teapot.sha256").read_text().split()[0],
thresholds=tau, wide_ms=WIDE_MS, datasets={})
for (ds, scheme), g in pairs.groupby(["dataset", "scheme"]):
comp = g[g.role == "competitor"]
c1 = dict(n_pairs=len(comp), r2_in=float(comp.r2.mean()), band_pcc_in=float(comp.band_pcc.mean()),
ss_const=float(comp.ss_const.mean()),
m2_r2_in=float(g[g.role == "M2-Sa"].r2.mean()), m2_band_pcc_in=float(g[g.role == "M2-Sa"].band_pcc.mean()))
c1["pass"] = bool(c1["band_pcc_in"] >= tau["tau_band_pcc"] and c1["r2_in"] >= tau["tau_r2"] and c1["ss_const"] > 0)
med = float(sp[sp.dataset == ds].sigma_post_ms.median())
verdict["datasets"][f"{ds}/{scheme}"] = dict(C1=c1, C2=dict(sigma_post_median_ms=med, **{"pass": med >= WIDE_MS}))
(OUT / "verdict.json").write_text(json.dumps(verdict, indent=2))
print(json.dumps(verdict, indent=2))
if __name__ == "__main__":
main()

Some files were not shown because too many files have changed in this diff Show More