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>
This commit is contained in:
2026-10-27 06:03:33 +00:00
parent a76e61398a
commit cee2ff0859
84 changed files with 8793 additions and 460 deletions

View File

@@ -1,8 +1,8 @@
"""Tổng hợp kết quả LOWO P1: bảng theo giếng và macro, độ nhạy tham chiếu, calibration B3, cổng G-A.
"""Summarize the P1 LOWO results: per-well and macro tables, reference sensitivity, B3 calibration, gate G-A.
python scripts/06_summarize_p1.py
Đầu ra: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png
Outputs: outputs/p1/summary.md, outputs/p1/summary.json, outputs/figures/p1_lowo.png
"""
from __future__ import annotations
@@ -43,7 +43,7 @@ def per_well(res, label, ref):
def macro(res, label, ref):
mean, _, r = per_well(res, label, ref)
# macro theo giếng cho từng seed rồi lấy mean ± sd theo seed (phương pháp tất định có sd = 0)
# 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)
@@ -68,16 +68,16 @@ def main() -> None:
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 4 giếng: nhãn {label}, tham chiếu {ref}\n")
lines.append("| Phương pháp | RMSE (p.u.) | PCC | R² | PCC băng seismic | Skill vs B0a |")
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### Theo giếng: nhãn {lab1}, tham chiếu calibrated (RMSE p.u. / PCC / PCC băng)\n")
lines.append("| Phương pháp | " + " | ".join(wells) + " |")
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:
@@ -95,7 +95,7 @@ def main() -> None:
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### Calibration B3 (nhãn {lab1}, macro)\n")
lines.append(f"\n### B3 calibration (label {lab1}, macro)\n")
lines.append("| | " + " | ".join(cc) + " |")
lines.append("| --- |" + " --- |" * len(cc))
summary["calibration"] = {}
@@ -103,7 +103,7 @@ def main() -> None:
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 so với B3b
# 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")]
@@ -113,9 +113,9 @@ def main() -> None:
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 khác B3b'} theo ngưỡng protocol (|ΔRMSE| < 5%, |ΔPCC| < 0.05).")
f"{'B3a ≈ B3b' if equal else 'B3a differs from B3b'} under the protocol thresholds (|ΔRMSE| < 5%, |ΔPCC| < 0.05).")
# QC nhãn trong cửa sổ (D-1)
# Label QC within the window (D-1)
m_ = D[f"{wells[0]}/main_mask"].astype(bool)
lq = {}
for w in wells:
@@ -123,8 +123,8 @@ def main() -> None:
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### QC nhãn trong 600–1100 ms (PHIE so với PHIE_DT, calibrated)\n")
lines.append("| Giếng | R² | max |Δ| (p.u.) | std PHIE_DT (p.u.) |\n| --- | --- | --- | --- |")
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']} |")
@@ -133,20 +133,20 @@ def main() -> None:
(out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
print("\n".join(lines))
# Hình: dự đoán tại 4 giếng (nhãn chính)
# 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="tham chiếu (calibrated)")
ax.plot(100 * D[f"{w}/wlt/{lab1}"][m_], t, color="k", lw=0.8, ls=":", label="tham chiếu (.wlt)")
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 + (" (TB 5 seed)" if len(ks) > 1 else ""))
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%")
@@ -156,7 +156,7 @@ def main() -> None:
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, nhãn {lab1}: dự đoán tại giếng test", fontsize=11)
fig.suptitle(f"LOWO P1, label {lab1}: predictions at the test wells", fontsize=11)
fig.savefig(outputs_dir() / "figures" / "p1_lowo.png", dpi=130)