Files
ML-Porosity/scripts/15_diag_train.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

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