Regenerate p2_phase, p2r_grid, p2r_h2b, bench_s1 and bench_s8 from the existing summaries so they use the paper's descriptive names, and remove the \figcodes notes and macro. Display fixes only: mathtext for the -5 dB label and a shorter anchor-mean cell label. Add a post hoc, descriptive table of the band content of the F3 labels, the synthetic labels and the Oracle predictions (scripts/40_band_spectra.py, Table tab:bandspectra in App. C) and rewrite the "Band of the benchmark" limitation. No number, verdict, threshold, locked protocol or abstract changed. Clean-room check rerun: 12/12 stages pass, nothing differs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
306 lines
15 KiB
Python
306 lines
15 KiB
Python
"""Journal-style figures for the manuscript (paper/figures/*.pdf), drawn from the locked summaries only.
|
||
|
||
python scripts/22_paper_figures.py [--only td_drift,h1,p2_phase,h2b,p2r_grid,f3_volume]
|
||
|
||
Reads: F3 wells (TD QC), outputs/p2/h1/, outputs/p2/summary/main/cells.csv, outputs/p2r/summary/{h2b,band_rmse}.csv,
|
||
outputs/p3/volume/{metadata.json,mean.npy,sigma.npy}, outputs/f3_wells.npz (well inline/crossline).
|
||
No titles or verdicts inside the figures (captions carry them); Computer Modern text to match the manuscript;
|
||
palette of ml_porosity.eval.figstyle (validated, colour-blind safe) on a white surface.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import importlib.util
|
||
|
||
import matplotlib
|
||
|
||
matplotlib.use("Agg")
|
||
import matplotlib as mpl
|
||
import matplotlib.pyplot as plt
|
||
import numpy as np
|
||
import pandas as pd
|
||
from matplotlib.colors import LinearSegmentedColormap, Normalize
|
||
from matplotlib.lines import Line2D
|
||
from matplotlib.patches import Rectangle
|
||
|
||
from ml_porosity.eval import figstyle as fs
|
||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||
|
||
FIG = REPO_ROOT / "paper" / "figures"
|
||
WIDTH = 6.3 # in; \textwidth of the manuscript (A4, 2.5 cm margins)
|
||
WHITE = "#ffffff"
|
||
SEQ_BLUE = LinearSegmentedColormap.from_list("seq_blue", ["#f0f5fc", "#86b6ef", "#2a78d6", "#104281"])
|
||
RAMP4 = ["#86b6ef", "#5598e7", "#256abf", "#104281"] # ordinal ramp for σ (as in scripts/13)
|
||
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
|
||
REGIME_LABELS = {"R10": "10 dB", "R0": "0 dB", "Rm5": r"$-5$ dB", "R0h": "half-anchor", "R10tb": "two-anchor"} # names used in the paper
|
||
METHODS = [("B3b", "Calibrated sonic"), ("B3c", "Correlation tie"), ("B3c-R", "Phase-est. correlation"), ("B3d", "Anchor mean"),
|
||
("B3d-Sa", "SMC mean"), ("M2-Sa", "SMC bank")]
|
||
METHOD_LABELS = {"B3a": "sonic", "B3b": "cal. sonic", "B3c": "corr. tie", "B3c-R": "phase corr.", "B3d": "anchor"} # short names in cells
|
||
|
||
|
||
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
|
||
|
||
|
||
def style() -> None:
|
||
fs.apply()
|
||
mpl.rcParams.update({
|
||
"figure.facecolor": WHITE, "axes.facecolor": WHITE, "savefig.facecolor": WHITE,
|
||
"font.family": "serif", "font.serif": ["cmr10"], "mathtext.fontset": "cm", "axes.unicode_minus": False,
|
||
"axes.formatter.use_mathtext": True, "font.size": 8, "axes.labelsize": 8, "xtick.labelsize": 7.5,
|
||
"ytick.labelsize": 7.5, "legend.fontsize": 7.5, "axes.titlesize": 8.5, "axes.titlelocation": "left",
|
||
"pdf.fonttype": 42, "lines.linewidth": 1.4,
|
||
})
|
||
|
||
|
||
def panel(ax, letter: str) -> None:
|
||
ax.set_title(f"({letter})", loc="left", fontsize=8.5, color=fs.INK, pad=4)
|
||
|
||
|
||
def text_on(rgba) -> str:
|
||
return fs.INK if 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2] > 0.55 else WHITE
|
||
|
||
|
||
def save(fig, name: str) -> None:
|
||
FIG.mkdir(parents=True, exist_ok=True)
|
||
fig.savefig(FIG / f"{name}.pdf", bbox_inches="tight", pad_inches=0.02)
|
||
plt.close(fig)
|
||
print("wrote", FIG / f"{name}.pdf")
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. TD drift (Section 3)
|
||
def td_drift() -> None:
|
||
from ml_porosity.data.las_io import F3_WELLS, load_td_source, load_well
|
||
from ml_porosity.data.tdr import TDR, legacy_sonic_tdr, misfit_at_anchors
|
||
|
||
src = [("legacy", "Integrated DT", fs.ORANGE, "o"), ("wlt", "OpendTect TD model", fs.BLUE, "s"),
|
||
("dt_model", "DT model", fs.AQUA, "^")]
|
||
fig, axes = plt.subplots(1, len(F3_WELLS), figsize=(WIDTH, 2.9), sharey=True, sharex=True)
|
||
for ax, name in zip(axes, F3_WELLS):
|
||
w = load_well(name)
|
||
cs = w.checkshot
|
||
tdrs = {"legacy": legacy_sonic_tdr(w.md, w.curve("DT")),
|
||
"wlt": TDR.from_pairs(load_td_source(name, "wlt"), drop_flat=True),
|
||
"dt_model": TDR.from_pairs(load_td_source(name, "dt_model"))}
|
||
ax.axhspan(600, 1100, color=fs.GRID, alpha=0.55, lw=0, zorder=0)
|
||
ax.axvline(0, color=fs.AXIS, lw=0.8, zorder=1)
|
||
for key, lab, col, mk in src:
|
||
ax.plot(misfit_at_anchors(tdrs[key], cs.md, cs.twt_ms), cs.twt_ms, marker=mk, ms=3, lw=1.1, color=col,
|
||
label=lab, zorder=3)
|
||
ax.set_title(name, loc="center", fontsize=8, color=fs.INK)
|
||
ax.set_xlabel("offset from marker (ms)")
|
||
axes[0].set_ylabel("marker TWT (ms)")
|
||
axes[0].set_ylim(1300, 400)
|
||
fig.legend(*axes[0].get_legend_handles_labels(), loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.06))
|
||
fig.tight_layout(rect=(0, 0.06, 1, 1), w_pad=0.6)
|
||
save(fig, "td_drift")
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. H1 (Section 4)
|
||
def h1() -> None:
|
||
s11, s12, s13 = load_script("11_run_d2.py"), load_script("12_h1_blur.py"), load_script("13_summarize_p2.py")
|
||
P = s11.load_protocol(check=True)
|
||
h = s13.h1_summary(P, s12)
|
||
f, tab = h["f"], h["table"]
|
||
fig, (ax, bx) = plt.subplots(1, 2, figsize=(WIDTH, 2.6), gridspec_kw={"width_ratios": [1.55, 1]})
|
||
sig = [s for s in sorted(h["use"]) if s > 0]
|
||
for s, col in zip(sig, RAMP4):
|
||
th, H, u = np.array(h["theory"][s]), np.array(h["H"][s]), h["use"][s]
|
||
ax.plot(f, th, color=col, lw=0.9, ls="--")
|
||
ax.plot(f[u], H[u], color=col, lw=1.5, marker="o", ms=2.2)
|
||
left = s == max(sig)
|
||
i = int(u.sum()) // 2 if left else -1
|
||
ax.annotate(rf"$\sigma = {s:g}$ ms", (f[u][i], H[u][i]), xytext=(7, 4) if left else (4, 0), textcoords="offset points",
|
||
va="center", ha="left", fontsize=7, color=fs.INK2, zorder=4,
|
||
bbox=dict(fc=WHITE, ec="none", pad=0.6, alpha=0.9))
|
||
ax.axvspan(0, 6, color=fs.GRID, alpha=0.7, lw=0)
|
||
ax.set(xlim=(0, 60), ylim=(-0.1, 1.15), xlabel="frequency (Hz)", ylabel="transfer function")
|
||
ax.legend(handles=[Line2D([], [], color=fs.INK2, lw=1.5, marker="o", ms=2.2, label=r"estimated $\hat H_\sigma(f)$"),
|
||
Line2D([], [], color=fs.INK2, lw=0.9, ls="--", label=r"$e^{-2\pi^2\sigma^2 f^2}$")],
|
||
loc="upper right")
|
||
panel(ax, "a")
|
||
s = tab.index[tab.index > 0]
|
||
bx.axhspan(0.5, 2.0, color=fs.GRID, alpha=0.7, lw=0)
|
||
bx.axhline(1.0, color=fs.AXIS, lw=0.9)
|
||
bx.vlines(s, tab.loc[s, "r_lo"], tab.loc[s, "r_hi"], color=fs.BLUE, lw=1.4)
|
||
bx.plot(s, tab.loc[s, "r"], "o", color=fs.BLUE, ms=4.5)
|
||
for x, r, n in zip(s, tab.loc[s, "r"], tab.loc[s, "n_freq"]):
|
||
bx.annotate(f"{r:.3f}\n({n} freq.)", (x, r), xytext=(0, 7), textcoords="offset points", ha="center",
|
||
va="bottom", fontsize=6.5, color=fs.INK2)
|
||
bx.set_xscale("log", base=2)
|
||
bx.set_yscale("log", base=2)
|
||
bx.set_xticks(list(s), [f"{x:g}" for x in s])
|
||
bx.set_yticks([0.5, 1, 2], ["0.5", "1", "2"])
|
||
bx.minorticks_off()
|
||
bx.set(xlim=(3, 45), ylim=(0.4, 2.5), xlabel=r"$\sigma$ (ms)", ylabel=r"$r(\sigma)$")
|
||
panel(bx, "b")
|
||
fig.tight_layout(w_pad=1.5)
|
||
save(fig, "p2_h1")
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. Experiment 1 (Section 6.1)
|
||
def p2_phase() -> None:
|
||
cells = pd.read_csv(outputs_dir() / "p2" / "summary" / "main" / "cells.csv")
|
||
cs, Ns = sorted(cells.c.unique()), sorted(cells.n_train.unique())
|
||
ix = cells.set_index(["c", "n_train"])
|
||
fig, axes = plt.subplots(1, 2, figsize=(WIDTH, 0.75 + 0.62 * len(cs)), layout="constrained")
|
||
panels = [("ratio", fs.diverging_norm(0.8, 1.0, 1.2), fs.DIVERGING, "{:.3f}", "{:.2f}", [0.90, 1.0], "band RMSE ratio"),
|
||
("dpcc", fs.diverging_norm(-0.1, 0.0, 0.1), fs.DIVERGING.reversed(), "{:+.3f}", "{:+.2f}", [0.0, 0.05],
|
||
"band PCC difference")]
|
||
for ax, (k, norm, cmap, fmt, fci, ticks, clabel), letter in zip(axes, panels, "ab"):
|
||
Z = ix[k].unstack("n_train").reindex(index=cs, columns=Ns).to_numpy()
|
||
im = ax.imshow(Z, cmap=cmap, norm=norm, origin="lower", aspect="auto")
|
||
for i, c in enumerate(cs):
|
||
for j, N in enumerate(Ns):
|
||
r = ix.loc[(c, N)]
|
||
col = text_on(cmap(norm(r[k])))
|
||
ax.text(j, i + 0.2, fmt.format(r[k]), ha="center", va="center", fontsize=7.5, color=col)
|
||
ax.text(j, i - 0.12, f"[{fci.format(r[k + '_lo'])}, {fci.format(r[k + '_hi'])}]", ha="center",
|
||
va="center", fontsize=6, color=col)
|
||
if k == "ratio":
|
||
ax.text(j, i - 0.36, f"{METHOD_LABELS.get(r.best, r.best)}, {'pass' if r.cell_pass else 'fail'}", ha="center", va="center",
|
||
fontsize=5.5, color=col)
|
||
ax.set_xticks(range(len(Ns)), [str(n) for n in Ns])
|
||
ax.set_yticks(range(len(cs)), [f"{c:g}" for c in cs])
|
||
ax.set(xlabel=r"training wells $N$", ylabel=r"drift factor $c$")
|
||
ax.grid(False)
|
||
for sp in ax.spines.values():
|
||
sp.set_visible(False)
|
||
ax.tick_params(length=0)
|
||
if 1.0 in cs:
|
||
ax.add_patch(Rectangle((-0.5, cs.index(1.0) - 0.5), len(Ns), 1, fill=False, ec=fs.INK, lw=1.2))
|
||
cb = fig.colorbar(im, ax=ax, shrink=0.9, extend="both", pad=0.02)
|
||
for t in ticks:
|
||
cb.ax.axhline(t, color=fs.INK, lw=0.9)
|
||
cb.set_label(clabel, color=fs.INK2)
|
||
cb.outline.set_visible(False)
|
||
panel(ax, letter)
|
||
save(fig, "p2_phase")
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. H2b (Section 6.3)
|
||
def h2b() -> None:
|
||
d = pd.read_csv(outputs_dir() / "p2r" / "summary" / "h2b.csv")
|
||
shapes = {0.0: "o", 1.0: "s", 2.0: "^"}
|
||
cols = {16: fs.BLUE, 4: fs.ORANGE}
|
||
fig, (ax, bx) = plt.subplots(1, 2, figsize=(WIDTH, 2.8))
|
||
for (N, c), g in d.groupby(["n_train", "c"]):
|
||
kw = dict(marker=shapes[c], s=26, zorder=3)
|
||
kw |= dict(color=cols[N], lw=0) if N == 16 else dict(facecolor="none", edgecolor=cols[N], lw=1.0)
|
||
ax.errorbar(g.sigma_post_ms, g.ratio, yerr=[g.ratio - g.ratio_lo, g.ratio_hi - g.ratio], fmt="none",
|
||
ecolor=cols[N], elinewidth=0.7, alpha=0.6, zorder=2)
|
||
ax.scatter(g.sigma_post_ms, g.ratio, **kw)
|
||
bx.scatter(g["bound_1/B"], g.ratio, **kw)
|
||
ax.axvline(1.5, color=fs.INK2, lw=0.8, ls="--")
|
||
ax.text(1.55, 0.62, "1.5 ms", fontsize=7, color=fs.INK2)
|
||
ax.axhline(1.0, color=fs.AXIS, lw=0.9)
|
||
ax.set_xscale("log")
|
||
ax.set_xticks([0.3, 0.5, 1, 2, 5, 10], ["0.3", "0.5", "1", "2", "5", "10"])
|
||
ax.minorticks_off()
|
||
ax.set(xlabel=r"posterior width $\sigma_{\mathrm{post}}$ (ms)", ylabel="band RMSE ratio, SMC bank / SMC mean",
|
||
ylim=(0.6, 1.05))
|
||
panel(ax, "a")
|
||
lo, hi = 0.6, 1.05
|
||
bx.plot([lo, hi], [lo, hi], color=fs.AXIS, lw=0.9)
|
||
bx.text(0.74, 0.695, "ratio = bound", rotation=45, rotation_mode="anchor", fontsize=7, color=fs.INK2)
|
||
bx.set(xlim=(lo, hi), ylim=(lo, hi), aspect="equal", xlabel=r"classical bound $\rho^\star_{\mathrm{cl}}(\sigma_{\mathrm{post}})$",
|
||
ylabel="band RMSE ratio, SMC bank / SMC mean")
|
||
panel(bx, "b")
|
||
handles = [Line2D([], [], ls="", marker="o", color=fs.BLUE, mew=0, label=r"$N = 16$"),
|
||
Line2D([], [], ls="", marker="o", mfc="none", mec=fs.ORANGE, label=r"$N = 4$")]
|
||
handles += [Line2D([], [], ls="", marker=m, color=fs.INK2, mfc="none", label=rf"$c = {c:g}$")
|
||
for c, m in shapes.items()]
|
||
fig.legend(handles=handles, loc="lower center", ncol=5, bbox_to_anchor=(0.5, -0.04))
|
||
fig.tight_layout(rect=(0, 0.06, 1, 1), w_pad=2.0)
|
||
save(fig, "p2r_h2b")
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. Experiment 2 overview (Section 6.3)
|
||
def p2r_grid() -> None:
|
||
d = pd.read_csv(outputs_dir() / "p2r" / "summary" / "band_rmse.csv")
|
||
d = d[d.setting.isin(REGIMES)]
|
||
cs = sorted(d.c.unique())
|
||
cols = [(r, c) for r in REGIMES for c in cs]
|
||
vals = []
|
||
for N in (4, 16):
|
||
t = d[d.n_train == N].set_index(["setting", "c"])
|
||
vals.append(np.array([[t.loc[(r, c), m] / t.loc[(r, c), "Oracle"] for r, c in cols] for m, _ in METHODS]))
|
||
norm = Normalize(1.0, 2.0) # R10tb at c = 2 reaches 3.2; clipped so that 1.0-1.6 stays readable
|
||
fig, axes = plt.subplots(2, 1, figsize=(WIDTH, 4.3), layout="constrained")
|
||
for ax, V, N, letter in zip(axes, vals, (4, 16), "ab"):
|
||
im = ax.imshow(V, cmap=SEQ_BLUE, norm=norm, aspect="auto")
|
||
for i in range(V.shape[0]):
|
||
for j in range(V.shape[1]):
|
||
ax.text(j, i, f"{V[i, j]:.2f}", ha="center", va="center", fontsize=6,
|
||
color=text_on(SEQ_BLUE(norm(V[i, j]))))
|
||
ax.set_yticks(range(len(METHODS)), [lab for _, lab in METHODS])
|
||
ax.set_xticks(range(len(cols)), [f"{c:g}" for _, c in cols])
|
||
sec = ax.secondary_xaxis("top")
|
||
sec.set_xticks([len(cs) * k + (len(cs) - 1) / 2 for k in range(len(REGIMES))], [REGIME_LABELS[r] for r in REGIMES])
|
||
sec.tick_params(length=0, labelsize=7.5, labelcolor=fs.INK)
|
||
sec.spines["top"].set_visible(False)
|
||
for k in range(1, len(REGIMES)):
|
||
ax.axvline(len(cs) * k - 0.5, color=WHITE, lw=2.5)
|
||
ax.grid(False)
|
||
for sp in ax.spines.values():
|
||
sp.set_visible(False)
|
||
ax.tick_params(length=0)
|
||
ax.set_xlabel(r"drift factor $c$")
|
||
ax.set_title(f"({letter}) $N = {N}$", loc="left", fontsize=8.5, color=fs.INK, pad=14)
|
||
cb = fig.colorbar(im, ax=axes, shrink=0.8, pad=0.01, extend="max")
|
||
cb.set_label("band RMSE / Oracle", color=fs.INK2)
|
||
cb.outline.set_visible(False)
|
||
save(fig, "p2r_grid")
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. F3 volume (Section 6.4)
|
||
def f3_volume(well: str = "F03-4") -> None:
|
||
import json
|
||
|
||
root = outputs_dir() / "p3" / "volume"
|
||
meta = json.loads((root / "metadata.json").read_text(encoding="utf-8"))
|
||
il, xl, t = (np.asarray(meta[k], float) for k in ("ilines", "xlines", "times_ms"))
|
||
with np.load(outputs_dir() / "f3_wells.npz") as z:
|
||
w_il, w_xl = int(z[f"{well}/il"]), int(z[f"{well}/xl"])
|
||
i = int(np.flatnonzero(il == w_il)[0])
|
||
fields = [100 * np.asarray(np.load(root / f"{k}.npy", mmap_mode="r")[i]) for k in ("mean", "sigma")] # (xline, t), p.u.
|
||
dt = t[1] - t[0]
|
||
extent = [xl[0] - 0.5, xl[-1] + 0.5, t[-1] + dt / 2, t[0] - dt / 2]
|
||
fig, axes = plt.subplots(1, 2, figsize=(WIDTH, 2.5), sharey=True, layout="constrained")
|
||
specs = [("viridis", np.nanpercentile(fields[0], [1, 99]), "both", "mean (p.u.)"),
|
||
(SEQ_BLUE, (0.0, np.nanpercentile(fields[1], 99)), "max", "standard deviation (p.u.)")]
|
||
for ax, v, (cmap, (lo, hi), ext, lab), letter in zip(axes, fields, specs, "ab"):
|
||
cm = (mpl.colormaps[cmap] if isinstance(cmap, str) else cmap).with_extremes(bad=WHITE)
|
||
im = ax.imshow(v.T, cmap=cm, vmin=lo, vmax=hi, aspect="auto", interpolation="nearest", extent=extent)
|
||
ax.axvline(w_xl, color=fs.INK, lw=0.8, ls=(0, (4, 2)))
|
||
ax.text(w_xl, t[0] - dt, well, ha="center", va="bottom", fontsize=7, color=fs.INK)
|
||
ax.grid(False)
|
||
ax.set_xlabel(f"crossline (inline {w_il})")
|
||
panel(ax, letter)
|
||
cb = fig.colorbar(im, ax=ax, pad=0.01, extend=ext)
|
||
cb.set_label(lab, color=fs.INK2)
|
||
cb.outline.set_visible(False)
|
||
axes[0].set_ylabel("TWT (ms)")
|
||
save(fig, "f3_volume")
|
||
|
||
|
||
FIGURES = {"td_drift": td_drift, "h1": h1, "p2_phase": p2_phase, "h2b": h2b, "p2r_grid": p2r_grid,
|
||
"f3_volume": f3_volume}
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--only", default="", help="comma-separated subset of " + ",".join(FIGURES))
|
||
args = ap.parse_args()
|
||
style()
|
||
for k in (args.only.split(",") if args.only else FIGURES):
|
||
FIGURES[k]()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|