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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:33 +00:00

262 lines
10 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""LOWO for the P1 baselines per configs/protocol.yaml (B0a, B0b, B1, B2, B3a, B3b).
python scripts/05_lowo.py [--workers 12] [--device cuda] [--only B2,B3a]
Refuses to run if the SHA-256 of protocol.yaml differs from configs/protocol.sha256.
Outputs: outputs/p1/results.csv (one row per method, label, test_well, seed, reference, metric),
outputs/p1/preds.npz (μ, σ per method/label/well/seed), outputs/p1/selection.csv.
"""
from __future__ import annotations
import argparse
import hashlib
import itertools
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
PROTO = REPO_ROOT / "configs" / "protocol.yaml"
def check_protocol() -> dict:
expected = (REPO_ROOT / "configs" / "protocol.sha256").read_text().split()[0]
actual = hashlib.sha256(PROTO.read_bytes()).hexdigest()
if actual != expected:
raise SystemExit(f"protocol.yaml changed after locking ({actual[:12]} ≠ {expected[:12]}); create a new version and lock it again")
return yaml.safe_load(PROTO.read_text()) | {"sha256": actual}
class Data:
def __init__(self, proto: dict):
D = np.load(outputs_dir() / "f3_wells.npz")
self.wells = proto["data"]["wells"]
w0 = self.wells[0]
self.t = D[f"{w0}/times_ms"]
self.m = D[f"{w0}/main_mask"].astype(bool)
self.D = {k: D[k] for k in D.files}
def X(self, w):
"""Per-channel z-scored patch over the main window, shape (C, L)."""
p = self.D[f"{w}/seismic_patch"][:, self.m].astype(np.float64)
return (p - p.mean(1, keepdims=True)) / (p.std(1, keepdims=True) + 1e-8)
def y(self, w, tdr, label):
return self.D[f"{w}/{tdr}/{label}"][self.m]
def ext(self, w, key):
return self.D[f"{w}/{key}"]
# ---------------------------------------------------------------- metric
def evaluate(d: Data, test: str, label: str, mu, sigma=None) -> list[dict]:
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
rows = []
for ref in ["calibrated"] + d.proto["registration"]["sensitivity_references"]:
yt = 100 * d.y(test, ref, label)
mp = 100 * np.asarray(mu)
r = {"reference": ref} | point_metrics(yt, mp) | band_metrics(yt, mp, d.proto["metrics"]["bands"]["f_c_hz"])
if sigma is not None:
r |= gaussian_metrics(yt, mp, 100 * np.asarray(sigma))
rows.append(r)
return rows
# ---------------------------------------------------------------- B0a, B0b, B1 (CPU, nhanh)
def run_classical(d: Data, label: str, test: str, seeds: list[int]):
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from ml_porosity.baselines.attributes import trace_attributes
from ml_porosity.baselines import inversion as inv
P = d.proto["methods"]
train = [w for w in d.wells if w != test]
out, sel = [], []
tt = d.t[d.m]
def ytrain(ws):
return np.concatenate([d.y(w, "calibrated", label) for w in ws])
# B0a: linear trend in TWT
lr = LinearRegression().fit(np.tile(tt, len(train))[:, None], ytrain(train))
out.append(("B0a", -1, lr.predict(tt[:, None]), None))
# B0b: attributes from the patch mean trace (z-scored), computed on the extended window
def feats(w):
p = d.ext(w, "seismic_patch").astype(float)
p = (p - p[:, d.m].mean(1, keepdims=True)) / (p[:, d.m].std(1, keepdims=True) + 1e-8)
return trace_attributes(p.mean(0), d.t)[d.m]
F = {w: feats(w) for w in d.wells}
Ftr = np.vstack([F[w] for w in train])
ytr = ytrain(train)
def inner_mse(make):
errs = []
for v in train:
tr2 = [w for w in train if w != v]
mdl = make().fit(np.vstack([F[w] for w in tr2]), ytrain(tr2))
errs.append(np.mean((mdl.predict(F[v]) - d.y(v, "calibrated", label)) ** 2))
return float(np.mean(errs))
grid = P["B0b"]["models"]["ridge"]["alpha_grid"]
scores = [inner_mse(lambda a=a: make_pipeline(StandardScaler(), Ridge(alpha=a))) for a in grid]
alpha = grid[int(np.argmin(scores))]
sel.append({"label": label, "test_well": test, "method": "B0b-ridge", "param": "alpha", "value": alpha})
ridge = make_pipeline(StandardScaler(), Ridge(alpha=alpha)).fit(Ftr, ytr)
out.append(("B0b-ridge", -1, ridge.predict(F[test]), None))
for s in seeds:
rf = RandomForestRegressor(random_state=s, n_jobs=4, **P["B0b"]["models"]["rf"]).fit(Ftr, ytr)
out.append(("B0b-rf", s, rf.predict(F[test]), None))
gb = HistGradientBoostingRegressor(random_state=s, **P["B0b"]["models"]["gbm"]).fit(Ftr, ytr)
out.append(("B0b-gbm", s, gb.predict(F[test]), None))
# B1: inversion
hz = P["B1"]["lfm"].split("[")[1].split("]")[0].split(", ")
def wellinfo(w):
return {"logai": np.log(inv.fill_edges(d.ext(w, "calibrated/AI"))),
"h": np.array([float(d.ext(w, f"horizon/{h}")) for h in hz]),
"xy": np.array([float(d.ext(w, "x")), float(d.ext(w, "y"))])}
info = {w: wellinfo(w) for w in d.wells}
seis = {w: d.ext(w, "seismic_patch")[4].astype(float) for w in d.wells}
def b1_predict(tr_wells, target, e):
wav = inv.estimate_wavelet([info[w]["logai"] for w in tr_wells], [seis[w] for w in tr_wells], d.m)
lfm = inv.build_lfm(d.t, info[target]["h"], info[target]["xy"], {w: info[w] for w in tr_wells},
f_c_hz=d.proto["metrics"]["bands"]["f_c_hz"])
ai = np.exp(inv.invert(seis[target], wav, lfm, e))[d.m]
ai_tr = np.concatenate([np.exp(info[w]["logai"])[d.m] for w in tr_wells])
phi_fit = LinearRegression().fit(ai_tr[:, None], np.concatenate([d.y(w, "calibrated", label) for w in tr_wells]))
return phi_fit.predict(ai[:, None])
egrid = [0.01, 0.03, 0.1, 0.3, 1.0]
escores = [np.mean([np.mean((b1_predict([w for w in train if w != v], v, e) - d.y(v, "calibrated", label)) ** 2)
for v in train]) for e in egrid]
e_best = egrid[int(np.argmin(escores))]
sel.append({"label": label, "test_well": test, "method": "B1", "param": "e", "value": e_best})
out.append(("B1", -1, b1_predict(train, test, e_best), None))
return out, sel
# ---------------------------------------------------------------- B2, B3 (GPU)
def run_cnn(job):
method, label, test, seed, device, proto = job
import torch
torch.set_num_threads(2)
from ml_porosity.models.train import predict, train_cnn
d = Data(proto)
d.proto = proto
P = proto["methods"]
cfg = P["B2"]
kind = "legacy" if method == "B2" else "nll"
tdr_train = "legacy" if method == "B3a" else "calibrated"
train = [w for w in d.wells if w != test]
def XY(ws):
X = np.stack([d.X(w) for w in ws])
Y = np.stack([d.y(w, tdr_train, label) for w in ws])
return X, Y
# inner loop: epoch selection
curves = []
for v in train:
tr2 = [w for w in train if w != v]
Xa, Ya = XY(tr2)
mu_, sd_ = Ya.mean(), Ya.std() + 1e-8
Xv, Yv = XY([v])
_, c = train_cnn(Xa, (Ya - mu_) / sd_, cfg, kind, seed, cfg["max_epochs"], device,
Xv, (Yv - mu_) / sd_, cfg["eval_every"])
curves.append([m * sd_**2 for _, m in c]) # MSE in original label units
eps = [e for e, _ in c]
best_ep = int(eps[int(np.argmin(np.mean(curves, axis=0)))])
Xtr, Ytr = XY(train)
mu_, sd_ = Ytr.mean(), Ytr.std() + 1e-8
model, _ = train_cnn(Xtr, (Ytr - mu_) / sd_, cfg, kind, seed, best_ep, device)
m, s = predict(model, d.X(test)[None], device)
mu = m[0] * sd_ + mu_
sigma = None if s is None else s[0] * sd_
return method, label, test, seed, mu, sigma, best_ep
# ---------------------------------------------------------------- main
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=12)
ap.add_argument("--device", default="cuda")
ap.add_argument("--only", default="")
args = ap.parse_args()
proto = check_protocol()
d = Data(proto)
d.proto = proto
seeds = proto["split"]["seeds"]
labels = [proto["data"]["labels"]["primary"], proto["data"]["labels"]["secondary"]]
only = set(filter(None, args.only.split(",")))
out_dir = outputs_dir() / "p1"
out_dir.mkdir(exist_ok=True)
preds, rows, sel = {}, [], []
def record(method, label, test, seed, mu, sigma):
preds[f"{label}/{test}/{method}/s{seed}/mu"] = np.asarray(mu)
if sigma is not None:
preds[f"{label}/{test}/{method}/s{seed}/sigma"] = np.asarray(sigma)
for r in evaluate(d, test, label, mu, sigma):
rows.append({"method": method, "label": label, "test_well": test, "seed": seed} | r)
t0 = time.time()
if not only or only & {"B0a", "B0b", "B1"}:
for label, test in itertools.product(labels, d.wells):
out, s = run_classical(d, label, test, seeds)
sel += s
for method, seed, mu, sigma in out:
record(method, label, test, seed, mu, sigma)
print(f"B0a/B0b/B1 done after {time.time() - t0:.0f} s")
cnn = [m for m in ("B2", "B3a", "B3b") if not only or m in only]
jobs = [(m, lab, w, s, args.device, proto) for m in cnn for lab in labels for w in d.wells for s in seeds]
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = [ex.submit(run_cnn, j) for j in jobs]
for i, f in enumerate(as_completed(futs), 1):
method, label, test, seed, mu, sigma, best_ep = f.result()
sel.append({"label": label, "test_well": test, "method": method, "param": f"epochs_s{seed}", "value": best_ep})
record(method, label, test, seed, mu, sigma)
if i % 10 == 0 or i == len(jobs):
print(f"CNN {i}/{len(jobs)} sau {time.time() - t0:.0f} s")
tag = "_".join(sorted(only)) if only else "all"
pd.DataFrame(rows).assign(protocol_sha256=proto["sha256"][:12]).to_csv(out_dir / f"results_{tag}.csv", index=False)
pd.DataFrame(sel).to_csv(out_dir / f"selection_{tag}.csv", index=False)
np.savez_compressed(out_dir / f"preds_{tag}.npz", **preds)
print(f"-> {out_dir} ({len(rows)} rows, {time.time() - t0:.0f} s)")
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()