P0 - ml_porosity/: survey geometry, LAS/TDR/SEG-Y readers (4 ms delay fix, invalid time scalar, header LUT for incomplete cubes), anti-aliased log-to-time resampling, CNN-GRU v2 with the thesis loss, 41+ unit tests. - Full F3 Demo 2023 under data/ (text well/fault files tracked, bulk data ignored); the filtered copy and its cleanup notes are removed. - SHA-256 manifests for F3, Volve, NLOG and the thesis outputs. P1 - configs/protocol.yaml v2, locked by SHA-256 at 2026-10-26T04:28:09Z, before the first LOWO run (04:30:50Z); 05_lowo.py refuses to run on a hash mismatch. This commit postdates the runs. - Wavelet/synthetic tie QC, residual misregistration, LOWO 5 seeds for B0a, B0b, B1, B2, B3a, B3b (scripts 04-06); gate G-A: no pivot. - Volve D3: horizons, well picks, checkshots and the ST10010 cube read from data/Volve (scripts/07). - D-1 label check against measured NLOG density (scripts/08): PHIE_DT stays the primary label. - docs/plan.md, Volve and NLOG inventories, report.html. Full-text reference PDFs in refs/ stay local (ignored). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
165 lines
7.8 KiB
Python
165 lines
7.8 KiB
Python
"""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.
|
||
|
||
python scripts/06_summarize_p1.py
|
||
|
||
Đầu ra: 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 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)
|
||
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 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("| --- | --- | --- | --- | --- | --- |")
|
||
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("| --- |" + " --- |" * 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### Calibration B3 (nhãn {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 so với 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 khác B3b'} theo ngưỡng protocol (|ΔRMSE| < 5%, |ΔPCC| < 0.05).")
|
||
|
||
# QC nhãn trong cửa sổ (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### 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| --- | --- | --- | --- |")
|
||
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))
|
||
|
||
# Hình: dự đoán tại 4 giếng (nhãn chính)
|
||
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)")
|
||
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 ""))
|
||
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, nhãn {lab1}: dự đoán tại giếng test", fontsize=11)
|
||
fig.savefig(outputs_dir() / "figures" / "p1_lowo.png", dpi=130)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|