- 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>
218 lines
11 KiB
Python
218 lines
11 KiB
Python
"""P2 on D2: register the train wells, train every method, score on the 8 test wells (plan §5–6).
|
||
|
||
python scripts/11_run_d2.py --dev # dev realizations 900, 901: select step budgets → outputs/p2/dev/budgets.json
|
||
python scripts/11_run_d2.py --main # main grid (protocol_p2 must match the locked hash) → outputs/p2/main/
|
||
|
||
Each job is one cell (realization, c, N); seeds run sequentially within a job. Each cell's results are written
|
||
immediately to outputs/p2/<mode>/cells/, so a re-run skips completed cells. Cell (c = 1, N = 4) of the main grid also
|
||
includes the anchor-free variants M1-na/M2-na (H4).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import dataclasses
|
||
import hashlib
|
||
import json
|
||
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_p2.yaml"
|
||
METHODS = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M1", "M2"]
|
||
|
||
|
||
def load_protocol(check: bool) -> dict:
|
||
actual = hashlib.sha256(PROTO.read_bytes()).hexdigest()
|
||
if check:
|
||
f = REPO_ROOT / "configs" / "protocol_p2.sha256"
|
||
expected = f.read_text().split()[0] if f.exists() else "(not locked)"
|
||
if actual != expected:
|
||
raise SystemExit(f"protocol_p2.yaml is not locked or changed after locking ({actual[:12]} ≠ {expected[:12]})")
|
||
proto = yaml.safe_load(PROTO.read_text())
|
||
for v in proto["inputs"].values():
|
||
h = hashlib.sha256((REPO_ROOT / v["path"]).read_bytes()).hexdigest()
|
||
if h != v["sha256"]:
|
||
raise SystemExit(f"{v['path']} differs from the version recorded in protocol_p2 ({h[:12]} ≠ {v['sha256'][:12]})")
|
||
return proto | {"sha256": actual}
|
||
|
||
|
||
def reg_settings(P: dict) -> dict:
|
||
r = P["registration"]
|
||
keys = ("S", "g_max", "sigma_a_ms", "sigma_b_ms", "kernel", "hyperprior", "hyper_starts", "ess_min_frac",
|
||
"shift_K", "wavelet_ms")
|
||
return {k: r[k] for k in keys}
|
||
|
||
|
||
def method_specs(out: dict, P: dict, names: list[str]) -> dict:
|
||
"""Training spec (bank_train.train_predict) for each method, with normalized labels."""
|
||
m0, s0 = out["norm"]
|
||
nb = lambda a: (a - m0) / s0
|
||
B, lam = out["banks"], out["lam"]
|
||
N = len(out["wells"])
|
||
T = P["training"]
|
||
specs = {}
|
||
for m in names:
|
||
base = m.removesuffix("-na")
|
||
if base in ("Oracle", "B3a", "B3b", "B3c", "B3d"):
|
||
specs[m] = {"kind": "bank", "Y": nb(B[base]), "logpi": np.zeros((N, 1)), "lam": lam}
|
||
elif base in ("B4a", "B4b"):
|
||
K = B["B4"].shape[1]
|
||
specs[m] = {"kind": "bank", "Y": nb(B["B4"]), "logpi": np.full((N, K), -np.log(K)),
|
||
"lam": None if base == "B4a" else lam}
|
||
elif base == "B4c":
|
||
specs[m] = {"kind": "softdtw", "Y": nb(B["B3b"])} | T["softdtw"]
|
||
elif base == "B4d":
|
||
specs[m] = {"kind": "dilate", "Y": nb(B["B3b"])} | T["dilate"]
|
||
elif base in ("M1", "M2"):
|
||
specs[m] = {"kind": "bank", "Y": nb(B[base]), "logpi": out["logpi"][base], "lam": lam}
|
||
elif base == "MSE0": # H1 with σ_δ = 0: Oracle labels, windowed MSE
|
||
from ml_porosity.models.bank_train import WIN, window_starts_fixed
|
||
Y = nb(B["Oracle"][:, 0])
|
||
specs[m] = {"kind": "mse_win", "Ywin": np.stack([Y[:, j: j + WIN] for j in window_starts_fixed(Y.shape[1])], 1)}
|
||
else:
|
||
raise ValueError(m)
|
||
return specs
|
||
|
||
|
||
def evaluate(yt: np.ndarray, mu: np.ndarray, sigma: np.ndarray, f_c: float) -> list[dict]:
|
||
from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics
|
||
|
||
return [point_metrics(a, m) | band_metrics(a, m, f_c) | gaussian_metrics(a, m, s) for a, m, s in zip(yt, mu, sigma)]
|
||
|
||
|
||
def run_cell(job) -> tuple[list[dict], list[dict], float]:
|
||
rid, c, N, seeds, budgets, P, device, out_dir = job
|
||
import torch
|
||
|
||
torch.set_num_threads(2)
|
||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||
from ml_porosity.models.bank_train import train_predict, zscore_patch
|
||
from ml_porosity.registration.pipeline import register
|
||
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"]]
|
||
drift = WarpHyper(**prior["hyper"])
|
||
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
|
||
R = D2Realization(cfg, rid, hg, drift, wav)
|
||
G = P["grid"]
|
||
sa = cfg["anchors"]["sigma_a_ms"]
|
||
obs = [R.observe(w, c, G["snr_db"], sa, G["anchor_density"]) for w in R.pool[:N]]
|
||
test = [R.observe(w, c, G["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 = reg_settings(P)
|
||
h4 = "M1-na" in budgets
|
||
tcfg = P["training"]["model"] | P["training"]["optimizer"]
|
||
rows, diag, preds = [], [], {}
|
||
key = dict(rid=rid, c=c, n_train=N)
|
||
for seed in seeds:
|
||
out = register(R, obs, reg, seed)
|
||
specs = method_specs(out, P, [m for m in budgets if not m.endswith("-na")])
|
||
info = key | {"seed": seed, "phase": out["phase"], "lam": out["lam"], "tau_c": out["tau_c"]} | \
|
||
{f"hyper_{k}": v for k, v in out["hyper"].items() if k != "kernel"} | \
|
||
{"hyper_log_marginal": out["hyper_info"]["log_marginal"], "hyper_at_bound": ",".join(out["hyper_info"]["at_bound"])}
|
||
diag += [info | {"variant": "anchor"} | d for d in out["diag"]]
|
||
if h4:
|
||
na = register(R, obs, reg, seed, prior=dataclasses.replace(drift.scaled(c), sigma_b_ms=reg["sigma_b_ms"]))
|
||
specs |= method_specs(na, P, ["M1-na", "M2-na"])
|
||
diag += [key | {"seed": seed, "phase": na["phase"], "lam": na["lam"], "tau_c": na["tau_c"], "variant": "no_anchor"} | d
|
||
for d in na["diag"]]
|
||
m0, s0 = out["norm"]
|
||
for m, sp in specs.items():
|
||
bud = budgets[m] if isinstance(budgets[m], list) else [budgets[m]]
|
||
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, 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)
|
||
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)
|
||
tag = f"r{rid}_c{c:g}_n{N}"
|
||
np.savez_compressed(out_dir / f"{tag}.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"{tag}_diag.csv", index=False)
|
||
pd.DataFrame(rows).to_csv(out_dir / f"{tag}.csv", index=False) # written last: marks the cell as done
|
||
return rows, diag, time.time() - t0
|
||
|
||
|
||
def select_budgets(df: pd.DataFrame) -> dict:
|
||
"""For each method: the budget with the smallest mean total RMSE (macro over test wells → mean over rid × N × seed)."""
|
||
run = df.groupby(["method", "budget", "rid", "n_train", "seed"])["rmse"].mean().groupby(["method", "budget"]).mean()
|
||
return {m: int(run.loc[m].idxmin()) for m in run.index.get_level_values(0).unique()}
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser()
|
||
mode = ap.add_mutually_exclusive_group(required=True)
|
||
mode.add_argument("--dev", action="store_true")
|
||
mode.add_argument("--main", action="store_true")
|
||
ap.add_argument("--workers", type=int, default=6)
|
||
ap.add_argument("--device", default="cuda:1")
|
||
ap.add_argument("--only-cells", default="", help="cell filter, e.g. 'c=1,n=4' (testing only)")
|
||
args = ap.parse_args()
|
||
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "3"}.items():
|
||
os.environ.setdefault(k, v)
|
||
|
||
P = load_protocol(check=args.main)
|
||
G = P["grid"]
|
||
if args.dev:
|
||
tag, rids, cs, ns, seeds = "dev", G["dev_realizations"], [G["realistic_drift"]], [4, 16], [0, 1]
|
||
budgets = {m: P["training"]["budget_candidates"] for m in METHODS + ["MSE0"]}
|
||
else:
|
||
tag, rids, cs, ns, seeds = "main", G["realizations"], G["drift_factors"], G["n_train"], G["seeds"]
|
||
budgets = dict(P["training"]["budgets"])
|
||
missing = [m for m in METHODS if m not in budgets]
|
||
if missing:
|
||
raise SystemExit(f"missing budgets for {missing} in protocol_p2")
|
||
out_dir = outputs_dir() / "p2" / tag
|
||
(out_dir / "cells").mkdir(parents=True, exist_ok=True)
|
||
|
||
flt = dict(kv.split("=") for kv in args.only_cells.split(",") if kv)
|
||
jobs = []
|
||
for rid in rids:
|
||
for c in cs:
|
||
for N in ns:
|
||
if ("c" in flt and float(flt["c"]) != c) or ("n" in flt and int(flt["n"]) != N):
|
||
continue
|
||
if (out_dir / "cells" / f"r{rid}_c{c:g}_n{N}.csv").exists():
|
||
continue
|
||
b = {m: budgets[m] for m in METHODS + (["MSE0"] if args.dev else [])}
|
||
if args.main and c == G["realistic_drift"] and N == 4:
|
||
b |= {"M1-na": budgets["M1"], "M2-na": budgets["M2"]}
|
||
jobs.append((rid, c, N, seeds, b, P, args.device, out_dir / "cells"))
|
||
jobs.sort(key=lambda j: -j[2]) # cells with large N run first for load balancing
|
||
print(f"{len(jobs)} cells to run, {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 r{futs[f][0]} c={futs[f][1]:g} N={futs[f][2]} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
|
||
|
||
cells = sorted((out_dir / "cells").glob("r*_n*.csv"))
|
||
df = pd.concat([pd.read_csv(f) for f in cells if not f.name.endswith("_diag.csv")], ignore_index=True)
|
||
dg = pd.concat([pd.read_csv(f) for f in cells if f.name.endswith("_diag.csv")], ignore_index=True)
|
||
df.assign(protocol_sha256=P["sha256"][:12]).to_csv(out_dir / "results.csv", index=False)
|
||
dg.to_csv(out_dir / "diag.csv", index=False)
|
||
if args.dev:
|
||
sel = select_budgets(df)
|
||
(out_dir / "budgets.json").write_text(json.dumps(sel, indent=1))
|
||
print("selected budgets:", sel)
|
||
print(f"-> {out_dir} ({len(df)} rows, {time.time() - t0:.0f} s)")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
os.environ.setdefault("PYTHONHASHSEED", "0")
|
||
main()
|