- 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>
165 lines
7.7 KiB
Python
165 lines
7.7 KiB
Python
"""Summarize the P1 LOWO results: per-well and macro tables, reference sensitivity, B3 calibration, gate G-A.
|
||
|
||
python scripts/06_summarize_p1.py
|
||
|
||
Outputs: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
|
||
import matplotlib
|
||
|
||
matplotlib.use("Agg")
|
||
import matplotlib.pyplot as plt
|
||
import numpy as np
|
||
import pandas as pd
|
||
import yaml
|
||
|
||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||
|
||
ORDER = ["B0a", "B0b-ridge", "B0b-rf", "B0b-gbm", "B1", "B2", "B3a", "B3b"]
|
||
|
||
|
||
def load():
|
||
d = outputs_dir() / "p1"
|
||
res = pd.concat([pd.read_csv(f) for f in sorted(d.glob("results_*.csv"))], ignore_index=True)
|
||
preds = {}
|
||
for f in sorted(d.glob("preds_*.npz")):
|
||
z = np.load(f)
|
||
preds.update({k: z[k] for k in z.files})
|
||
return res, preds
|
||
|
||
|
||
def per_well(res, label, ref):
|
||
r = res[(res.label == label) & (res.reference == ref)].copy()
|
||
b0a = r[r.method == "B0a"].set_index("test_well")["rmse"] ** 2
|
||
r["skill"] = 1 - r.rmse**2 / r.test_well.map(b0a)
|
||
cols = ["rmse", "pcc", "r2", "band_pcc", "band_std_ratio", "low_pcc", "skill"]
|
||
g = r.groupby(["method", "test_well"])[cols]
|
||
return g.mean(), g.std().fillna(0.0), r
|
||
|
||
|
||
def macro(res, label, ref):
|
||
mean, _, r = per_well(res, label, ref)
|
||
# macro over wells for each seed, then mean ± sd over seeds (deterministic methods have sd = 0)
|
||
cols = ["rmse", "pcc", "r2", "band_pcc", "skill"]
|
||
by_seed = r.groupby(["method", "seed"])[cols].mean()
|
||
out = by_seed.groupby("method").agg(["mean", "std"]).fillna(0.0)
|
||
return out.reindex([m for m in ORDER if m in out.index])
|
||
|
||
|
||
def fmt(m, s, nd=2):
|
||
return f"{m:.{nd}f}" if s == 0 else f"{m:.{nd}f} ± {s:.{nd}f}"
|
||
|
||
|
||
def main() -> None:
|
||
proto = yaml.safe_load((REPO_ROOT / "configs" / "protocol.yaml").read_text())
|
||
res, preds = load()
|
||
D = np.load(outputs_dir() / "f3_wells.npz")
|
||
wells = proto["data"]["wells"]
|
||
lab1, lab2 = proto["data"]["labels"]["primary"], proto["data"]["labels"]["secondary"]
|
||
lines, summary = [], {"protocol_sha256": res.protocol_sha256.iloc[0]}
|
||
|
||
for label in (lab1, lab2):
|
||
for ref in ("calibrated", "wlt"):
|
||
mt = macro(res, label, ref)
|
||
key = f"{label}/{ref}"
|
||
summary[key] = {m: {c: [round(mt.loc[m, (c, "mean")], 3), round(mt.loc[m, (c, "std")], 3)]
|
||
for c in ("rmse", "pcc", "r2", "band_pcc", "skill")} for m in mt.index}
|
||
lines.append(f"\n### Macro over 4 wells: label {label}, reference {ref}\n")
|
||
lines.append("| Method | RMSE (p.u.) | PCC | R² | Seismic-band PCC | Skill vs B0a |")
|
||
lines.append("| --- | --- | --- | --- | --- | --- |")
|
||
for m in mt.index:
|
||
lines.append("| " + " | ".join([m] + [fmt(mt.loc[m, (c, "mean")], mt.loc[m, (c, "std")])
|
||
for c in ("rmse", "pcc", "r2", "band_pcc", "skill")]) + " |")
|
||
|
||
mean, sd, _ = per_well(res, lab1, "calibrated")
|
||
lines.append(f"\n### Per well: label {lab1}, calibrated reference (RMSE p.u. / PCC / band PCC)\n")
|
||
lines.append("| Method | " + " | ".join(wells) + " |")
|
||
lines.append("| --- |" + " --- |" * len(wells))
|
||
summary["per_well"] = {}
|
||
for m in ORDER:
|
||
if m not in mean.index.get_level_values(0):
|
||
continue
|
||
cells = []
|
||
for w in wells:
|
||
a, s = mean.loc[(m, w)], sd.loc[(m, w)]
|
||
cells.append(f"{fmt(a.rmse, s.rmse)} / {a.pcc:.2f} / {a.band_pcc:.2f}")
|
||
summary["per_well"].setdefault(m, {})[w] = [round(a.rmse, 2), round(a.pcc, 2), round(a.band_pcc, 2)]
|
||
lines.append(f"| {m} | " + " | ".join(cells) + " |")
|
||
|
||
# calibration B3
|
||
cal = res[(res.label == lab1) & (res.reference == "calibrated") & res.method.isin(["B3a", "B3b"])]
|
||
if len(cal):
|
||
cc = ["nll", "crps", "coverage_50", "coverage_80", "coverage_90", "coverage_95", "mean_sigma"]
|
||
cm = cal.groupby(["method", "seed"])[cc].mean().groupby("method").agg(["mean", "std"])
|
||
lines.append(f"\n### B3 calibration (label {lab1}, macro)\n")
|
||
lines.append("| | " + " | ".join(cc) + " |")
|
||
lines.append("| --- |" + " --- |" * len(cc))
|
||
summary["calibration"] = {}
|
||
for m in cm.index:
|
||
lines.append(f"| {m} | " + " | ".join(fmt(cm.loc[m, (c, 'mean')], cm.loc[m, (c, 'std')]) for c in cc) + " |")
|
||
summary["calibration"][m] = {c: round(cm.loc[m, (c, "mean")], 3) for c in cc}
|
||
|
||
# G-A: B3a vs B3b
|
||
mt = macro(res, lab1, "calibrated")
|
||
if {"B3a", "B3b"} <= set(mt.index):
|
||
ra, rb = mt.loc["B3a", ("rmse", "mean")], mt.loc["B3b", ("rmse", "mean")]
|
||
pa, pb = mt.loc["B3a", ("pcc", "mean")], mt.loc["B3b", ("pcc", "mean")]
|
||
d_rmse = (ra - rb) / rb * 100
|
||
equal = abs(d_rmse) < 5 and abs(pa - pb) < 0.05
|
||
summary["G-A"] = {"B3a_vs_B3b_rmse_pct": round(d_rmse, 1), "B3a_minus_B3b_pcc": round(pa - pb, 3),
|
||
"B3a_approx_B3b": bool(equal)}
|
||
lines.append(f"\n**G-A:** RMSE B3a − B3b = {d_rmse:+.1f}%, PCC B3a − B3b = {pa - pb:+.3f} → "
|
||
f"{'B3a ≈ B3b' if equal else 'B3a differs from B3b'} under the protocol thresholds (|ΔRMSE| < 5%, |ΔPCC| < 0.05).")
|
||
|
||
# Label QC within the window (D-1)
|
||
m_ = D[f"{wells[0]}/main_mask"].astype(bool)
|
||
lq = {}
|
||
for w in wells:
|
||
a, b = D[f"{w}/calibrated/PHIE"][m_], D[f"{w}/calibrated/PHIE_DT"][m_]
|
||
lq[w] = {"r2": round(float(np.corrcoef(a, b)[0, 1] ** 2), 4), "max_abs_diff_pu": round(float(np.max(np.abs(a - b)) * 100), 2),
|
||
"std_pu": round(float(np.std(b) * 100), 2)}
|
||
summary["label_qc"] = lq
|
||
lines.append("\n### Label QC in 600–1100 ms (PHIE vs PHIE_DT, calibrated)\n")
|
||
lines.append("| Well | R² | max |Δ| (p.u.) | std PHIE_DT (p.u.) |\n| --- | --- | --- | --- |")
|
||
for w, v in lq.items():
|
||
lines.append(f"| {w} | {v['r2']} | {v['max_abs_diff_pu']} | {v['std_pu']} |")
|
||
|
||
out = outputs_dir() / "p1"
|
||
(out / "summary.md").write_text("\n".join(lines) + "\n")
|
||
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
|
||
print("\n".join(lines))
|
||
|
||
# Figure: predictions at the 4 wells (primary label)
|
||
t = D[f"{wells[0]}/times_ms"][m_]
|
||
fig, axes = plt.subplots(1, 4, figsize=(14, 7), sharey=True, constrained_layout=True)
|
||
style = {"B0a": ("#8a93a3", "--"), "B0b-ridge": ("#2a9d8f", "-"), "B1": ("#8a5cc2", "-"),
|
||
"B2": ("#c47a00", "-"), "B3b": ("#1f5fbf", "-")}
|
||
for ax, w in zip(axes, wells):
|
||
ax.plot(100 * D[f"{w}/calibrated/{lab1}"][m_], t, "k", lw=1.6, label="reference (calibrated)")
|
||
ax.plot(100 * D[f"{w}/wlt/{lab1}"][m_], t, color="k", lw=0.8, ls=":", label="reference (.wlt)")
|
||
for meth, (c, ls) in style.items():
|
||
ks = [k for k in preds if k.startswith(f"{lab1}/{w}/{meth}/") and k.endswith("/mu")]
|
||
if not ks:
|
||
continue
|
||
mu = 100 * np.mean([preds[k] for k in ks], axis=0)
|
||
ax.plot(mu, t, color=c, ls=ls, lw=1.1, label=meth + (" (mean of 5 seeds)" if len(ks) > 1 else ""))
|
||
if meth == "B3b":
|
||
sig = 100 * np.mean([preds[k.replace("/mu", "/sigma")] for k in ks], axis=0)
|
||
ax.fill_betweenx(t, mu - 1.645 * sig, mu + 1.645 * sig, color=c, alpha=0.12, lw=0, label="B3b 90%")
|
||
ax.set_title(f"test {w}", fontsize=10)
|
||
ax.set_xlabel(f"{lab1} (p.u.)")
|
||
ax.grid(alpha=0.3)
|
||
axes[0].set_ylim(t[-1], t[0])
|
||
axes[0].set_ylabel("TWT (ms)")
|
||
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=8, fontsize=8.5)
|
||
fig.suptitle(f"LOWO P1, label {lab1}: predictions at the test wells", fontsize=11)
|
||
fig.savefig(outputs_dir() / "figures" / "p1_lowo.png", dpi=130)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|