P0 + P1: ml_porosity package, audited F3 data, LOWO baselines, protocol v2

P0
- ml_porosity/: survey geometry, LAS/TDR/SEG-Y readers (4 ms delay fix,
  invalid time scalar, header LUT for incomplete cubes), anti-aliased
  log-to-time resampling, CNN-GRU v2 with the thesis loss, 41+ unit tests.
- Full F3 Demo 2023 under data/ (text well/fault files tracked, bulk data
  ignored); the filtered copy and its cleanup notes are removed.
- SHA-256 manifests for F3, Volve, NLOG and the thesis outputs.

P1
- configs/protocol.yaml v2, locked by SHA-256 at 2026-10-26T04:28:09Z,
  before the first LOWO run (04:30:50Z); 05_lowo.py refuses to run on a
  hash mismatch. This commit postdates the runs.
- Wavelet/synthetic tie QC, residual misregistration, LOWO 5 seeds for
  B0a, B0b, B1, B2, B3a, B3b (scripts 04-06); gate G-A: no pivot.
- Volve D3: horizons, well picks, checkshots and the ST10010 cube read
  from data/Volve (scripts/07).
- D-1 label check against measured NLOG density (scripts/08): PHIE_DT
  stays the primary label.
- docs/plan.md, Volve and NLOG inventories, report.html.

Full-text reference PDFs in refs/ stay local (ignored).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 08:41:11 +00:00
parent d11b7b1bb5
commit a76e61398a
163 changed files with 120177 additions and 2742 deletions

120
scripts/03_train.py Normal file
View File

@@ -0,0 +1,120 @@
"""Huấn luyện CNN–GRU v2 với loss gốc trên bộ dữ liệu từ 01_build_wells.py (B2).
python scripts/03_train.py --config configs/b2_smoke.yaml [--epochs N] [--seed S]
So với `test 2/train_open_patch_v2.py`: vị trí giếng đúng, TDR chọn được, giếng validation
tách khỏi giếng train, không clip nhãn, không ước lượng lag bằng tương quan seismic–PHIE,
metric tính ở thang thật. Đầu ra: outputs/runs/<tên config>_s<seed>/.
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
import numpy as np
import torch
import yaml
from ml_porosity.eval.metrics import point_metrics
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
from ml_porosity.models.cnn_gru import CNNGRU
from ml_porosity.paths import outputs_dir
def zscore_rows(X: np.ndarray) -> np.ndarray:
mu = X.mean(axis=-1, keepdims=True)
sd = X.std(axis=-1, keepdims=True) + 1e-8
return (X - mu) / sd
def load_split(D, wells: list[str], tdr: str, label: str):
X = np.stack([zscore_rows(D[f"{w}/seismic_patch"].astype(np.float64)) for w in wells])
Y = np.stack([D[f"{w}/{tdr}/{label}"] for w in wells])
if not np.all(np.isfinite(Y)):
raise ValueError(f"nhãn {tdr}/{label} có NaN trong cửa sổ ở {wells}; cần chọn cửa sổ khác")
return X, Y
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--config", required=True)
ap.add_argument("--epochs", type=int)
ap.add_argument("--seed", type=int)
args = ap.parse_args()
cfg = yaml.safe_load(open(args.config))
if args.epochs is not None:
cfg["epochs"] = args.epochs
if args.seed is not None:
cfg["seed"] = args.seed
test, val, train = cfg["test_well"], cfg["val_well"], cfg["train_wells"]
if test in train or val in train or test == val:
raise ValueError("giếng train, validation và test phải tách rời")
torch.manual_seed(cfg["seed"])
np.random.seed(cfg["seed"])
device = "cuda" if torch.cuda.is_available() else "cpu"
D = np.load(outputs_dir() / cfg["dataset"])
Xtr, Ytr = load_split(D, train, cfg["tdr"], cfg["label"])
Xva, Yva = load_split(D, [val], cfg["tdr"], cfg["label"])
Xte, Yte = load_split(D, [test], cfg["tdr"], cfg["label"])
mu, sd = float(Ytr.mean()), float(Ytr.std() + 1e-8) # chỉ dùng thống kê train
def T(a):
return torch.tensor(a, dtype=torch.float32, device=device)
xtr, ytr = T(Xtr), T((Ytr - mu) / sd)[:, None]
xva, yva = T(Xva), T((Yva - mu) / sd)[:, None]
model = CNNGRU(in_ch=Xtr.shape[1], d=cfg["d_channels"], pdrop=cfg["p_dropout"]).to(device)
loss_fn = LegacyV2Loss()
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode="min", factor=0.5, patience=50)
run_dir = outputs_dir() / "runs" / f"{Path(args.config).stem}_s{cfg['seed']}"
run_dir.mkdir(parents=True, exist_ok=True)
best, best_ep, t_start = float("inf"), 0, time.time()
for ep in range(1, cfg["epochs"] + 1):
model.train()
opt.zero_grad()
pred = model(xtr)
if ep <= 50: # nhiễu nhỏ những epoch đầu như luận văn
pred = pred + 0.01 * torch.randn_like(pred)
loss = loss_fn(pred, ytr)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
opt.step()
model.eval()
with torch.no_grad():
vloss = float(loss_fn(model(xva), yva))
sched.step(vloss)
if vloss < best:
best, best_ep = vloss, ep
torch.save(model.state_dict(), run_dir / "best.pt")
if ep == 1 or ep % 50 == 0:
print(f"ep {ep:4d} train {loss.item():.4f} val {vloss:.4f} best {best:.4f} @ {best_ep}")
model.load_state_dict(torch.load(run_dir / "best.pt", map_location=device))
model.eval()
with torch.no_grad():
yp = model(T(Xte)).cpu().numpy()[0, 0] * sd + mu
yt = Yte[0]
m = point_metrics(yt, yp)
m_const = point_metrics(yt, np.full_like(yt, mu)) # dự đoán bằng trung bình train
result = {"config": cfg, "device": device, "best_epoch": best_ep, "best_val_loss": best,
"train_seconds": round(time.time() - t_start, 1),
"test": m, "test_constant_train_mean": m_const}
(run_dir / "metrics.json").write_text(json.dumps(result, indent=1, ensure_ascii=False))
np.savez_compressed(run_dir / "pred_test.npz", times_ms=D[f"{test}/times_ms"], y_true=yt, y_pred=yp)
print(f"[test {test}] RMSE {m['rmse']:.4f} PCC {m['pcc']:.3f} R² {m['r2']:.2f} "
f"(hằng số: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}")
if __name__ == "__main__":
main()