- Benchmark summary: scripts/36_bench_verdicts.py applies the locked protocol_bench statements as worded (9/11 pass; S2-H1 fails for rock physics and wavelet phase), outside the lock hash. - S7 packaging: scripts/37_bench_package.py, benchmark/ (manifest, reference tables, README, draft Zenodo metadata). Deposit not done. - Paper: Experiment 3 (Sec. 6.5), T2 mechanism (Sec. 6.4), benchmark figures (scripts/38_bench_figures.py), dataset citations. - Proof review of Sec. 4 and App. A (14 of 15 findings fixed, 1 partly; no verdict or reported number changed); docs/theory.md synced. - Reproduction package: scripts/39_repro_package.py and repro/ (manifest, README, clean-room verify report: 12/12 stages pass). - Related work: preliminary novelty scan; full texts of AWSM, BootNet, Li et al. 2024, Guillon et al. 2020, Rizzuti et al. 2024/2025 and Castagna et al. 2026 checked; abstract-only markers updated and the Castagna sentence corrected. Paper compiles cleanly (68 pages). - Docs synced (AGENTS.md, plan.md, report.html, READMEs). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
170 lines
8.6 KiB
Python
170 lines
8.6 KiB
Python
"""Manuscript figures of Experiment 3 (protocol_bench, phase P6), drawn from the locked summary outputs only.
|
||
|
||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/38_bench_figures.py [--only bench_s1,bench_s8] [--flipband]
|
||
|
||
Outside the protocol_bench code hash (like scripts/36 and 37); checks the lock first and never writes under outputs/.
|
||
Reads outputs/bench/summary/s1_cells.csv (S1 phase diagram) and outputs/bench/summary/s8_transfer_curves.json; the
|
||
S8 usable band (Oracle cross-spectrum ≥ 0.1 × its maximum above 6 Hz) is recomputed from the S8 prediction files
|
||
exactly as ml_porosity/benchmark/summary.py does, because the curves file does not store it.
|
||
Style, palette and output folder are those of scripts/22_paper_figures.py (→ paper/figures/{bench_s1,bench_s8}.pdf).
|
||
--flipband prints (stdout only) the Section 6.5 S8 comparison: mean cos(πfΔ), mean cos²(πfΔ) (Corollary 3, the λ → 0
|
||
transfer of the equal-weight two-member bank, which contains the true warp but is not calibrated) and the measured
|
||
PM2/BK2/HM2 transfer over the usable frequencies of the band 1/(2Δ) < f < 3/(2Δ), for every S8 cell.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import importlib.util
|
||
import json
|
||
|
||
import numpy as np
|
||
import pandas as pd
|
||
from matplotlib.lines import Line2D
|
||
from matplotlib.patches import Rectangle
|
||
|
||
from ml_porosity.benchmark import summary as S
|
||
from ml_porosity.benchmark.cells import Cell, bench_root, train_paths
|
||
from ml_porosity.benchmark.protocol import freeze, load_protocol
|
||
from ml_porosity.eval import figstyle as fs
|
||
from ml_porosity.paths import REPO_ROOT
|
||
|
||
_spec = importlib.util.spec_from_file_location("s22", REPO_ROOT / "scripts" / "22_paper_figures.py")
|
||
F = importlib.util.module_from_spec(_spec) # style(), save(), text_on(), WIDTH of the other manuscript figures
|
||
_spec.loader.exec_module(F)
|
||
plt = F.plt
|
||
SUMMARY = bench_root(dev=False) / "summary"
|
||
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. S1 phase diagram (Section 6.5)
|
||
def bench_s1() -> None:
|
||
d = pd.read_csv(SUMMARY / "s1_cells.csv")
|
||
cs, Ns = sorted(d.c.unique()), sorted(d.n_train.unique())
|
||
norm, cmap = fs.diverging_norm(0.65, 1.0, 1.15), fs.DIVERGING
|
||
rows = [("pm_best", r"B3d-Sa / best point tie"), ("m2_pm", r"M2-Sa / B3d-Sa")]
|
||
fig, axes = plt.subplots(2, len(REGIMES), figsize=(F.WIDTH, 3.55), sharex=True, sharey=True, layout="constrained")
|
||
for i, (k, lab) in enumerate(rows):
|
||
for j, reg in enumerate(REGIMES):
|
||
ax = axes[i, j]
|
||
t = d[d.regime == reg].set_index(["c", "n_train"])
|
||
Z = t[f"{k}_ratio"].unstack("n_train").reindex(index=cs, columns=Ns).to_numpy()
|
||
im = ax.imshow(Z, cmap=cmap, norm=norm, origin="lower", aspect="auto")
|
||
for a, c in enumerate(cs):
|
||
for b, N in enumerate(Ns):
|
||
r = t.loc[(c, N)]
|
||
txt = f"{r[k + '_ratio']:.2f}"
|
||
ax.text(b, a, txt if r[k + "_better"] else f"({txt})", ha="center", va="center", fontsize=6,
|
||
color=F.text_on(cmap(norm(r[k + "_ratio"]))))
|
||
if k == "m2_pm" and r.sigma_post_ms >= 1.5:
|
||
ax.add_patch(Rectangle((b - 0.42, a - 0.42), 0.84, 0.84, fill=False, ec=fs.INK, lw=0.6))
|
||
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.grid(False)
|
||
for s in ax.spines.values():
|
||
s.set_visible(False)
|
||
ax.tick_params(length=0)
|
||
ax.set_title(f"({'ab'[i]}{j + 1}) {reg}", loc="left", fontsize=8, color=fs.INK, pad=3)
|
||
if i == 1:
|
||
ax.set_xlabel(r"wells $N$")
|
||
if j == 0:
|
||
ax.set_ylabel(r"drift factor $c$")
|
||
cb = fig.colorbar(im, ax=axes[i, :], shrink=0.95, pad=0.01, extend="both")
|
||
cb.ax.axhline(1.0, color=fs.INK, lw=0.9)
|
||
cb.set_label(lab, color=fs.INK2, fontsize=7)
|
||
cb.outline.set_visible(False)
|
||
F.save(fig, "bench_s1")
|
||
|
||
|
||
# ---------------------------------------------------------------- Fig. S8 two-mode transfer functions (Section 6.5)
|
||
def oracle_spectrum(p: dict, reg: str, d: float, N: int) -> tuple[np.ndarray, np.ndarray]:
|
||
"""Usable-frequency mask of an S8 cell, as in summary.s8 (Oracle cross-spectrum pooled over rids/seeds/wells)."""
|
||
f = np.fft.rfftfreq(S.NFFT, 4.0 / 1000.0)
|
||
b = S.study_budgets(p, "S8")["Oracle"]
|
||
so = np.zeros(len(f))
|
||
for rid in p["grid"]["realizations"]:
|
||
cell = Cell("S8", reg, None, 1.0, int(N), int(rid), tuple(p["studies"]["S8"]["methods"]), posterior="none",
|
||
delta_ms=float(d))
|
||
with np.load(train_paths(cell, bench_root(dev=False))["npz"]) as z:
|
||
Y = z["y_true"].astype(float)
|
||
for k in (k for k in z.files if k.startswith("Oracle/s") and k.endswith(f"/b{b}/mu")):
|
||
so += S.cross_spectrum(Y, z[k].astype(float))
|
||
band = f >= 6.0
|
||
return f, band & (so >= 0.1 * so[band].max())
|
||
|
||
|
||
STYLE_S8 = {"PM2": dict(lw=1.3, marker="o", ms=1.6), "BK2": dict(lw=1.8, marker="o", ms=2.0),
|
||
"HM2": dict(lw=0.9, ls=(0, (3, 1.5)))} # BK2 and HM2 nearly coincide: HM2 dashed on top
|
||
|
||
|
||
def bench_s8(N: int = 16) -> None:
|
||
p = load_protocol()
|
||
curves = [c for c in json.loads((SUMMARY / "s8_transfer_curves.json").read_text()) if c["n_train"] == N]
|
||
deltas = sorted({c["delta_ms"] for c in curves})
|
||
cols = {"PM2": fs.ORANGE, "BK2": fs.BLUE, "HM2": fs.AQUA}
|
||
fig, axes = plt.subplots(2, len(deltas), figsize=(F.WIDTH, 3.5), sharey=True, layout="constrained")
|
||
for i, reg in enumerate(["R10", "Rm5"]):
|
||
for j, d in enumerate(deltas):
|
||
ax = axes[i, j]
|
||
f, use = oracle_spectrum(p, reg, d, N)
|
||
fmax = f[use].max()
|
||
lo, hi = 1000.0 / (2 * d), 3000.0 / (2 * d)
|
||
ax.axvspan(lo, min(hi, fmax + 5), color=fs.GRID, alpha=0.7, lw=0)
|
||
ax.axhline(0.0, color=fs.AXIS, lw=0.8)
|
||
ax.plot(f, np.cos(np.pi * f * d / 1000.0), color=fs.INK2, lw=0.9, ls="--")
|
||
for m, col in cols.items():
|
||
c = next(c for c in curves if c["regime"] == reg and c["delta_ms"] == d and c["method"] == m)
|
||
H = np.where(use, np.asarray(c["H"], float), np.nan)
|
||
ax.plot(f, H, color=col, **STYLE_S8[m])
|
||
ax.set(xlim=(0, fmax + 5), ylim=(-1.4, 1.6))
|
||
ax.set_title(f"({'ab'[i]}{j + 1}) {reg}, " + rf"$\Delta = {d:g}$ ms", loc="left", fontsize=8, color=fs.INK, pad=3)
|
||
if i == 1:
|
||
ax.set_xlabel("frequency (Hz)")
|
||
if j == 0:
|
||
ax.set_ylabel(r"transfer $\hat H(f)$ vs. Oracle")
|
||
handles = [Line2D([], [], color=col, label=m, **STYLE_S8[m]) for m, col in cols.items()]
|
||
handles.append(Line2D([], [], color=fs.INK2, lw=0.9, ls="--", label=r"$\cos(\pi f \Delta)$"))
|
||
fig.legend(handles=handles, loc="outside lower center", ncol=4)
|
||
F.save(fig, "bench_s8")
|
||
|
||
|
||
def flipband() -> None:
|
||
p = load_protocol()
|
||
curves = json.loads((SUMMARY / "s8_transfer_curves.json").read_text())
|
||
print("regime delta_ms N n_freq mean_cos mean_cos2 PM2 BK2 HM2")
|
||
for reg in ["R10", "Rm5"]:
|
||
for d in sorted({c["delta_ms"] for c in curves}):
|
||
for N in sorted({c["n_train"] for c in curves}):
|
||
f, use = oracle_spectrum(p, reg, d, N)
|
||
fl = use & (f > 1000.0 / (2 * d)) & (f < 3000.0 / (2 * d))
|
||
if not fl.any():
|
||
print(f"{reg:6s} {d:8g} {N:2d} {0:6d} (no usable frequency in the band)")
|
||
continue
|
||
c = np.cos(np.pi * f[fl] * d / 1000.0)
|
||
H = {m: np.asarray(next(x for x in curves if x["regime"] == reg and x["delta_ms"] == d
|
||
and x["n_train"] == N and x["method"] == m)["H"], float)[fl].mean()
|
||
for m in ("PM2", "BK2", "HM2")}
|
||
print(f"{reg:6s} {d:8g} {N:2d} {int(fl.sum()):6d} {c.mean():8.3f} {(c ** 2).mean():9.3f} "
|
||
+ " ".join(f"{H[m]:5.3f}" for m in ("PM2", "BK2", "HM2")))
|
||
|
||
|
||
FIGURES = {"bench_s1": bench_s1, "bench_s8": bench_s8}
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--only", default="", help="comma-separated subset of " + ",".join(FIGURES))
|
||
ap.add_argument("--flipband", action="store_true", help="print the S8 flip-band table instead of drawing")
|
||
args = ap.parse_args()
|
||
freeze(check=True)
|
||
if args.flipband:
|
||
flipband()
|
||
return
|
||
F.style()
|
||
for k in (args.only.split(",") if args.only else FIGURES):
|
||
FIGURES[k]()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|