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>
This commit is contained in:
2026-10-28 07:01:08 +07:00
parent a22f9d951f
commit 9976abc96b
50 changed files with 2738 additions and 219 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

3
.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/

View File

@@ -4,7 +4,7 @@ Seismic-to-porosity learning on F3 when the well tie is uncertain (RML: training
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 (28/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,16 +13,31 @@ 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.
## 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). 1. **P4 Volve** (pipeline 28/10, runs 29/10, gate G-D).
2. **P4 Volve** (pipeline 28/10, runs 29/10, gate G-D). 2. **P5 writing** (29–30/10). Include the negative P3 result and the previously
3. **P5 writing** (29–30/10). If late, cut scope in the order given in `docs/plan.md` §6. recorded P2r deviation. If late, cut scope in the order given in `docs/plan.md` §6.
## 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.
@@ -30,7 +45,16 @@ Read first: `docs/plan.md` (plan, gates, decisions; §6 roadmap, §10 forbidden
- **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.
- **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
@@ -37,7 +78,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) |
@@ -56,4 +97,4 @@ Biến môi trường máy đặt sẵn `OMP_NUM_THREADS=40` (cả MKL, OpenBLAS
| `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` |
`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

@@ -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

@@ -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`;
@@ -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
@@ -440,7 +442,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.
--- ---
@@ -550,7 +552,7 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
## 12. Việc làm ngay (26/10–31/10/2026) ## 12. Việc làm ngay (26/10–31/10/2026)
1. `git init` kèm `.gitignore` loại trừ dữ liệu và `outputs/`. Ghi lại hash của dữ liệu theo `cleanup-manifest.json`. 1. `git init` kèm `.gitignore` loại trừ dữ liệu và `outputs/`. Ghi lại hash của dữ liệu theo `cleanup-manifest.json`.
2. ~~Tải về máy `F3_entire.segy` và các horizon.~~ **Đã xong ngày 26/10/2026** (tải F3 Demo 2023 đầy đủ qua gdown; 104 file đã lọc trước đó khớp byte-by-byte với bản mới). Còn thiếu `outputs/`. 2. ~~Tải về máy `F3_entire.segy` và các horizon.~~ **Đã xong ngày 26/10/2026** (tải F3 Demo 2023 đầy đủ qua gdown; 104 file đã lọc trước đó khớp byte-by-byte với bản mới). 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.
@@ -604,3 +606,20 @@ Trạng thái ngày 26/10/2026. "Có" nghĩa là toàn văn nằm trong [`refs/`
- **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), nên không quy hết cho khử nhoè. c = 2 có cờ "unstable posterior", không là bằng chứng chính.
- **H3 (mô tả):** mọi ensemble, kể cả Oracle, under-cover (coverage 90% từ 0.31 đến 0.79, trung vị 0.47); không claim calibration. - **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.

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

@@ -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
```

View File

@@ -68,7 +68,7 @@ Với phổ seismic thật của F3 (tâm khoảng 50 Hz):
Chỉ cần σ_δ = 8 ms là gần như toàn bộ chi tiết mà seismic có thể cung cấp bị xoá khỏi mục tiêu học. Trên F3, sai số thực tế còn lớn hơn thế. Chỉ cần σ_δ = 8 ms là gần như toàn bộ chi tiết mà seismic có thể cung cấp bị xoá khỏi mục tiêu học. Trên F3, sai số thực tế còn lớn hơn thế.
Phép tính này giải thích các "triệu chứng" của mô hình trong luận văn gốc (code trong `test 2/`): Phép tính này giải thích các "triệu chứng" của mô hình trong luận văn gốc (code trong `code_thesis/`):
- dự đoán bị trơn (smoothing); - dự đoán bị trơn (smoothing);
- phải thêm loss khớp phương sai (L_Var) vì dự đoán co biên độ; - phải thêm loss khớp phương sai (L_Var) vì dự đoán co biên độ;
- phải thêm bước tìm best-shift ±64 ms. - phải thêm bước tìm best-shift ±64 ms.

View File

@@ -128,3 +128,18 @@ 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
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

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 @@
"""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
if tau_k.size:
self.mu, cov, self.A, self.off = laplace_posterior(grid, h, tau_k, self.d_k) 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
if fcntl is not None:
fcntl.flock(f, fcntl.LOCK_EX)
else:
import msvcrt
lock = open(root / '.index.lock', 'a+b')
lock.seek(0, 2)
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) f.seek(0)
new = not f.read(1) new = not f.read(1)
w = csv.DictWriter(f, FIELDS, extrasaction="ignore") w = csv.DictWriter(f, FIELDS, extrasaction="ignore", lineterminator='\n')
if new: if new:
w.writeheader() w.writeheader()
w.writerow(row) w.writerow(row)
f.flush()
finally:
if fcntl is not None:
fcntl.flock(f, fcntl.LOCK_UN) 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:
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) 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,11 +352,15 @@ 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
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() 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"])

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()

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

@@ -115,6 +115,18 @@ 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 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>
@@ -176,7 +188,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.
@@ -211,10 +223,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."}
@@ -248,11 +260,15 @@ const PHASES = [
]}, ]},
{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",
@@ -309,8 +325,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."},
@@ -341,7 +357,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 +462,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 +474,8 @@ 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."]
]; ];
/* ===================== HẾT DATA ===================== */ /* ===================== HẾT DATA ===================== */
@@ -468,7 +485,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 +578,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()

40
scripts/run_p3.ps1 Normal file
View File

@@ -0,0 +1,40 @@
param(
[ValidateSet('status','prepare','benchmark','benchmark-registration','lock','register','train','diagnostics','summarize','all')]
[string]$Stage = 'all',
[ValidatePattern('^(cuda:[0-9]+|cpu)$')][string]$Device = 'cuda:0',
[ValidateRange(1,8)][int]$Workers = 4,
[switch]$Detach,
[switch]$Smoke,
[switch]$Sections,
[switch]$SkipVolume
)
$ErrorActionPreference = 'Stop'
$p3Workspace = Split-Path -Parent $PSScriptRoot
$p3Python = Join-Path $p3Workspace '.venv/Scripts/python.exe'
$env:OMP_NUM_THREADS = '2'
$env:MKL_NUM_THREADS = '2'
$env:OPENBLAS_NUM_THREADS = '2'
$env:NUMBA_NUM_THREADS = '2'
$env:PYTHONUTF8 = '1'
$env:PYTHONHASHSEED = '0'
$env:CUBLAS_WORKSPACE_CONFIG = ':4096:8'
$p3Arguments = @('-X','utf8','-m','ml_porosity.runlog','-n',"p3_$Stage",'--',
$p3Python,'-X','utf8',(Join-Path $PSScriptRoot '19_run_f3.py'),$Stage,
'--device',$Device,'--workers',"$Workers")
if ($Smoke) { $p3Arguments += '--smoke' }
if ($Sections) { $p3Arguments += '--sections' }
if ($SkipVolume) { $p3Arguments += '--skip-volume' }
if ($Detach) {
$p3LogDirectory = Join-Path $p3Workspace 'logs/runs'
New-Item -ItemType Directory -Path $p3LogDirectory -Force | Out-Null
$p3Stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$p3QuotedArguments = $p3Arguments | ForEach-Object { '"' + $_.Replace('"','\"') + '"' }
$p3Process = Start-Process -FilePath $p3Python -ArgumentList $p3QuotedArguments -WorkingDirectory $p3Workspace `
-WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $p3LogDirectory "${p3Stamp}_p3_stdout.log") `
-RedirectStandardError (Join-Path $p3LogDirectory "${p3Stamp}_p3_stderr.log")
Write-Output "P3 detached: PID $($p3Process.Id). Track report.html and outputs/p3/progress.json."
} else {
Push-Location $p3Workspace
try { & $p3Python @p3Arguments; if ($LASTEXITCODE -ne 0) { throw "P3 exited with code $LASTEXITCODE" } }
finally { Pop-Location }
}

214
tests/test_f3.py Normal file
View File

@@ -0,0 +1,214 @@
"""P3 invariants: well-level separation, inner-only selection, uncertainty and safe resume."""
from __future__ import annotations
import copy
import json
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
import torch
from ml_porosity.f3.data import F3Data
from ml_porosity.f3.evaluation import choose_budget, gate_verdict, neural_predictions
from ml_porosity.f3.protocol import digest, inner_folds, load_protocol, training_sets
from ml_porosity.f3.runner import job_path, reusable
from ml_porosity.f3.training import ensemble, make_model, method_spec, train_trajectory
from ml_porosity.f3.volume import deployment_budget, predict_batch
@pytest.fixture
def f3_data(tmp_path, monkeypatch):
p = copy.deepcopy(load_protocol())
p['data']['labels'] = ['PHIE_DT']
p['split']['seeds'] = [0]
p['methods'].update(main=['M2-Sa'], ablations=[], ablation_labels=[])
p['registration']['sigma_a_sensitivity_ms'] = []
p['training']['budgets'] = [1, 2]
times = np.arange(600., 1104., 4.)
a = {}
for i, w in enumerate(p['data']['wells']):
a[f'{w}/times_ms'] = times
a[f'{w}/main_mask'] = np.ones(len(times), bool)
a[f'{w}/seismic_patch'] = np.random.default_rng(i).normal(size=(9, len(times)))
a[f'{w}/anchors_md'] = np.array([1., 2.])
for ref in ('calibrated', 'wlt'):
a[f'{w}/{ref}/PHIE_DT'] = .2+.01*np.sin(np.arange(len(times))*.1)+i*.01
np.savez_compressed(tmp_path/'f3_wells.npz', **a)
monkeypatch.setattr('ml_porosity.f3.data.outputs_dir', lambda: tmp_path)
return p, a, tmp_path
def test_training_view_has_no_held_out_logs_or_markers(f3_data):
p, _, _ = f3_data
train = tuple(p['data']['wells'][:2])
d = F3Data(p, training_wells=train)
outer = p['data']['wells'][-1]
assert d.X(outer).shape == (9, 126)
assert f'{outer}/anchors_md' not in d.arrays
assert f'{outer}/calibrated/PHIE_DT' not in d.arrays
with pytest.raises(RuntimeError, match='Held-out labels'):
d.y(outer, 'calibrated', 'PHIE_DT')
with pytest.raises(RuntimeError, match='Held-out logs'):
d.training_observations((outer,))
def test_inner_folds_keep_entire_wells_out():
wells = ['a', 'b', 'c', 'd']
for outer in wells:
folds = inner_folds(wells, outer)
assert len(folds) == 3
for valid, train in folds:
assert len(train) == 2 and outer not in train and valid not in train
assert set(train) | {valid, outer} == set(wells)
assert len(training_sets(wells)) == 6
def test_changing_outer_labels_cannot_change_its_checkpoint_or_prediction(f3_data):
p, arrays, root = f3_data
for train in training_sets(p['data']['wells']):
path = job_path(root, train, 'M2-Sa', 'PHIE_DT', 0)
path.parent.mkdir(parents=True, exist_ok=True)
pred = {'wells': np.asarray(p['data']['wells'])}
for budget in (1, 2):
pred[f'{budget}/mu'] = np.stack([arrays[f'{w}/calibrated/PHIE_DT']+budget*.001 for w in p['data']['wells']])
pred[f'{budget}/sigma'] = np.ones((4, 126))*.01
np.savez_compressed(path, **pred)
target = p['data']['wells'][0]
before, chosen_before = neural_predictions(F3Data(p), p, root)
arrays[f'{target}/calibrated/PHIE_DT'] += 100
np.savez_compressed(root/'f3_wells.npz', **arrays)
after, chosen_after = neural_predictions(F3Data(p), p, root)
assert [a['budget'] for a in chosen_before if a['test_well'] == target] == [a['budget'] for a in chosen_after if a['test_well'] == target]
for a, b in zip([a for a in before if a['test_well'] == target], [a for a in after if a['test_well'] == target]):
np.testing.assert_array_equal(a['mu'], b['mu'])
np.testing.assert_array_equal(a['sigma'], b['sigma'])
def test_ensemble_uses_total_variance_not_mean_sigma():
mean, sigma = ensemble(np.array([[0., 2.], [2., 4.]]), np.array([[1., 1.], [1., 1.]]))
np.testing.assert_allclose(mean, [1., 3.])
np.testing.assert_allclose(sigma, np.sqrt(2))
def test_volume_preserves_small_predictive_variance():
class ConstantModel(torch.nn.Module):
def forward(self, x):
mu = torch.full((len(x), 1, x.shape[-1]), 1000., device=x.device)
return mu, torch.full_like(mu, 1e-6)
mu, sigma = predict_batch([(ConstantModel(), 0., 1.) for _ in range(20)], np.zeros((2, 9, 126)), 'cpu')
np.testing.assert_allclose(mu, 1000.)
np.testing.assert_allclose(sigma, 1e-6, rtol=1e-5)
def test_warp_support_rejects_unmeasured_labels_and_gaps():
from types import SimpleNamespace
from ml_porosity.f3.registration import valid_label_warps
tau = np.arange(0., 100., 1.)
data = SimpleNamespace(tau=tau, t_main=np.arange(20., 30.))
valid = np.ones(len(tau), bool)
valid[50:60] = False
obs = {'label_valid': {'PHIE_DT': valid}}
# Identity stays measured; the shifted map sends the same scoring times into a missing interval.
warps = np.stack([tau, tau-30, tau+60])
np.testing.assert_array_equal(valid_label_warps(data, obs, warps, ['PHIE_DT']), [True, False, False])
def test_budget_ties_choose_earliest():
assert choose_budget(np.array([[3., 1., 1.], [1., 1., 1.]]), [1, 2, 3]) == 2
assert deployment_budget([125, 250], [125, 250]) == 125
def test_gc_does_not_choose_baseline_from_outer_metrics():
p = load_protocol()
metrics, selection = [], []
for w in p['data']['wells']:
for m, rmse in [('M2-Sa', .9), ('B3b', 1.0), ('B3c', .1), ('B3c-R', .2)]:
metrics.append(dict(label='PHIE_DT', reference='calibrated', seed='ensemble', sigma_a_ms=7.,
test_well=w, method=m, band_rmse=rmse, coverage_80=.8, coverage_90=.9))
for m, mse in [('B3b', 1.), ('B3c', 2.), ('B3c-R', 3.)]:
selection.append(dict(label='PHIE_DT', sigma_a_ms=7., test_well=w, method=m, validation_mse=mse))
frame, sel = pd.DataFrame(metrics), pd.DataFrame(selection)
g = gate_verdict(frame, sel, p)
assert g['pass'] and g['improved_wells'] == 4
assert all(r['competitor'] == 'B3b' for r in g['per_well'])
frame.loc[frame.method == 'M2-Sa', 'coverage_90'] = .79
g = gate_verdict(frame, sel, p)
assert g['direction_pass'] and not g['coverage_pass'] and not g['pass']
def test_resume_refuses_missing_or_changed_checkpoint(tmp_path):
path = tmp_path/'train/job.npz'
path.parent.mkdir()
np.savez_compressed(path, mu=np.ones((2, 126)))
checkpoint = path.with_suffix('.pt')
torch.save({'example': torch.ones(1)}, checkpoint)
meta = {'fingerprint': 'test', 'artifact_sha256': digest(path), 'checkpoint_sha256': digest(checkpoint)}
path.with_suffix('.json').write_text(json.dumps(meta), encoding='utf-8')
assert reusable(path, 'test')
checkpoint.write_bytes(b'changed')
with pytest.raises(RuntimeError, match='checkpoint'):
reusable(path, 'test')
@pytest.mark.parametrize('method', ['B2', 'B3b', 'B4a', 'B4b', 'B4c', 'B4d', 'M1', 'M2-Sa',
'M2-anchor-only', 'M2-bulk', 'M2-lambda1', 'M2-S1', 'M2-S8', 'M2-S256', 'M2-fixed-sigma',
'M2-legacy-loss', 'M2-TCN', 'B3d-Sa-TCN', 'M2-LFM'])
def test_every_training_branch_and_checkpoint_replays(method, tmp_path):
p = load_protocol()
rng = np.random.default_rng(7)
bundle = {'PHIE_DT/norm': np.array([0., 1.]), 'PHIE_DT/lambda': np.array(.37)}
for m, size in [('B2', 1), ('B3b', 1), ('B3d-Sa', 1), ('B4', 17), ('M1', 64), ('M2-Sa', 64), ('M2-S256', 256), ('M2-bulk', 64)]:
bundle[f'PHIE_DT/{m}'] = rng.normal(size=(2, size, 126)).astype(np.float32)
spec = method_spec(bundle, 'PHIE_DT', method, p)
cfg = p['training'] | {'d_channels': 8, 'fixed_sigma': 1.0}
channels = 10 if method == 'M2-LFM' else 9
X = rng.normal(size=(2, channels, 126)).astype(np.float32)
path = tmp_path/'model.pt'
pred, meta = train_trajectory(X, X, spec, method, cfg, 0, [1, 2], 'cpu', path)
assert meta['steps'] == 2 and np.isfinite(pred['2/mu']).all()
saved = torch.load(path, map_location='cpu', weights_only=True)
model = make_model(saved['method'], channels, saved['config'])
model.load_state_dict(saved['states'][2])
from ml_porosity.models.train import predict
mu, sigma = predict(model, X, 'cpu')
np.testing.assert_allclose(mu, pred['2/mu'], atol=1e-6)
if sigma is not None:
np.testing.assert_allclose(sigma, pred['2/sigma'], atol=1e-6)
@pytest.mark.parametrize('no_anchors', [False, True])
def test_registration_pipeline_on_synthetic_wells_only(no_anchors):
from types import SimpleNamespace
from ml_porosity.f3.registration import register_set
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.registration.tie_likelihood import fine_wavelet, synth_for_warps
from ml_porosity.registration.warp_prior import WarpGrid
p = copy.deepcopy(load_protocol())
p['registration'].update(particles=16, S=8, hyper_starts=1, smc_moves=1,
phase_half_width=0, phase_max_extra=0, fine_dt_ms=2., warp_dtau_ms=40.)
tau = np.arange(200., 1501., 2.)
t = np.arange(400., 1301., 4.)
main = t[(t >= 600) & (t <= 1100)]
tf = np.arange(100., 1601., 2.)
rng = np.random.default_rng(19)
w0 = statistical_wavelet(rng.normal(size=(2, len(t))), 4., 128.)
obs = []
for i, name in enumerate(('train_a', 'train_b')):
ai = 8000+600*np.sin(tau/25+i)+200*np.cos(tau/11)
phi = .25+.02*np.sin(tau/25+i)
syn = synth_for_warps(tau, ai, tau, tf, t, fine_wavelet(w0, 2))[0]
seis = syn+rng.normal(size=len(syn))*max(syn.std(), 1e-8)*.1
anchors = np.arange(400., 1301., 100.)
obs.append(dict(name=name, ai_log=ai, labels={'PHIE_DT': phi, 'PHIE': phi},
label_valid={lab: np.ones(len(tau), bool) for lab in ('PHIE_DT', 'PHIE')},
seis=seis, tau_k=anchors, t_k=anchors+rng.normal(size=len(anchors))))
toy = SimpleNamespace(grid=WarpGrid(200., 1500., 40.), tau=tau, t=t, t_main=main, t_fine=tf, dt=4.,
training_observations=lambda names: obs,
y=lambda name, ref, label: np.interp(main, tau, obs[0 if name == 'train_a' else 1]['labels'][label]))
bundle, meta = register_set(toy, ('train_a', 'train_b'), p, 'cpu', no_anchors=no_anchors)
assert meta['training_wells'] == ['train_a', 'train_b']
assert bundle['PHIE_DT/M2-Sa'].shape == (2, 8, 126)
assert np.isfinite(bundle['PHIE_DT/M2-Sa']).all()
assert np.isfinite(bundle['PHIE_DT/B3d-Sa']).all()

View File

@@ -9,6 +9,8 @@ import sys
import time import time
from pathlib import Path from pathlib import Path
import pytest
from ml_porosity.paths import REPO_ROOT from ml_porosity.paths import REPO_ROOT
CHILD = ("import subprocess, sys; print('out-parent'); print('err-parent', file=sys.stderr); " CHILD = ("import subprocess, sys; print('out-parent'); print('err-parent', file=sys.stderr); "
@@ -47,8 +49,9 @@ def test_failure_keeps_exit_code(tmp_path):
def test_nested_steps_go_into_parent(tmp_path): def test_nested_steps_go_into_parent(tmp_path):
inner = f"{sys.executable} -m ml_porosity.runlog -n step -- {sys.executable} -c 'print(1)'" inner = [sys.executable, '-m', 'ml_porosity.runlog', '-n', 'step', '--', sys.executable, '-c', 'print(1)']
p = launch(tmp_path, "-n", "parent", "--", "bash", "-c", f"{inner} && {inner}") code = f'import subprocess; cmd={inner!r}; subprocess.run(cmd, check=True); subprocess.run(cmd, check=True)'
p = launch(tmp_path, "-n", "parent", "--", sys.executable, '-c', code)
p.communicate(timeout=60) p.communicate(timeout=60)
assert p.returncode == 0 assert p.returncode == 0
(d,) = runs(tmp_path) (d,) = runs(tmp_path)
@@ -57,6 +60,7 @@ def test_nested_steps_go_into_parent(tmp_path):
assert [r["parent"] for r in rows] == [d.name, d.name, ""] assert [r["parent"] for r in rows] == [d.name, d.name, ""]
@pytest.mark.skipif(os.name == 'nt', reason='Windows TerminateProcess bypasses Python signal handlers; POSIX SIGTERM semantics do not apply')
def test_sigterm_marks_interrupted(tmp_path): def test_sigterm_marks_interrupted(tmp_path):
p = launch(tmp_path, sys.executable, "-c", "import time; print('started', flush=True); time.sleep(60)") p = launch(tmp_path, sys.executable, "-c", "import time; print('started', flush=True); time.sleep(60)")
t0 = time.time() t0 = time.time()