Address simulated GP referee reports: E1-E6 and A1-A9 (exploratory), theory scope, per-well field and anchor-error tables, scorer v1.1, paper_gp and response letter
Experiments declared and hashed before computing (docs/research/gp-review-*.md). The SMC-mean gain holds against a practitioner tie, all budgets and a same-target point tie, but is lost at anchor errors of 2 ms or less and reverses with per-well bulk error. No locked protocol, verdict or threshold changed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
269
scripts/19_paper_figures.py
Normal file
269
scripts/19_paper_figures.py
Normal file
@@ -0,0 +1,269 @@
|
||||
"""Journal-style figures for the manuscript (paper/figures/*.pdf), drawn from the locked summaries only.
|
||||
|
||||
python scripts/19_paper_figures.py [--only td_drift,h1,p2_phase,h2b,p2r_grid]
|
||||
|
||||
Reads: F3 wells (TD QC), outputs/p2/h1/, outputs/p2/summary/main/cells.csv, outputs/p2r/summary/{h2b,band_rmse}.csv.
|
||||
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"]
|
||||
METHODS = [("B3b", "B3b"), ("B3c", "B3c"), ("B3c-R", "B3c-R"), ("B3d", "B3d"), ("B3d-Sa", "B3d-Sa"), ("M2-Sa", "M2-Sa")]
|
||||
|
||||
|
||||
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"{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, M2-Sa / B3d-Sa",
|
||||
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"deblurring bound $1/B(\sigma_{\mathrm{post}})$",
|
||||
ylabel="band RMSE ratio, M2-Sa / B3d-Sa")
|
||||
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))], 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")
|
||||
|
||||
|
||||
FIGURES = {"td_drift": td_drift, "h1": h1, "p2_phase": p2_phase, "h2b": h2b, "p2r_grid": p2r_grid}
|
||||
|
||||
|
||||
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()
|
||||
@@ -23,12 +23,15 @@ score Predictions <pred>/<split>/<setting>/r{rid}_c{c}_n{N}_s{seed}.npz with
|
||||
(8, 126), porosity in p.u., test wells in task order. Metrics are those of the runner (scripts/11 evaluate).
|
||||
On the test split the locked rules of ml_porosity/benchmark/summary.py are applied per cell: the H2a cell
|
||||
rule against the best point tie {B3b, B3c, B3c-R}, and the `better` rule against B3d-Sa, M2-Sa, Oracle
|
||||
(PM2, BK2, Oracle in the two-mode settings). Reference rows are restricted to the submitted realizations and
|
||||
seeds. Bootstrap CIs use one generator (rng 0) per cell, so they can differ slightly from the summary
|
||||
tables; no rule uses a CI. → <pred>/score/
|
||||
(PM2, BK2, Oracle in the two-mode settings). Scorer v1.1 (17/11/2026, after the Geophysical Prospecting
|
||||
review) adds the anchor mean B3d: the same H2a cell rule against the best of {B3b, B3c, B3c-R, B3d}
|
||||
(rule_point_ties_anchor.csv; only the nominal settings have B3d) and the `better` rule against B3d. The v1
|
||||
outputs are unchanged and no task file or hash changed. Reference rows are restricted to the submitted
|
||||
realizations and seeds. Bootstrap CIs use one generator (rng 0) per cell, so they can differ slightly from
|
||||
the summary tables; no rule uses a CI. → <pred>/score/
|
||||
selftest Writes saved predictions of reference methods as a submission (S1 R10 c = 1.5, S2 R10 wv_L1, P2r R10 c = 1,
|
||||
S8 R10 Δ = 16), scores it, and checks that metrics and rule outputs equal those of the reference runs and
|
||||
that the package truth equals the y_true saved by the runner.
|
||||
that the package truth equals the y_true saved by the runner; v1.1 also checks the anchor-mean rule.
|
||||
check Recomputes the content hashes of DIR against benchmark/MANIFEST.json (for a downloaded copy).
|
||||
|
||||
Outside the code hash of the protocol_bench lock (scripts/34 and ml_porosity/ only); generate and tables check the
|
||||
@@ -64,6 +67,8 @@ RUN = ["setting", "c", "n_train", "rid", "seed", "method"]
|
||||
PRED = re.compile(r"r(\d+)_c([\d.]+)_n(\d+)_s(\d+)")
|
||||
WIDE_MS = 1.5 # rules.wide of protocol_bench
|
||||
N_BOOT = 2000
|
||||
SCORER_VERSION = "1.1" # 1.0: 02/11/2026; 1.1: anchor mean B3d added as a competitor (17/11/2026)
|
||||
ANCHOR_TIES = [*S.POINT_TIES, "B3d"]
|
||||
SIGMA_A_STRESS = (3.5, 14.0) # σ_a stated in the task file of the settings R10__sa3.5 and R10__sa14 (true value 7 ms)
|
||||
|
||||
|
||||
@@ -204,7 +209,7 @@ def generate(a) -> None:
|
||||
"'key|dtype|shape|' then the C-order bytes (scripts/37_bench_package.py content_sha)",
|
||||
"inputs": {f"inputs/{f.name}": file_sha(f) for f in sorted(src.iterdir()) if f.name != "analyst.json"},
|
||||
"splits": {sp: rids[sp] for sp in sorted(set(old.get("splits", {})) | set(a.split))},
|
||||
"n_tasks": int(len(idx)), "files": dict(sorted((keep | files).items()))}
|
||||
"scorer_version": SCORER_VERSION, "n_tasks": int(len(idx)), "files": dict(sorted((keep | files).items()))}
|
||||
(out / "MANIFEST.json").write_text(json.dumps(man, indent=1))
|
||||
ref = DOC / "MANIFEST.json"
|
||||
if ref.exists() and not a.update_manifest:
|
||||
@@ -346,8 +351,8 @@ def read_predictions(pred: Path, pkg: Path, name: str, f_c: float) -> pd.DataFra
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def rule_tables(run: pd.DataFrame, ref: pd.DataFrame, name: str) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
|
||||
rules, pairs, means = [], [], []
|
||||
def rule_tables(run: pd.DataFrame, ref: pd.DataFrame, name: str) -> tuple[pd.DataFrame, ...]:
|
||||
rules, anch, pairs, means = [], [], [], []
|
||||
for (setting, c, N), sub in run.groupby(CELL):
|
||||
r = ref[(ref.setting == setting) & (ref.c == c) & (ref.n_train == N) & ref.rid.isin(sub.rid) & ref.seed.isin(sub.seed)]
|
||||
both = pd.concat([sub[RUN + S.METRICS], r[RUN + S.METRICS]], ignore_index=True)
|
||||
@@ -356,14 +361,18 @@ def rule_tables(run: pd.DataFrame, ref: pd.DataFrame, name: str) -> tuple[pd.Dat
|
||||
if set(S.POINT_TIES) <= set(r.method):
|
||||
cells = S.h2a_cells(both, name, S.POINT_TIES, np.random.default_rng(0), N_BOOT)
|
||||
rules.append(cells.drop(columns=["c", "n_train", "n_rid", "n_seed"]).assign(**key))
|
||||
for m in ("B3d-Sa", "M2-Sa", "PM2", "BK2", "Oracle"):
|
||||
if set(ANCHOR_TIES) <= set(r.method): # v1.1: anchor mean among the competitors
|
||||
cells = S.h2a_cells(both, name, ANCHOR_TIES, np.random.default_rng(0), N_BOOT)
|
||||
anch.append(cells.drop(columns=["c", "n_train", "n_rid", "n_seed"]).assign(**key))
|
||||
for m in ("B3d-Sa", "M2-Sa", "B3d", "PM2", "BK2", "Oracle"):
|
||||
if m in set(r.method):
|
||||
d = S.pair(both, name, m, np.random.default_rng(0), N_BOOT)
|
||||
pairs.append(key | {"reference": m} | d)
|
||||
first = lambda df, cols: df[[*cols, *[k for k in df.columns if k not in cols]]] if len(df) else df
|
||||
k = ["setting", "c", "n_train", "n_rid", "n_seed"]
|
||||
rules = pd.concat(rules, ignore_index=True) if rules else pd.DataFrame()
|
||||
return first(rules, k), first(pd.DataFrame(pairs), k + ["reference"]), first(pd.DataFrame(means), k)
|
||||
anch = pd.concat(anch, ignore_index=True) if anch else pd.DataFrame()
|
||||
return first(rules, k), first(anch, k), first(pd.DataFrame(pairs), k + ["reference"]), first(pd.DataFrame(means), k)
|
||||
|
||||
|
||||
def score(a) -> None:
|
||||
@@ -379,33 +388,42 @@ def score(a) -> None:
|
||||
well.to_csv(out / "per_well.csv", index=False)
|
||||
run.to_csv(out / "runs.csv", index=False)
|
||||
test = run[run.split == "test"].drop(columns="split")
|
||||
L = [f"# Score of `{a.name}` (scripts/37_bench_package.py score)", "",
|
||||
L = [f"# Score of `{a.name}` (scripts/37_bench_package.py score, scorer v{SCORER_VERSION})", "",
|
||||
f"{len(well.groupby(['split', *RUN]))} predictions; test split: {len(test)} runs in {test.groupby(CELL).ngroups} cells.",
|
||||
"Rules: protocol_bench (improves: band RMSE ≤ 0.90 × best point tie or band PCC ≥ +0.05; cell_pass: ≥ 4/5 seeds "
|
||||
"and > 1/2 of realizations; better: lower band RMSE in ≥ 4/5 seeds and > 1/2 of realizations).", ""]
|
||||
if len(test):
|
||||
rules, pairs, means = rule_tables(test, ref, a.name)
|
||||
for f, df in (("rule_point_ties.csv", rules), ("pairs.csv", pairs), ("cells.csv", means)):
|
||||
rules, anch, pairs, means = rule_tables(test, ref, a.name)
|
||||
for f, df in (("rule_point_ties.csv", rules), ("rule_point_ties_anchor.csv", anch), ("pairs.csv", pairs),
|
||||
("cells.csv", means)):
|
||||
df.to_csv(out / f, index=False)
|
||||
complete = lambda df: df[(df.n_rid == 8) & (df.n_seed == 5)] if len(df) else df
|
||||
if len(rules):
|
||||
rc = complete(rules)
|
||||
L += [f"- H2a cell rule vs best point tie: {int(rules.cell_pass.sum())}/{len(rules)} cells pass "
|
||||
f"({int(rc.cell_pass.sum())}/{len(rc)} among complete cells: 8 realizations × 5 seeds)."]
|
||||
for m in ("B3d-Sa", "M2-Sa", "PM2", "BK2", "Oracle"):
|
||||
if len(anch):
|
||||
ac = complete(anch)
|
||||
L += [f"- v1.1 H2a cell rule vs best of point ties and anchor mean B3d: {int(anch.cell_pass.sum())}/{len(anch)} "
|
||||
f"cells pass ({int(ac.cell_pass.sum())}/{len(ac)} among complete cells; nominal settings only)."]
|
||||
for m in ("B3d-Sa", "M2-Sa", "B3d", "PM2", "BK2", "Oracle"):
|
||||
q = pairs[pairs.reference == m] if len(pairs) else pairs
|
||||
if len(q):
|
||||
L += [f"- better than {m}: {int(q.better.sum())}/{len(q)} cells; median ratio {q.ratio.median():.3f}."]
|
||||
L += ["", "| setting | c | N | n_rid × n_seed | ratio vs best point tie (best) | cell_pass | ratio vs B3d-Sa |",
|
||||
"|---|---|---|---|---|---|---|"]
|
||||
L += ["", "| setting | c | N | n_rid × n_seed | ratio vs best point tie (best) | cell_pass | "
|
||||
"ratio vs best of point ties and B3d (best) | cell_pass (v1.1) | ratio vs B3d-Sa |",
|
||||
"|---|---|---|---|---|---|---|---|---|"]
|
||||
rr = rules.set_index(CELL) if len(rules) else None
|
||||
ra = anch.set_index(CELL) if len(anch) else None
|
||||
pb = pairs[pairs.reference == "B3d-Sa"].set_index(CELL) if len(pairs) else None
|
||||
for row in means.itertuples():
|
||||
k = (row.setting, row.c, row.n_train)
|
||||
h = f"{rr.loc[k, 'ratio']:.3f} ({rr.loc[k, 'best']})" if rr is not None and k in rr.index else "—"
|
||||
cp = str(bool(rr.loc[k, "cell_pass"])) if rr is not None and k in rr.index else "—"
|
||||
ha = f"{ra.loc[k, 'ratio']:.3f} ({ra.loc[k, 'best']})" if ra is not None and k in ra.index else "—"
|
||||
ca = str(bool(ra.loc[k, "cell_pass"])) if ra is not None and k in ra.index else "—"
|
||||
b = f"{pb.loc[k, 'ratio']:.3f}" if pb is not None and k in pb.index else "—"
|
||||
L.append(f"| {row.setting} | {row.c:g} | {row.n_train} | {row.n_rid} × {row.n_seed} | {h} | {cp} | {b} |")
|
||||
L.append(f"| {row.setting} | {row.c:g} | {row.n_train} | {row.n_rid} × {row.n_seed} | {h} | {cp} | {ha} | {ca} | {b} |")
|
||||
dev = run[run.split == "dev"]
|
||||
if len(dev):
|
||||
L += ["", f"Dev split: {len(dev)} runs, metrics only (runs.csv); dev labels may be used for design."]
|
||||
@@ -448,6 +466,7 @@ def selftest(a) -> None:
|
||||
ref = pd.read_csv(pkg / "reference" / "runs.csv.gz")
|
||||
got = pd.read_csv(sub / "score" / "runs.csv")
|
||||
rules = pd.read_csv(sub / "score" / "rule_point_ties.csv")
|
||||
anch = pd.read_csv(sub / "score" / "rule_point_ties_anchor.csv")
|
||||
pairs = pd.read_csv(sub / "score" / "pairs.csv")
|
||||
msg, ok = [f"max |y_true(runner, float32) − y_test(package)| = {worst_y:.2e} p.u."], worst_y < 1e-4
|
||||
for setting, _, _, c, m in SELFTEST:
|
||||
@@ -464,6 +483,11 @@ def selftest(a) -> None:
|
||||
have = rules[(rules.setting == setting) & (rules.c == c) & (rules.n_train == N)].iloc[0]
|
||||
same = want.best == have.best and bool(want.cell_pass) == bool(have.cell_pass) and abs(want.ratio - have.ratio) < 1e-4
|
||||
line += f"; N={N} ratio {have.ratio:.4f} vs {want.ratio:.4f} ({want.best}, pass {bool(want.cell_pass)})"
|
||||
if set(ANCHOR_TIES) <= set(cr.method): # v1.1 anchor-mean rule
|
||||
wa = S.h2a_cells(cr, m, ANCHOR_TIES, np.random.default_rng(0), N_BOOT).iloc[0]
|
||||
ha = anch[(anch.setting == setting) & (anch.c == c) & (anch.n_train == N)].iloc[0]
|
||||
same &= wa.best == ha.best and bool(wa.cell_pass) == bool(ha.cell_pass) and abs(wa.ratio - ha.ratio) < 1e-4
|
||||
line += f" | v1.1 {ha.ratio:.4f} vs {wa.ratio:.4f} ({wa.best}, pass {bool(wa.cell_pass)})"
|
||||
else:
|
||||
want = S.pair(cr, m, "PM2", np.random.default_rng(0), N_BOOT)
|
||||
have = pairs[(pairs.setting == setting) & (pairs.c == c) & (pairs.n_train == N) & (pairs.reference == "PM2")].iloc[0]
|
||||
@@ -472,7 +496,7 @@ def selftest(a) -> None:
|
||||
ok &= same
|
||||
msg.append(line)
|
||||
print("\n".join(msg))
|
||||
(pkg / "selftest.json").write_text(json.dumps({"pass": bool(ok), "checks": msg}, indent=1))
|
||||
(pkg / "selftest.json").write_text(json.dumps({"pass": bool(ok), "scorer_version": SCORER_VERSION, "checks": msg}, indent=1))
|
||||
shutil.rmtree(sub)
|
||||
if not ok:
|
||||
raise SystemExit("selftest FAILED")
|
||||
|
||||
@@ -42,7 +42,7 @@ 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"SMC mean / best point tie"), ("m2_pm", r"SMC bank / SMC mean")]
|
||||
rows = [("pm_best", r"SMC mean / best deterministic tie"), ("m2_pm", r"SMC bank / SMC mean")]
|
||||
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):
|
||||
|
||||
85
scripts/50_ref_overlap.py
Normal file
85
scripts/50_ref_overlap.py
Normal file
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline word n-gram overlap between the manuscript prose and the reference PDFs in refs/.
|
||||
|
||||
Nothing leaves the machine. Prose of paper/sections/*.tex and paper_gp/main.tex (math, citation and
|
||||
reference commands removed) is compared with the text of every distinct PDF in refs/ (PyMuPDF; line-end
|
||||
hyphenation joined). Runs of shared word n-grams are merged into spans and written, longest first, to
|
||||
outputs/ref_overlap/overlap_n<N>.json. Only near-verbatim reuse is found, and only against refs/ (PDFs
|
||||
listed in refs/MISSING.md are not checked). Not a substitute for iThenticate.
|
||||
|
||||
python scripts/50_ref_overlap.py [N] # default N = 8
|
||||
"""
|
||||
import glob, hashlib, json, os, re, sys, warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
import fitz
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
N = int(sys.argv[1]) if len(sys.argv) > 1 else 8
|
||||
OUT = os.path.join(REPO, "outputs", "ref_overlap")
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
def tex_to_text(s):
|
||||
s = re.sub(r"(?<!\\)%.*", "", s)
|
||||
s = re.sub(r"\\begin\{(equation|align|gather|multline|eqnarray|displaymath)\*?\}.*?\\end\{\1\*?\}", " MATH ", s, flags=re.S)
|
||||
s = re.sub(r"\\\[.*?\\\]", " MATH ", s, flags=re.S)
|
||||
s = re.sub(r"(?<!\\)\$.+?(?<!\\)\$", " MATH ", s, flags=re.S)
|
||||
s = re.sub(r"\\(cite[a-z]*|ref|eqref|label|Sref|includegraphics|input|url|href|todo)\*?(\[[^\]]*\])*\{[^}]*\}", " ", s)
|
||||
s = re.sub(r"\\[a-zA-Z]+\*?", " ", s)
|
||||
s = re.sub(r"[{}\[\]~&\\]", " ", s)
|
||||
return s
|
||||
|
||||
def words(s):
|
||||
s = s.replace("\u2010", "-").replace("\u2011", "-").replace("\ufb01", "fi").replace("\ufb02", "fl")
|
||||
s = re.sub(r"(\w)-\s*\n\s*(\w)", r"\1\2", s) # de-hyphenate line breaks
|
||||
return re.findall(r"[a-z0-9]+", s.lower())
|
||||
|
||||
# manuscript: full sections + GP article (prose); keep line numbers for reporting
|
||||
docs = {}
|
||||
for p in sorted(glob.glob(f"{REPO}/paper/sections/*.tex")) + [f"{REPO}/paper_gp/main.tex"]:
|
||||
raw = open(p, encoding="utf-8").read()
|
||||
if p.endswith("paper_gp/main.tex"):
|
||||
raw = re.sub(r".*?\\begin\{document\}", "", raw, flags=re.S)
|
||||
docs[os.path.relpath(p, REPO)] = words(tex_to_text(raw))
|
||||
|
||||
# references: dedupe by text hash
|
||||
refs, seen = {}, {}
|
||||
for p in sorted(glob.glob(f"{REPO}/refs/*.pdf")):
|
||||
try:
|
||||
t = "\n".join(pg.get_text() for pg in fitz.open(p))
|
||||
except Exception as e:
|
||||
print("skip", p, e); continue
|
||||
w = words(t)
|
||||
h = hashlib.sha1(" ".join(w[:2000]).encode()).hexdigest()
|
||||
if h in seen:
|
||||
continue
|
||||
seen[h] = p
|
||||
refs[os.path.basename(p)] = w
|
||||
print(f"{len(refs)} distinct reference texts; n = {N}")
|
||||
|
||||
index = {}
|
||||
for name, w in refs.items():
|
||||
for i in range(len(w) - N + 1):
|
||||
index.setdefault(tuple(w[i:i + N]), set()).add(name)
|
||||
|
||||
results = []
|
||||
for d, w in docs.items():
|
||||
hit = [index.get(tuple(w[i:i + N])) for i in range(len(w) - N + 1)]
|
||||
i = 0
|
||||
while i < len(hit):
|
||||
if hit[i]:
|
||||
j = i; src = set(hit[i])
|
||||
while j + 1 < len(hit) and hit[j + 1]:
|
||||
j += 1; src |= hit[j]
|
||||
span = w[i:j + N]
|
||||
results.append(dict(doc=d, nwords=len(span), text=" ".join(span), sources=sorted(src)))
|
||||
i = j + 1
|
||||
else:
|
||||
i += 1
|
||||
results.sort(key=lambda r: -r["nwords"])
|
||||
json.dump(results, open(f"{OUT}/overlap_n{N}.json", "w"), indent=1)
|
||||
tot = {d: sum(r["nwords"] for r in results if r["doc"] == d) for d in docs}
|
||||
for d in docs:
|
||||
print(f"{d}: {len(docs[d])} words, {tot[d]} in matched spans ({100*tot[d]/max(1,len(docs[d])):.2f}%)")
|
||||
print(f"\n{len(results)} spans; longest first:")
|
||||
for r in results[:60]:
|
||||
print(f"[{r['nwords']}] {r['doc']} <- {', '.join(r['sources'])}\n {r['text']}")
|
||||
1015
scripts/51_gp_review.py
Normal file
1015
scripts/51_gp_review.py
Normal file
File diff suppressed because it is too large
Load Diff
548
scripts/52_gp_experiments.py
Normal file
548
scripts/52_gp_experiments.py
Normal file
@@ -0,0 +1,548 @@
|
||||
"""GP review, Phase 3: experiments E4, E5, E6 (and E3 if A3 is not sufficient). Declared in
|
||||
docs/research/gp-review-experiments.md and hashed before the first run; exploratory; outside every lock and the
|
||||
reproduction archives. The locked scripts 14, 15, 18 and 32 are imported unchanged; the only in-process replacement is
|
||||
the budget list of `train_predict` in the E6 workers (as declared). E2 and E1 live in scripts 53 and 54.
|
||||
|
||||
E4 point tie optimizing the SMC target (L-BFGS-B from the 4 best saved particles), labels at the optimum, NLL, 250
|
||||
E5 posterior-mean labels (64-member bank mean; 1024-particle mean) trained with the Gaussian likelihood
|
||||
E6 the seven registered methods of Experiment 2 at 125/250/500 iterations (equal budget)
|
||||
|
||||
.venv/bin/python scripts/52_gp_experiments.py --stage e5 --workers 5 --device cuda:0
|
||||
.venv/bin/python scripts/52_gp_experiments.py --stage e6 --workers 5 --device cuda:0
|
||||
.venv/bin/python scripts/52_gp_experiments.py --stage e4 --workers 4 --device cuda:0
|
||||
.venv/bin/python scripts/52_gp_experiments.py --stage summary # -> outputs/gp_review/e{4,5,6}/summary.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
t2 = load_script("32_t2_mechanism.py")
|
||||
ci = load_script("43_referee_r5_ci.py")
|
||||
run_d2 = t2.run_d2
|
||||
|
||||
DECL = REPO_ROOT / "docs" / "research" / "gp-review-experiments.md"
|
||||
DECL_HASH = REPO_ROOT / "docs" / "research" / "gp-review-experiments.sha256"
|
||||
OUT = outputs_dir() / "gp_review"
|
||||
P2R = outputs_dir() / "p2r"
|
||||
LAMLIM = outputs_dir() / "lambda_limit"
|
||||
POINT_TIE = outputs_dir() / "point_tie"
|
||||
RIDS = list(range(8, 16))
|
||||
SEEDS = [0, 1, 2, 3, 4]
|
||||
H2A_REGIMES, CS, NS = ["R10", "R0", "Rm5"], [0.0, 1.0], [4, 16]
|
||||
E_BUDGETS = [125, 250, 500]
|
||||
PRIMARY = 250
|
||||
REG_BUD = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250}
|
||||
SEVEN = list(REG_BUD)
|
||||
POINT = ["B3b", "B3c", "B3c-R"]
|
||||
WIDE = [(r, c) for r, c in t2.WIDE16]
|
||||
NARROW = [(r, c) for r, c in t2.NARROW16]
|
||||
N_BOOT = 2000
|
||||
|
||||
|
||||
def check_declaration() -> str:
|
||||
expected = DECL_HASH.read_text().split()[0]
|
||||
actual = hashlib.sha256(DECL.read_bytes()).hexdigest()
|
||||
if actual != expected:
|
||||
raise SystemExit(f"{DECL.name} differs from its recorded SHA-256 ({actual[:12]} != {expected[:12]})")
|
||||
return actual
|
||||
|
||||
|
||||
def set_threads(n: int = 2) -> None:
|
||||
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
|
||||
os.environ.setdefault(k, str(n))
|
||||
|
||||
|
||||
def bank(Y, logpi, lam) -> dict:
|
||||
return {"kind": "bank", "Y": np.asarray(Y, np.float32), "logpi": np.asarray(logpi, np.float32), "lam": lam}
|
||||
|
||||
|
||||
def score_rows(cell, key, m, preds, s0, m0, f_c) -> list[dict]:
|
||||
rows = []
|
||||
for b, (mu, sg) in preds.items():
|
||||
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
|
||||
for wt, r in zip(cell["R"].test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)):
|
||||
rows.append(key | {"method": m, "budget": b, "test_well": wt.name} | r)
|
||||
return rows
|
||||
|
||||
|
||||
def run_pool(fn, jobs, workers: int, label: str) -> None:
|
||||
print(f"{label}: {len(jobs)} jobs, {workers} workers", flush=True)
|
||||
if not jobs:
|
||||
return
|
||||
t0 = time.time()
|
||||
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
|
||||
futs = {ex.submit(fn, j): j[:4] for j in jobs}
|
||||
for i, f in enumerate(as_completed(futs), 1):
|
||||
stem, dt = f.result()
|
||||
print(f"[{i}/{len(jobs)}] {stem} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# E5: posterior-mean labels with the Gaussian likelihood
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def e5_job(job) -> tuple[str, float]:
|
||||
regime, rid, c, N, seeds, device, out_dir, P = job
|
||||
import torch
|
||||
|
||||
torch.set_num_threads(2)
|
||||
from ml_porosity.models.bank_train import train_predict
|
||||
|
||||
t0 = time.time()
|
||||
cell = t2.build_cell(regime, rid, c, N, P, with_register=True)
|
||||
out, wells = cell["out"], cell["wells"]
|
||||
stem = t2.tag(regime, rid, c, N)
|
||||
key = dict(regime=regime, rid=rid, c=c, n_train=N)
|
||||
m0, s0 = out["norm"]
|
||||
lam = out["lam"]
|
||||
tcfg = P["training"]["model"] | P["training"]["optimizer"]
|
||||
f_c = P["metrics"]["bands"]["f_c_hz"]
|
||||
nb = lambda a: ((np.asarray(a, np.float64) - m0) / s0).astype(np.float32)
|
||||
|
||||
Y_pm = nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])) # B3d-Sa: label at the mean warp
|
||||
Y_rml = nb(np.stack([w["Y"] for w in wells])) # (N, 64, L) M2-Sa bank
|
||||
logpi = np.stack([w["logpi"] for w in wells]).astype(np.float64)
|
||||
Y_mean = (Y_rml.astype(np.float64) * np.exp(logpi)[:, :, None]).sum(1) # label of Mean-MSE (scripts/41)
|
||||
diag, Y_1024 = [], []
|
||||
for w in wells:
|
||||
Yall = cell["lab"](w["y_aa"], w["Tf"]) # (1024, L), all saved particles
|
||||
ok = np.all(np.isfinite(Yall), 1)
|
||||
y1024 = Yall[ok].mean(0)
|
||||
Y_1024.append(y1024)
|
||||
ypm = cell["lab"](w["y_aa"], w["tm"])[0]
|
||||
y64 = Y_mean[w["i"]] * s0 + m0
|
||||
rms = lambda a, b: float(100 * np.sqrt(np.mean((a - b) ** 2)))
|
||||
diag.append(key | {"well": w["name"], "n_valid_1024": int(ok.sum()), "n_valid_64": int(w["ok"].sum()),
|
||||
"rms_mean64_vs_pm_pu": rms(y64, ypm), "rms_mean1024_vs_pm_pu": rms(y1024, ypm),
|
||||
"rms_mean64_vs_mean1024_pu": rms(y64, y1024)})
|
||||
Y_1024 = nb(np.stack(Y_1024))
|
||||
z1 = np.zeros((N, 1))
|
||||
specs = {"Mean-NLL": bank(Y_mean[:, None, :], z1, lam), "Mean-NLL-1024": bank(Y_1024[:, None, :], z1, lam),
|
||||
"B3d-Sa": bank(Y_pm, z1, lam)}
|
||||
rows = []
|
||||
for seed in seeds:
|
||||
for m, sp in specs.items():
|
||||
preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, E_BUDGETS, device)
|
||||
rows += [r | {"seed": seed} for r in score_rows(cell, key, m, preds, s0, m0, f_c)]
|
||||
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
|
||||
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the job complete
|
||||
return stem, time.time() - t0
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# E6: equal budgets through the locked scripts/15 run_cell
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def e6_job(job) -> tuple[str, float]:
|
||||
regime, rid, c, N, seeds, device, cell_dir, P = job
|
||||
import ml_porosity.models.bank_train as bt
|
||||
|
||||
orig = bt.train_predict
|
||||
if not getattr(orig, "_gp_review_patched", False):
|
||||
def train_predict(X, Xte, spec, cfg, seed, budgets, device, on_budget=None):
|
||||
return orig(X, Xte, spec, cfg, seed, list(E_BUDGETS), device, on_budget=on_budget)
|
||||
train_predict._gp_review_patched = True
|
||||
bt.train_predict = train_predict # declared replacement: the budget list only
|
||||
s15 = load_script("15_diag_train.py")
|
||||
snr, dens = t2.regime_settings()[regime]
|
||||
st = {"snr_db": snr, "anchor_density": dens, "sigma_a_reg": None, "variants": ["a"], "methods": SEVEN,
|
||||
"save_preds": True, "budgets": None}
|
||||
_, dt = s15.run_cell((rid, c, N, seeds, 0, P, device, P2R / "posterior" / regime, cell_dir, st))
|
||||
return f"{regime}/r{rid}_c{c:g}_n{N}", dt
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# E4: point tie optimizing the SMC target
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def optimize_target(T, gamma: float, Z0s: np.ndarray, h: float = 1e-3, maxiter: int = 200) -> list:
|
||||
"""L-BFGS-B on −F, F(z) = log p(u|anchor) + gamma * l(u), forward-difference gradient in one batched call."""
|
||||
from scipy.optimize import minimize
|
||||
|
||||
d = Z0s.shape[1]
|
||||
E = np.eye(d) * h
|
||||
|
||||
def F(Zb):
|
||||
base, ll = T.parts(Zb)
|
||||
f = base + gamma * ll
|
||||
return np.where(np.isfinite(f), f, -np.inf)
|
||||
|
||||
def fg(z):
|
||||
f = F(np.vstack([z[None, :], z[None, :] + E]))
|
||||
f0, fp = f[0], f[1:]
|
||||
if not np.isfinite(f0):
|
||||
return 1e12, np.zeros(d)
|
||||
g = (fp - f0) / h
|
||||
bad = np.flatnonzero(~np.isfinite(fp))
|
||||
if bad.size:
|
||||
fm = F(z[None, :] - E[bad])
|
||||
g[bad] = np.where(np.isfinite(fm), (f0 - fm) / h, 0.0)
|
||||
return -f0, -g
|
||||
|
||||
res = []
|
||||
for z0 in Z0s:
|
||||
r = minimize(fg, z0.astype(float), jac=True, method="L-BFGS-B",
|
||||
options={"maxiter": maxiter, "ftol": 1e-9, "gtol": 1e-6})
|
||||
res.append(r)
|
||||
return res
|
||||
|
||||
|
||||
def e4_job(job) -> tuple[str, float]:
|
||||
regime, rid, c, N, seeds, device, out_dir, P = job
|
||||
import torch
|
||||
|
||||
torch.set_num_threads(2)
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.models.bank_train import train_predict
|
||||
from ml_porosity.registration.smc import TiePosterior, phase_basis, phase_wavelet
|
||||
from ml_porosity.registration.ties import warp_errors
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
t0 = time.time()
|
||||
cell = t2.build_cell(regime, rid, c, N, P, with_register=True)
|
||||
R, obs, reg, ph, out, wells = cell["R"], cell["obs"], cell["reg"], cell["ph"], cell["out"], cell["wells"]
|
||||
stem = t2.tag(regime, rid, c, N)
|
||||
key = dict(regime=regime, rid=rid, c=c, n_train=N)
|
||||
m0, s0 = out["norm"]
|
||||
lam = out["lam"]
|
||||
tcfg = P["training"]["model"] | P["training"]["optimizer"]
|
||||
f_c = P["metrics"]["bands"]["f_c_hz"]
|
||||
nb = lambda a: ((np.asarray(a, np.float64) - m0) / s0).astype(np.float32)
|
||||
h = WarpHyper(**out["hyper"])
|
||||
fac = int(round(R.dt / R.cfg["fine_dt_ms"]))
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"])
|
||||
pc = pd.read_csv(P2R / "posterior" / regime / f"r{rid}_c{c:g}_n{N}_s0.csv")
|
||||
pc = pc[(pc.method == "SMC_g_acf") & (pc.wavelet == "estR")].set_index("well")
|
||||
diag, lab_opt, lab_map = [], [], []
|
||||
for i, (o, w) in enumerate(zip(obs, wells)):
|
||||
tw = time.time()
|
||||
T = TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine, R.t_ext, wR,
|
||||
seis[i], (R.t_main[0], R.t_main[-1]))
|
||||
gamma = float(pc.loc[o["name"], "gamma"])
|
||||
Z = T.z(w["U"])
|
||||
base, ll = T.parts(Z)
|
||||
F0 = np.where(np.isfinite(base) & np.isfinite(ll), base + gamma * ll, -np.inf)
|
||||
k_map = int(np.argmax(F0)) # SMC-MAP of scripts/44
|
||||
fin = np.flatnonzero(np.isfinite(F0))
|
||||
_, first = np.unique(Z[fin], axis=0, return_index=True) # distinct saved particles
|
||||
cand = fin[first]
|
||||
starts = cand[np.argsort(-F0[cand])][:4]
|
||||
res = optimize_target(T, gamma, Z[starts])
|
||||
pool = [(F0[k], Z[k], "start") for k in starts] + [(-r.fun, r.x, "opt") for r in res if r.fun < 1e11]
|
||||
f_best, z_best, src = max(pool, key=lambda p: p[0])
|
||||
b_best, l_best = T.parts(z_best[None, :])
|
||||
f_chk = float(b_best[0] + gamma * l_best[0])
|
||||
u = T.u(z_best[None, :])[0]
|
||||
t_opt = R.grid.t_of_tau(u[0], u[1:], tau=R.tau_fine)[0]
|
||||
t_map = w["Tf"][k_map]
|
||||
err = lambda t: warp_errors(np.atleast_2d(t), R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
y_opt = cell["lab"](w["y_aa"], t_opt)[0]
|
||||
if not np.all(np.isfinite(y_opt)):
|
||||
raise RuntimeError(f"{stem} {o['name']}: label at the optimum is not finite")
|
||||
lab_opt.append(y_opt)
|
||||
lab_map.append(cell["lab"](w["y_aa"], t_map)[0])
|
||||
diag.append(key | {"well": o["name"], "gamma": gamma, "F_map": float(F0[k_map]), "F_opt": f_chk,
|
||||
"dF": f_chk - float(F0[k_map]), "base_map": float(base[k_map]), "ll_map": float(ll[k_map]),
|
||||
"base_opt": float(b_best[0]), "ll_opt": float(l_best[0]), "source": src,
|
||||
"n_starts": int(len(starts)), "n_improved": int(sum(-r.fun > F0[k] + 1e-9 for r, k in zip(res, starts))),
|
||||
"nit_max": int(max(r.nit for r in res)), "nfev_sum": int(sum(r.nfev for r in res)),
|
||||
"converged": int(sum(bool(r.success) for r in res)),
|
||||
"z_dist_opt_map": float(np.linalg.norm(z_best - Z[k_map])),
|
||||
"SMC-opt_warp_rmse_ms": err(t_opt), "SMC-MAP_warp_rmse_ms": err(t_map),
|
||||
"B3d-Sa_warp_rmse_ms": err(w["tm"]), "seconds": time.time() - tw})
|
||||
z1 = np.zeros((N, 1))
|
||||
specs = {"SMC-opt": bank(nb(np.stack(lab_opt))[:, None, :], z1, lam),
|
||||
"SMC-MAP": bank(nb(np.stack(lab_map))[:, None, :], z1, lam)}
|
||||
rows = []
|
||||
for seed in seeds:
|
||||
for m, sp in specs.items():
|
||||
if m == "SMC-MAP" and seed != 0: # reproduction check of scripts/44 at seed 0
|
||||
continue
|
||||
preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, [PRIMARY], device)
|
||||
rows += [r | {"seed": seed} for r in score_rows(cell, key, m, preds, s0, m0, f_c)]
|
||||
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
|
||||
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False)
|
||||
return stem, time.time() - t0
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# summaries
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def side(r: dict, m: str = "pct") -> str:
|
||||
return "below" if r[f"{m}_hi"] < 1 else ("above" if r[f"{m}_lo"] > 1 else "contains")
|
||||
|
||||
|
||||
def ratio_table(runs: pd.DataFrame, pairs: dict, cells, rng, budget_col: str | None = None) -> pd.DataFrame:
|
||||
"""runs: per (regime, c, n_train, rid, seed, method[, budget]) band_rmse. pairs: tag -> (num, den | 'best')."""
|
||||
rows = []
|
||||
groups = ["regime", "c", "n_train"] + ([budget_col] if budget_col else [])
|
||||
for k, g in runs.groupby(groups):
|
||||
if (k[0], k[1], k[2]) not in cells:
|
||||
continue
|
||||
have = set(g.method)
|
||||
best = min((m for m in POINT if m in have), key=lambda m: g[g.method == m].band_rmse.mean(), default=None)
|
||||
for tag, (x, y) in pairs.items():
|
||||
y = best if y == "best" else y
|
||||
if x not in have or y not in have:
|
||||
continue
|
||||
sx, sy = ci.per_rid(g, x), ci.per_rid(g, y)
|
||||
if len(sx) < len(RIDS) or len(sy) < len(RIDS):
|
||||
continue
|
||||
r = ci.intervals(sx, sy, rng)
|
||||
rows.append(dict(zip(groups, k)) | {"cmp": tag, "num": x, "den": y} | r)
|
||||
df = pd.DataFrame(rows)
|
||||
for m in ("pct", "bca", "t"):
|
||||
df[f"{m}_vs_1"] = [side(r, m) for _, r in df.iterrows()]
|
||||
return df
|
||||
|
||||
|
||||
def per_run(cells_csv: list[Path], extra: tuple = ()) -> pd.DataFrame:
|
||||
d = pd.concat([pd.read_csv(f) for f in cells_csv], ignore_index=True)
|
||||
keys = ["regime", "rid", "c", "n_train", "method", "seed", "budget", *extra]
|
||||
num = [c for c in d.columns if c not in keys + ["test_well"] and pd.api.types.is_numeric_dtype(d[c])]
|
||||
return d.groupby(keys, as_index=False)[num].mean()
|
||||
|
||||
|
||||
def three_way(df: pd.DataFrame, tag: str, cells, need: int, words: tuple[str, str, str]) -> dict:
|
||||
d = df[(df.cmp == tag) & df.apply(lambda r: (r.regime, r.c) in cells, axis=1)]
|
||||
nb, na = int((d.pct_vs_1 == "below").sum()), int((d.pct_vs_1 == "above").sum())
|
||||
reading = words[0] if nb >= need else (words[1] if na >= need else words[2])
|
||||
return {"n_cells": int(len(d)), "ci_below_1": nb, "ci_above_1": na, "rule": f">= {need} of {len(cells)}",
|
||||
"reading": reading, "ratio_range": [float(d.ratio.min()), float(d.ratio.max())] if len(d) else None}
|
||||
|
||||
|
||||
def summary_e5(rng) -> None:
|
||||
out = OUT / "e5"
|
||||
files = sorted(f for f in (out / "cells").glob("*.csv") if not f.name.endswith("_diag.csv"))
|
||||
if not files:
|
||||
print("E5: no cells yet")
|
||||
return
|
||||
new = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
cells = sorted({(r, c) for r, c in new[["regime", "c"]].drop_duplicates().itertuples(index=False)})
|
||||
reg = t2.registered_cells([(r, c, 16) for r, c in cells])
|
||||
keys = ["regime", "c", "rid", "seed", "method", "test_well"]
|
||||
rep = new[(new.method == "B3d-Sa") & (new.budget == PRIMARY)]
|
||||
mg = rep.merge(reg[keys + ["band_rmse", "rmse", "nll"]], on=keys, suffixes=("", "_reg"))
|
||||
dev = max(float((mg[c] - mg[f"{c}_reg"]).abs().max()) for c in ("band_rmse", "rmse", "nll"))
|
||||
sc = {"n_rows": int(len(mg)), "n_expected": int(len(rep)), "abs_dev_max": dev, "pass": bool(len(mg) == len(rep) and dev <= 1e-9)}
|
||||
ll = [f for f in sorted((LAMLIM / "cells").glob("*_n16.csv")) if not f.name.endswith("_seff.csv")]
|
||||
old = pd.concat([pd.read_csv(f) for f in ll], ignore_index=True)
|
||||
old = old[old.method.isin(["M2-Sa", "Bank-lam0", "Mean-MSE"])]
|
||||
allr = pd.concat([new, old], ignore_index=True)
|
||||
runs = allr.groupby(["regime", "rid", "c", "n_train", "method", "seed", "budget"], as_index=False)[
|
||||
["band_rmse", "rmse", "coverage_90", "mean_sigma", "nll"]].mean()
|
||||
pairs = {"R5a": ("Mean-NLL", "B3d-Sa"), "R5b": ("Mean-NLL", "Mean-MSE"), "R5c": ("M2-Sa", "Mean-NLL"),
|
||||
"D1": ("Bank-lam0", "Mean-NLL"), "D2": ("Mean-NLL-1024", "Mean-NLL")}
|
||||
df = ratio_table(runs, pairs, set((r, c, 16) for r, c in cells), rng, budget_col="budget")
|
||||
df.to_csv(out / "ratios.csv", index=False)
|
||||
d250 = df[df.budget == PRIMARY]
|
||||
complete = all((r, c) in cells for r, c in WIDE)
|
||||
reading = {"selfcheck": sc, "complete_wide": complete} | ({
|
||||
"R5a_label": three_way(d250, "R5a", WIDE, 5, ("the mean of labels is better", "the label at the mean warp is better", "no consistent difference")),
|
||||
"R5b_loss": three_way(d250, "R5b", WIDE, 5, ("NLL better", "MSE better", "no consistent difference")),
|
||||
"R5c_bank": three_way(d250, "R5c", WIDE, 5, ("bank better", "mean label better", "no consistent difference"))}
|
||||
if sc["pass"] and complete else {"note": "reproduction check failed or wide cells incomplete; ratios not read"})
|
||||
(out / "reading.json").write_text(json.dumps(reading, indent=1))
|
||||
cov = runs[runs.budget == PRIMARY].groupby(["regime", "c", "method"])[["coverage_90", "mean_sigma", "band_rmse"]].mean().reset_index()
|
||||
cov.to_csv(out / "coverage.csv", index=False)
|
||||
dg = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_diag.csv"))], ignore_index=True)
|
||||
lab = dg.groupby(["regime", "c"])[["rms_mean64_vs_pm_pu", "rms_mean1024_vs_pm_pu", "rms_mean64_vs_mean1024_pu", "n_valid_1024"]].mean().reset_index()
|
||||
lab.to_csv(out / "label_distance.csv", index=False)
|
||||
cols = ["cmp", "regime", "c", "budget", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "pct_vs_1"]
|
||||
txt = ["# E5: posterior-mean labels with the Gaussian likelihood (exploratory)", "", "```", json.dumps(reading, indent=1), "```", "",
|
||||
"## Ratios at 250 iterations", "", d250[cols].round(3).to_markdown(index=False), "",
|
||||
"## Coverage90, mean sigma and band RMSE at 250 iterations", "", cov.round(3).to_markdown(index=False), "",
|
||||
"## Label distances (p.u., main window)", "", lab.round(3).to_markdown(index=False), "",
|
||||
"## Ratios at 125 and 500 iterations", "", df[df.budget != PRIMARY][cols].round(3).to_markdown(index=False)]
|
||||
(out / "summary.md").write_text("\n".join(txt))
|
||||
print("\n".join(txt[:6]))
|
||||
|
||||
|
||||
def summary_e6(rng) -> None:
|
||||
out = OUT / "e6"
|
||||
s18 = load_script("18_summarize_p2r.py")
|
||||
parts, rep_rows = [], []
|
||||
for regime in H2A_REGIMES:
|
||||
cd = out / regime / "cells"
|
||||
files = sorted(f for f in cd.glob("r*_c*_n*.csv") if not f.name.endswith("_diag.csv")) if cd.exists() else []
|
||||
for f in files:
|
||||
d = pd.read_csv(f).assign(regime=regime)
|
||||
parts.append(d)
|
||||
r = pd.read_csv(P2R / "train" / regime / "cells" / f.name)
|
||||
r = r[r.method.isin(SEVEN) & (r.budget == r.method.map(REG_BUD))]
|
||||
mg = d.merge(r, on=["seed", "method", "budget", "test_well"], suffixes=("", "_reg"))
|
||||
met = [c for c in r.columns if c not in ("rid", "c", "n_train", "seed", "method", "budget", "test_well")]
|
||||
dev = max(float((mg[c] - mg[f"{c}_reg"]).abs().max()) for c in met)
|
||||
rep_rows.append({"regime": regime, "cell": f.stem, "n_rows": len(mg), "n_expected": len(r), "abs_dev_max": dev})
|
||||
if not parts:
|
||||
print("E6: no cells yet")
|
||||
return
|
||||
rep = pd.DataFrame(rep_rows)
|
||||
rep.to_csv(out / "reproduction.csv", index=False)
|
||||
sc = {"n_cells": int(len(rep)), "rows_ok": bool((rep.n_rows == rep.n_expected).all()),
|
||||
"abs_dev_max": float(rep.abs_dev_max.max()), "pass": bool((rep.n_rows == rep.n_expected).all() and rep.abs_dev_max.max() <= 1e-9)}
|
||||
d = pd.concat(parts, ignore_index=True)
|
||||
num = [c for c in d.columns if c not in ("regime", "rid", "c", "n_train", "seed", "method", "budget", "test_well")
|
||||
and pd.api.types.is_numeric_dtype(d[c])]
|
||||
runs = d.groupby(["regime", "rid", "c", "n_train", "method", "seed", "budget"], as_index=False)[num].mean()
|
||||
runs.to_csv(out / "runs.csv", index=False)
|
||||
sets = {"point_ties": POINT, "with_B3d": POINT + ["B3d"]}
|
||||
rows, ver = [], {}
|
||||
for b in E_BUDGETS:
|
||||
for regime in H2A_REGIMES:
|
||||
run = runs[(runs.regime == regime) & (runs.budget == b)].drop(columns=["regime", "budget"])
|
||||
if run.empty:
|
||||
continue
|
||||
for cand in ("B3d-Sa", "M2-Sa"):
|
||||
for sname, comp in sets.items():
|
||||
cells, gv = s18.h2a_cells(run, cand, comp, rng, N_BOOT)
|
||||
c1 = cells[cells.c == 1.0]
|
||||
ver[f"b{b}/{regime}/{cand}/{sname}"] = {"c1_pass": int(c1.cell_pass.sum()), "c1_cells": int(len(c1)),
|
||||
"zero_drift_macro_ratio": gv["zero_drift_macro_ratio"],
|
||||
"zero_drift_guard": gv["zero_drift_guard"]}
|
||||
rows.append(cells.assign(budget=b, regime=regime, candidate=cand, competitors=sname))
|
||||
tab = pd.concat(rows, ignore_index=True)
|
||||
tab.to_csv(out / "h2a_by_budget.csv", index=False)
|
||||
k = {b: sum(v["c1_pass"] for kk, v in ver.items() if kk.startswith(f"b{b}/") and kk.endswith("/B3d-Sa/point_ties"))
|
||||
for b in E_BUDGETS}
|
||||
complete = len(tab[(tab.candidate == "B3d-Sa") & (tab.competitors == "point_ties")]) == 3 * len(E_BUDGETS) * len(CS) * len(NS)
|
||||
if sc["pass"] and complete:
|
||||
reading = ("budget-robust" if all(v >= 5 for v in k.values())
|
||||
else ("budget-dependent" if any(v <= 3 for v in k.values()) else "partly robust"))
|
||||
else:
|
||||
reading = "not read (reproduction check failed or grid incomplete)"
|
||||
res = {"selfcheck": sc, "complete": complete, "k_b": k, "reading": reading, "per_budget": ver}
|
||||
(out / "reading.json").write_text(json.dumps(res, indent=1, default=float))
|
||||
mean = runs.groupby(["regime", "c", "n_train", "method", "budget"]).band_rmse.mean().unstack("budget").reset_index()
|
||||
mean.to_csv(out / "band_rmse_by_budget.csv", index=False)
|
||||
cols = ["budget", "regime", "candidate", "competitors", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi",
|
||||
"seeds_improve", "rids_improve", "cell_pass"]
|
||||
txt = ["# E6: equal-budget table (exploratory)", "", "```", json.dumps({kk: res[kk] for kk in ("selfcheck", "complete", "k_b", "reading")},
|
||||
indent=1, default=float), "```", "", "## H2a cell rule per budget", "", tab[cols].round(3).to_markdown(index=False), "",
|
||||
"## Mean band RMSE (p.u.) per budget", "", mean.round(3).to_markdown(index=False)]
|
||||
(out / "summary.md").write_text("\n".join(txt))
|
||||
print("\n".join(txt[:8]))
|
||||
|
||||
|
||||
def summary_e4(rng) -> None:
|
||||
out = OUT / "e4"
|
||||
files = sorted(f for f in (out / "cells").glob("*.csv") if not f.name.endswith("_diag.csv"))
|
||||
if not files:
|
||||
print("E4: no cells yet")
|
||||
return
|
||||
new = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
pt = pd.concat([pd.read_csv(f) for f in sorted((POINT_TIE / "cells").glob("*.csv")) if not f.name.endswith("_diag.csv")],
|
||||
ignore_index=True)
|
||||
keys = ["regime", "rid", "c", "n_train", "seed", "method", "test_well"]
|
||||
a = new[new.method == "SMC-MAP"].merge(pt[pt.method == "SMC-MAP"], on=keys, suffixes=("", "_pt"))
|
||||
sc = {"n_rows": int(len(a)), "n_expected": int((new.method == "SMC-MAP").sum()),
|
||||
"abs_dev_max": float((a.band_rmse - a.band_rmse_pt).abs().max()) if len(a) else None}
|
||||
sc["pass"] = bool(sc["n_rows"] == sc["n_expected"] and sc["abs_dev_max"] is not None and sc["abs_dev_max"] <= 1e-9)
|
||||
regs = []
|
||||
for regime in H2A_REGIMES:
|
||||
r = pd.read_csv(P2R / "train" / regime / "runs.csv")
|
||||
regs.append(r[r.method.isin(SEVEN) & r.c.isin(CS) & r.n_train.isin(NS)].assign(regime=regime))
|
||||
reg = pd.concat(regs, ignore_index=True)[["regime", "rid", "c", "n_train", "method", "seed", "band_rmse"]]
|
||||
ptr = pt[pt.method.isin(["SMC-MAP", "Anchor-LS"])].groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False).band_rmse.mean()
|
||||
opt = new[new.method == "SMC-opt"].groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False).band_rmse.mean()
|
||||
runs = pd.concat([reg, ptr, opt], ignore_index=True)
|
||||
pairs = {"E4-1": ("SMC-opt", "best"), "E4-2": ("B3d-Sa", "SMC-opt"), "E4-3": ("SMC-opt", "SMC-MAP"),
|
||||
"E4-4": ("SMC-opt", "Anchor-LS")}
|
||||
cells12 = {(r, c, n) for r in H2A_REGIMES for c in CS for n in NS}
|
||||
df = ratio_table(runs, pairs, cells12, rng)
|
||||
df.to_csv(out / "ratios.csv", index=False)
|
||||
n = lambda tag, s: int((df[df.cmp == tag].pct_vs_1 == s).sum())
|
||||
e3 = df[df.cmp == "E4-3"]
|
||||
complete = len(df[df.cmp == "E4-1"]) == 12
|
||||
reading = {"selfcheck_smc_map_seed0": sc, "complete": complete}
|
||||
if complete:
|
||||
reading |= {
|
||||
"R4a": {"ci_below_1": n("E4-1", "below"), "rule": ">= 10 of 12",
|
||||
"reading": "the target, not the sampler, carries the gain over deterministic ties" if n("E4-1", "below") >= 10 else "not supported"},
|
||||
"R4b": {"ci_below_1": n("E4-2", "below"), "ci_above_1": n("E4-2", "above"), "rule": ">= 6 of 12",
|
||||
"reading": ("posterior averaging improves on the optimized point" if n("E4-2", "below") >= 6 else
|
||||
("the optimized point is better than averaging" if n("E4-2", "above") >= 6 else "no consistent difference"))},
|
||||
"R4c": {"in_0.98_1.02": int(((e3.ratio >= 0.98) & (e3.ratio <= 1.02)).sum()), "rule": ">= 10 of 12",
|
||||
"reading": "optimizing beyond the best particle changes little" if ((e3.ratio >= 0.98) & (e3.ratio <= 1.02)).sum() >= 10 else "not supported"}}
|
||||
(out / "reading.json").write_text(json.dumps(reading, indent=1))
|
||||
dg = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_diag.csv"))], ignore_index=True)
|
||||
wd = dg.groupby(["regime", "c", "n_train"]).agg(dF_mean=("dF", "mean"), dF_median=("dF", "median"), z_dist=("z_dist_opt_map", "mean"),
|
||||
opt_warp=("SMC-opt_warp_rmse_ms", "mean"), map_warp=("SMC-MAP_warp_rmse_ms", "mean"),
|
||||
pm_warp=("B3d-Sa_warp_rmse_ms", "mean"), frac_opt_source=("source", lambda s: float((s == "opt").mean())),
|
||||
converged=("converged", "mean")).reset_index()
|
||||
wd.to_csv(out / "optimizer.csv", index=False)
|
||||
cols = ["cmp", "regime", "c", "n_train", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "pct_vs_1"]
|
||||
txt = ["# E4: point tie optimizing the SMC target (exploratory)", "", "```", json.dumps(reading, indent=1), "```", "",
|
||||
"## Ratios (budget 250 for SMC-opt; registered budgets otherwise)", "", df[cols].round(3).to_markdown(index=False), "",
|
||||
"## Optimizer and warp RMSE (ms), mean over training wells and realizations", "", wd.round(3).to_markdown(index=False)]
|
||||
(out / "summary.md").write_text("\n".join(txt))
|
||||
print("\n".join(txt[:6]))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--stage", choices=["e5", "e6", "e4", "summary"], required=True)
|
||||
ap.add_argument("--device", default="cuda:0")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=RIDS)
|
||||
args = ap.parse_args()
|
||||
set_threads()
|
||||
sha = check_declaration()
|
||||
P = run_d2.load_protocol(check=True)
|
||||
print(f"declaration {sha[:12]} and the locked protocols match ({time.strftime('%FT%TZ', time.gmtime())})", flush=True)
|
||||
if args.stage == "e5":
|
||||
d = OUT / "e5" / "cells"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
jobs = [(r, rid, c, 16, SEEDS, args.device, d, P) for r, c in WIDE + NARROW for rid in args.rids
|
||||
if not (d / f"{t2.tag(r, rid, c, 16)}.csv").exists()]
|
||||
run_pool(e5_job, jobs, args.workers, "E5")
|
||||
elif args.stage == "e6":
|
||||
jobs = []
|
||||
for r in H2A_REGIMES:
|
||||
d = OUT / "e6" / r / "cells"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
jobs += [(r, rid, c, n, SEEDS, args.device, d, P) for c in CS for n in NS for rid in args.rids
|
||||
if not (d / f"r{rid}_c{c:g}_n{n}.csv").exists()]
|
||||
jobs.sort(key=lambda j: -j[3])
|
||||
run_pool(e6_job, jobs, args.workers, "E6")
|
||||
elif args.stage == "e4":
|
||||
d = OUT / "e4" / "cells"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
jobs = [(r, rid, c, n, SEEDS, args.device, d, P) for r in H2A_REGIMES for c in CS for n in NS for rid in args.rids
|
||||
if not (d / f"{t2.tag(r, rid, c, n)}.csv").exists()]
|
||||
jobs.sort(key=lambda j: -j[3])
|
||||
run_pool(e4_job, jobs, args.workers, "E4")
|
||||
else:
|
||||
for f in (summary_e5, summary_e6, summary_e4):
|
||||
f(np.random.default_rng(0))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("PYTHONHASHSEED", "0")
|
||||
main()
|
||||
655
scripts/53_gp_practitioner_tie.py
Normal file
655
scripts/53_gp_practitioner_tie.py
Normal file
@@ -0,0 +1,655 @@
|
||||
"""GP review, Phase 3, experiment E2: a practitioner-grade deterministic tie (B3p), tuned on development data. Declared in
|
||||
docs/research/gp-review-experiments.md (section E2) and hashed before the first run; exploratory; outside every lock and
|
||||
the reproduction archives. Locked code is imported unchanged.
|
||||
|
||||
Tie (per well; synthetic sonic time is τ itself):
|
||||
1 anchor calibration of d(τ) = t − τ: exact (= B3b) or smooth (GCV smoothing spline with ≥ 5 anchors, LS line with
|
||||
3–4, B3b with ≤ 2; constant extrapolation; dt/dτ ≥ 0.05)
|
||||
2 wavelet from the N training wells: stat | stat+phase (15° grid in [−90°, 90°]) | LS (Wiener, 1% prewhitening)
|
||||
3 bulk shift in [−B, B] ms, B ∈ {0, 12}
|
||||
4 dynamic warping on a 1-ms grid, lags |l| ≤ L ∈ {4, 8, 16, 24}, strain ε ∈ {0.02, 0.05, 0.10} (knots every
|
||||
round(1/ε) ms, neighbours differ by ≤ 1 ms, linear between), dynamic programming
|
||||
5 t1(τ) = t(τ) + l(t(τ))
|
||||
6 iterations n ∈ {1, 2} (wavelet re-estimated at the first-pass ties, steps 3–5 redone from the step-1 tie)
|
||||
|
||||
.venv/bin/python scripts/53_gp_practitioner_tie.py --stage tune --workers 4 # dev 900–905, CPU
|
||||
.venv/bin/python scripts/53_gp_practitioner_tie.py --stage select # configuration per regime
|
||||
.venv/bin/python scripts/53_gp_practitioner_tie.py --stage budget --device cuda:0
|
||||
.venv/bin/python scripts/53_gp_practitioner_tie.py --stage train --set p2r|rep --workers 4 --device cuda:0
|
||||
.venv/bin/python scripts/53_gp_practitioner_tie.py --stage summary
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
t2 = load_script("32_t2_mechanism.py")
|
||||
ci = load_script("43_referee_r5_ci.py")
|
||||
run_d2 = t2.run_d2
|
||||
|
||||
DECL = REPO_ROOT / "docs" / "research" / "gp-review-experiments.md"
|
||||
DECL_HASH = REPO_ROOT / "docs" / "research" / "gp-review-experiments.sha256"
|
||||
OUT = outputs_dir() / "gp_review" / "e2"
|
||||
P2R = outputs_dir() / "p2r"
|
||||
REP = outputs_dir() / "replication"
|
||||
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
|
||||
DEV_RIDS = [900, 901, 902, 903, 904, 905]
|
||||
SEEDS = [0, 1, 2, 3, 4]
|
||||
CALIB = ["exact", "smooth"]
|
||||
WAVELETS = ["stat", "stat+phase", "LS"]
|
||||
BULK = [0, 12]
|
||||
LAGS = [4, 8, 16, 24]
|
||||
STRAIN = [0.02, 0.05, 0.10]
|
||||
ITERS = [1, 2]
|
||||
PHASES = np.arange(-90, 91, 15)
|
||||
REG_BUD = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250}
|
||||
POINT = ["B3b", "B3c", "B3c-R"]
|
||||
N_BOOT = 2000
|
||||
|
||||
|
||||
def check_declaration() -> str:
|
||||
expected = DECL_HASH.read_text().split()[0]
|
||||
actual = hashlib.sha256(DECL.read_bytes()).hexdigest()
|
||||
if actual != expected:
|
||||
raise SystemExit(f"{DECL.name} differs from its recorded SHA-256 ({actual[:12]} != {expected[:12]})")
|
||||
return actual
|
||||
|
||||
|
||||
def configs() -> list[dict]:
|
||||
return [dict(calib=a, wavelet=w, B=b, L=l, eps=e, n=n)
|
||||
for a, w, b, l, e, n in itertools.product(CALIB, WAVELETS, BULK, LAGS, STRAIN, ITERS)]
|
||||
|
||||
|
||||
def cfg_name(k: dict) -> str:
|
||||
return f"{k['calib']}|{k['wavelet']}|B{k['B']}|L{k['L']}|e{k['eps']:g}|n{k['n']}"
|
||||
|
||||
|
||||
def simplicity(k: dict) -> tuple:
|
||||
"""Declared tie-break order: n = 1, B = 0, smaller L, larger ε, exact, stat < stat+phase < LS."""
|
||||
return (k["n"], k["B"], k["L"], -k["eps"], CALIB.index(k["calib"]), WAVELETS.index(k["wavelet"]))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# cell construction (as scripts/32 build_cell, without the saved posterior)
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def make_cell(regime: str, rid: int, c: float, N: int, P: dict, snr=None, dens=None, sigma_a_reg=None,
|
||||
with_register: bool = False) -> dict:
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||||
from ml_porosity.losses.rml import effective_lambda
|
||||
from ml_porosity.models.bank_train import zscore_patch
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.pipeline import label_norm
|
||||
from ml_porosity.registration.ties import tie_b3b
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
if snr is None:
|
||||
snr, dens = t2.regime_settings()[regime]
|
||||
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
|
||||
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
|
||||
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
|
||||
sa = cfg["anchors"]["sigma_a_ms"]
|
||||
obs = [R.observe(w, c, snr, sa, dens) for w in R.pool[:N]]
|
||||
test = [R.observe(w, c, snr, sa) for w in R.test]
|
||||
reg = run_d2.reg_settings(P)
|
||||
if sigma_a_reg is not None:
|
||||
reg["sigma_a_ms"] = sigma_a_reg
|
||||
f = cfg["fine_dt_ms"]
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
y_aa = [antialias(o["phi_log"], f, R.dt) for o in obs]
|
||||
cell = dict(R=R, obs=obs, test=test, reg=reg, lab=lab, y_aa=y_aa, cfg=cfg,
|
||||
seis=[o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs])
|
||||
if with_register:
|
||||
from ml_porosity.registration.pipeline import register
|
||||
out = register(R, obs, reg, 0)
|
||||
cell["out"] = out
|
||||
cell["norm"], cell["lam"] = out["norm"], out["lam"]
|
||||
else: # the same normalisation and λ as register() (label_norm; B3b reference)
|
||||
cell["norm"] = label_norm(R, obs)
|
||||
ref = [lab(y, tie_b3b(o["tau_k"], o["t_k"], R.tau_fine))[0] for y, o in zip(y_aa, obs)]
|
||||
cell["lam"] = effective_lambda(ref, dt_ms=R.dt)[0]
|
||||
cell["X"] = np.stack([zscore_patch(o["seis"], R.main) for o in obs])
|
||||
cell["Xte"] = np.stack([zscore_patch(o["seis"], R.main) for o in test])
|
||||
cell["yt"] = 100 * np.stack([o["y_true"] for o in test])
|
||||
return cell
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# the B3p tie
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
class TieKit:
|
||||
"""Grids and forward model shared by all wells of a cell."""
|
||||
|
||||
def __init__(self, cell: dict):
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet
|
||||
|
||||
self.R, self.obs, self.seis = cell["R"], cell["obs"], cell["seis"]
|
||||
R = self.R
|
||||
self.fac = int(round(R.dt / cell["cfg"]["fine_dt_ms"]))
|
||||
self.wl = cell["reg"]["wavelet_ms"]
|
||||
self.t1 = np.arange(R.t_ext[0], R.t_ext[-1] + 0.5, 1.0) # 1-ms grid over the extended window
|
||||
from scipy.interpolate import CubicSpline
|
||||
self.splines = [CubicSpline(R.t_ext, s, extrapolate=False) for s in self.seis]
|
||||
self.seis1 = [np.nan_to_num(sp(self.t1)) for sp in self.splines]
|
||||
self.w0 = statistical_wavelet(np.stack(self.seis), R.dt, self.wl)
|
||||
n = int(round(self.wl / R.dt)) // 2
|
||||
spike = np.zeros(2 * n + 1)
|
||||
spike[n] = 1.0
|
||||
self.spike_fine = fine_wavelet(spike, self.fac) # band-limited reflectivity
|
||||
self.fine = lambda w: fine_wavelet(w, self.fac)
|
||||
|
||||
def synth(self, i: int, t: np.ndarray, wf: np.ndarray, t_out: np.ndarray) -> np.ndarray:
|
||||
from ml_porosity.registration.tie_likelihood import synth_for_warps
|
||||
return synth_for_warps(self.R.tau_fine, self.obs[i]["ai_log"], t, self.R.t_fine, t_out, wf)[0]
|
||||
|
||||
def support(self, t: np.ndarray, grid: np.ndarray, pad: tuple[float, float] | None = None) -> np.ndarray:
|
||||
lo, hi = max(grid[0], t[0]), min(grid[-1], t[-1])
|
||||
if pad is not None:
|
||||
lo, hi = max(lo, pad[0]), min(hi, pad[1])
|
||||
return (grid >= lo) & (grid <= hi)
|
||||
|
||||
# -- step 1 --------------------------------------------------------------------------------------------------
|
||||
def calibrate(self, i: int, mode: str) -> np.ndarray:
|
||||
from scipy.interpolate import make_smoothing_spline
|
||||
from ml_porosity.registration.ties import clean_monotone, tie_b3b
|
||||
|
||||
o, tau = self.obs[i], self.R.tau_fine
|
||||
if mode == "exact":
|
||||
return tie_b3b(o["tau_k"], o["t_k"], tau)
|
||||
tk, ttk = clean_monotone(o["tau_k"], o["t_k"])
|
||||
if len(tk) <= 2:
|
||||
return tie_b3b(o["tau_k"], o["t_k"], tau)
|
||||
d, tc = ttk - tk, np.clip(tau, tk[0], tk[-1])
|
||||
if len(tk) >= 5:
|
||||
dd = make_smoothing_spline(tk, d)(tc) # λ by GCV (lam=None)
|
||||
else:
|
||||
dd = np.polyval(np.polyfit(tk, d, 1), tc)
|
||||
t = tau + dd
|
||||
return np.maximum.accumulate(t - 0.05 * tau) + 0.05 * tau
|
||||
|
||||
# -- step 2 --------------------------------------------------------------------------------------------------
|
||||
def wavelet(self, kind: str, ties: list[np.ndarray]) -> np.ndarray:
|
||||
"""Fine-grid wavelet estimated from the N training wells at the given ties."""
|
||||
from ml_porosity.data.wavelet import estimate_wavelet_ls, rotate_phase
|
||||
|
||||
R = self.R
|
||||
if kind == "stat":
|
||||
return self.fine(self.w0)
|
||||
if kind == "stat+phase":
|
||||
f0, fh = self.fine(self.w0), self.fine(np.imag(__import__("scipy.signal", fromlist=["hilbert"]).hilbert(self.w0)))
|
||||
score = np.zeros(len(PHASES))
|
||||
for i, t in enumerate(ties):
|
||||
m = self.support(t, R.t_ext)
|
||||
s0, sh = self.synth(i, t, f0, R.t_ext)[m], self.synth(i, t, fh, R.t_ext)[m]
|
||||
d = self.seis[i][m]
|
||||
for k, ph in enumerate(PHASES):
|
||||
p = np.deg2rad(ph)
|
||||
score[k] += np.corrcoef(s0 * np.cos(p) - sh * np.sin(p), d)[0, 1]
|
||||
return self.fine(rotate_phase(self.w0, float(PHASES[int(np.argmax(score))])))
|
||||
if kind == "LS":
|
||||
r_list, s_list = [], []
|
||||
win = (R.t_main[0] - 50.0, R.t_main[-1] + 50.0)
|
||||
for i, t in enumerate(ties):
|
||||
m = self.support(t, R.t_ext, win)
|
||||
r_list.append(self.synth(i, t, self.spike_fine, R.t_ext)[m])
|
||||
s_list.append(self.seis[i][m])
|
||||
w = estimate_wavelet_ls(r_list, s_list, R.dt, self.wl, damping=0.01)
|
||||
return self.fine(w / np.max(np.abs(w)))
|
||||
raise ValueError(kind)
|
||||
|
||||
def phase_of(self, kind, ties): # for the diagnostics only
|
||||
return None
|
||||
|
||||
# -- steps 3–5 -----------------------------------------------------------------------------------------------
|
||||
def window(self, i: int, t: np.ndarray, wf: np.ndarray):
|
||||
m = self.support(t, self.t1)
|
||||
syn = self.synth(i, t, wf, self.t1)
|
||||
idx = np.flatnonzero(m)
|
||||
s = syn[idx]
|
||||
s = s / max(np.sqrt(np.mean(s ** 2)), 1e-12)
|
||||
d = self.seis1[i]
|
||||
sc = max(np.sqrt(np.mean(d[idx] ** 2)), 1e-12)
|
||||
return idx, s, sc
|
||||
|
||||
def bulk(self, i: int, t: np.ndarray, wf: np.ndarray, B: int) -> int:
|
||||
if B == 0:
|
||||
return 0
|
||||
idx, s, sc = self.window(i, t, wf)
|
||||
d, best, arg = self.seis1[i] / sc, -np.inf, 0
|
||||
for b in range(-B, B + 1):
|
||||
j = idx + b
|
||||
ok = (j >= 0) & (j < len(d))
|
||||
r = np.corrcoef(s[ok], d[j[ok]])[0, 1]
|
||||
if r > best + 1e-12 or (abs(r - best) <= 1e-12 and abs(b) < abs(arg)):
|
||||
best, arg = r, b
|
||||
return arg
|
||||
|
||||
def dtw(self, i: int, t: np.ndarray, wf: np.ndarray, L: int, eps: float) -> np.ndarray:
|
||||
"""Lag l(t) on the 1-ms window (knots every round(1/ε) ms, |Δl| ≤ 1 ms between knots), returned as t1(τ)."""
|
||||
idx, s, sc = self.window(i, t, wf)
|
||||
tt = self.t1[idx]
|
||||
h = int(round(1 / eps))
|
||||
kn = np.arange(0, len(tt), h)
|
||||
if kn[-1] != len(tt) - 1:
|
||||
kn = np.append(kn, len(tt) - 1)
|
||||
lags = np.arange(-L, L + 1)
|
||||
nA = len(lags)
|
||||
sp = self.splines[i]
|
||||
nseg = len(kn) - 1
|
||||
cost = np.full((nseg, nA, 3), np.inf)
|
||||
for j in range(nseg):
|
||||
a, b = kn[j], kn[j + 1]
|
||||
samp = np.arange(a, b + 1 if j == nseg - 1 else b)
|
||||
fr = (samp - a) / (b - a)
|
||||
for di, dl in enumerate((-1, 0, 1)):
|
||||
pos = tt[samp][None, :] + lags[:, None] + dl * fr[None, :]
|
||||
v = sp(pos)
|
||||
v = np.where(np.isfinite(v), v, 0.0) / sc # zero outside the seismic window
|
||||
cost[j, :, di] = np.sum((s[samp][None, :] - v) ** 2, 1)
|
||||
if j == 0:
|
||||
pass
|
||||
# cost[j, a, δ]: segment j from lag a to lag a + δ (δ ∈ {−1, 0, 1}); invalid end lags excluded
|
||||
V = np.zeros(nA)
|
||||
back = np.zeros((nseg, nA), int)
|
||||
for j in range(nseg):
|
||||
Vn = np.full(nA, np.inf)
|
||||
for di, dl in enumerate((-1, 0, 1)):
|
||||
src = np.arange(nA) - dl # end lag index e = src + dl
|
||||
ok = (src >= 0) & (src < nA)
|
||||
cand = np.full(nA, np.inf)
|
||||
cand[ok] = V[src[ok]] + cost[j, src[ok], di]
|
||||
better = cand < Vn
|
||||
Vn[better], back[j, better] = cand[better], src[better]
|
||||
V = Vn
|
||||
e = int(np.argmin(V))
|
||||
path = [e]
|
||||
for j in range(nseg - 1, -1, -1):
|
||||
e = back[j, e]
|
||||
path.append(e)
|
||||
lag_kn = lags[np.array(path[::-1])].astype(float)
|
||||
lag_t = np.interp(t, tt[kn], lag_kn) # constant outside the window
|
||||
return t + lag_t
|
||||
|
||||
def tie_from(self, i: int, t0: np.ndarray, wf: np.ndarray, B: int, L: int, eps: float) -> np.ndarray:
|
||||
b = self.bulk(i, t0, wf, B)
|
||||
return self.dtw(i, t0 + b, wf, L, eps)
|
||||
|
||||
|
||||
def all_ties(cell: dict, grid: list[dict] | None = None) -> dict:
|
||||
"""{cfg_name: [t(τ) per well]} for every configuration in `grid` (default: all 288)."""
|
||||
kit = TieKit(cell)
|
||||
N = len(cell["obs"])
|
||||
grid = grid or configs()
|
||||
need = {(k["calib"], k["wavelet"]) for k in grid}
|
||||
res = {}
|
||||
for calib in CALIB:
|
||||
if not any(a == calib for a, _ in need):
|
||||
continue
|
||||
t0 = [kit.calibrate(i, calib) for i in range(N)]
|
||||
for wk in WAVELETS:
|
||||
sub = [k for k in grid if k["calib"] == calib and k["wavelet"] == wk]
|
||||
if not sub:
|
||||
continue
|
||||
w1 = kit.wavelet(wk, t0)
|
||||
first = {}
|
||||
for B, L, eps in sorted({(k["B"], k["L"], k["eps"]) for k in sub}):
|
||||
first[(B, L, eps)] = [kit.tie_from(i, t0[i], w1, B, L, eps) for i in range(N)]
|
||||
for k in sub:
|
||||
key = (k["B"], k["L"], k["eps"])
|
||||
if k["n"] == 1 or wk == "stat": # stat does not depend on the tie
|
||||
res[cfg_name(k)] = first[key]
|
||||
else:
|
||||
w2 = kit.wavelet(wk, first[key])
|
||||
res[cfg_name(k)] = [kit.tie_from(i, t0[i], w2, *key) for i in range(N)]
|
||||
return res
|
||||
|
||||
|
||||
def warp_rmse(cell: dict, i: int, t: np.ndarray) -> float:
|
||||
from ml_porosity.registration.ties import warp_errors
|
||||
R, o = cell["R"], cell["obs"][i]
|
||||
return warp_errors(np.atleast_2d(t), R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# stages
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
PHASE_DIRS = {"R10": ["p2/diag/posterior", "bench/dev/posterior/R10"], "R0": ["p2/diag/stress/snr0_full"],
|
||||
"Rm5": ["p2/diag/stress/snr-5_full"], "R0h": ["p2/diag/stress/snr0_half"],
|
||||
"R10tb": ["p2/diag/stress/snr10_topbottom"]}
|
||||
|
||||
|
||||
def dev_phase(regime: str, rid: int, c: float, N: int) -> dict | None:
|
||||
"""Saved re-estimated phase of a development posterior with the regime's SNR and anchor density, if any."""
|
||||
snr, dens = t2.regime_settings()[regime]
|
||||
for sub in PHASE_DIRS[regime]:
|
||||
f = outputs_dir() / sub / f"r{rid}_c{c:g}_n{N}_s0_phase.json"
|
||||
if not f.exists():
|
||||
continue
|
||||
pc = pd.read_csv(f.with_name(f.name.replace("_phase.json", ".csv")))
|
||||
if "snr_db" in pc.columns: # bench dev posteriors carry their settings; the P2 diagnostic ones are 10 dB, full anchors, sigma_a 7
|
||||
if float(pc.snr_db.iloc[0]) != float(snr) or pc.anchor_density.iloc[0] != dens or float(pc.sigma_a_reg.iloc[0]) != 7.0:
|
||||
continue
|
||||
elif regime != "R10":
|
||||
continue
|
||||
ph = json.loads(f.read_text())
|
||||
return {"phase_R": float(ph["phase_R"]), "phase0": float(ph.get("phase0", 0.0)), "src": sub,
|
||||
"particles": int(pc.particles.iloc[0]) if "particles" in pc.columns else 1024}
|
||||
return None
|
||||
|
||||
|
||||
def tune_job(job) -> tuple[str, float]:
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.registration.smc import phase_basis, phase_wavelet
|
||||
from ml_porosity.registration.tie_likelihood import synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c
|
||||
|
||||
regime, rid, c, N, P, out_dir = job
|
||||
t0 = time.time()
|
||||
cell = make_cell(regime, rid, c, N, P, with_register=True)
|
||||
ties = all_ties(cell)
|
||||
R, ph = cell["R"], dev_phase(regime, rid, c, N)
|
||||
if ph is not None:
|
||||
fac = int(round(R.dt / cell["cfg"]["fine_dt_ms"]))
|
||||
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(cell["seis"]), R.dt, cell["reg"]["wavelet_ms"]), fac),
|
||||
ph["phase_R"])
|
||||
rows = []
|
||||
for i, o in enumerate(cell["obs"]):
|
||||
d = {"regime": regime, "rid": rid, "c": c, "n_train": N, "well": o["name"], "n_anchor": len(o["tau_k"])}
|
||||
dg = cell["out"]["diag"][i]
|
||||
d |= {f"{m}": dg[f"{m}_warp_rmse_ms"] for m in ("B3b", "B3c", "B3d")}
|
||||
d |= {"B3c-R": np.nan, "phase_src": None, "phase0_reg": cell["out"].get("phase")}
|
||||
if ph is not None:
|
||||
tb = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
|
||||
syn = synth_for_warps(R.tau_fine, o["ai_log"], tb, R.t_fine, R.t_ext, wR)[0]
|
||||
d |= {"B3c-R": warp_rmse(cell, i, tie_b3c(tb, R.tau_fine, syn, cell["seis"][i], R.t_ext, R.dt)),
|
||||
"phase_src": ph["src"], "phase_particles": ph["particles"], "phase0_saved": ph["phase0"]}
|
||||
d |= {name: warp_rmse(cell, i, T[i]) for name, T in ties.items()}
|
||||
rows.append(d)
|
||||
stem = f"{regime}_r{rid}_c{c:g}_n{N}"
|
||||
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False)
|
||||
return stem, time.time() - t0
|
||||
|
||||
|
||||
def select() -> dict:
|
||||
files = sorted((OUT / "tune").glob("*.csv"))
|
||||
d = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
grid = configs()
|
||||
names = [cfg_name(k) for k in grid]
|
||||
exp = len(REGIMES) * len(DEV_RIDS) * 3 * 2
|
||||
sel, rows = {}, []
|
||||
for regime in REGIMES:
|
||||
g = d[d.regime == regime]
|
||||
n_cells = g[["rid", "c", "n_train"]].drop_duplicates().shape[0]
|
||||
m = g[names].mean() # pooled over all training wells
|
||||
best = m.min()
|
||||
tied = [k for k in grid if m[cfg_name(k)] <= best + 1e-9]
|
||||
k = min(tied, key=simplicity)
|
||||
sel[regime] = k | {"name": cfg_name(k), "dev_warp_rmse_ms": float(m[cfg_name(k)]), "n_cells": int(n_cells),
|
||||
"n_wells": int(len(g)), "n_tied": len(tied)}
|
||||
gr = g[g["B3c-R"].notna()] # cells with a saved dev phase
|
||||
rows.append({"regime": regime, "B3p": cfg_name(k), "B3p_ms": float(m[cfg_name(k)]),
|
||||
**{f"{x}_ms": float(g[x].mean()) for x in ("B3b", "B3c", "B3d")},
|
||||
"B3c-R_ms": float(gr["B3c-R"].mean()) if len(gr) else np.nan,
|
||||
"B3p_ms_on_B3c-R_cells": float(gr[cfg_name(k)].mean()) if len(gr) else np.nan,
|
||||
"B3c_ms_on_B3c-R_cells": float(gr["B3c"].mean()) if len(gr) else np.nan,
|
||||
"n_cells_B3c-R": int(gr[["rid", "c", "n_train"]].drop_duplicates().shape[0]),
|
||||
"worst_config_ms": float(m.max()), "median_config_ms": float(m.median()), "n_cells": int(n_cells)})
|
||||
meta = {"selected": sel, "n_cells_found": int(d[["regime", "rid", "c", "n_train"]].drop_duplicates().shape[0]),
|
||||
"n_cells_expected": exp, "pooling": "mean over all training wells of all dev cells of the regime"}
|
||||
(OUT / "selected.json").write_text(json.dumps(meta, indent=1))
|
||||
pd.DataFrame(rows).to_csv(OUT / "dev_warp_rmse.csv", index=False)
|
||||
print(pd.DataFrame(rows).round(3).to_string(index=False))
|
||||
return meta
|
||||
|
||||
|
||||
def selected() -> dict:
|
||||
f = OUT / "selected.json"
|
||||
if not f.exists():
|
||||
raise SystemExit("run --stage select first")
|
||||
return json.loads(f.read_text())["selected"]
|
||||
|
||||
|
||||
def b3p_labels(cell: dict, k: dict) -> tuple[np.ndarray, list[np.ndarray], list[float]]:
|
||||
T = all_ties(cell, [{x: k[x] for x in ("calib", "wavelet", "B", "L", "eps", "n")}])[cfg_name(k)]
|
||||
Y = np.stack([cell["lab"](y, t)[0] for y, t in zip(cell["y_aa"], T)])
|
||||
if not np.all(np.isfinite(Y)):
|
||||
raise RuntimeError("B3p label is not finite (warp does not cover the main window)")
|
||||
return Y, T, [warp_rmse(cell, i, t) for i, t in enumerate(T)]
|
||||
|
||||
|
||||
def train_cell(cell: dict, k: dict, seeds, budgets, device, P, key: dict) -> tuple[list[dict], list[dict]]:
|
||||
from ml_porosity.models.bank_train import train_predict
|
||||
|
||||
Y, T, err = b3p_labels(cell, k)
|
||||
m0, s0 = cell["norm"]
|
||||
spec = {"kind": "bank", "Y": ((Y - m0) / s0).astype(np.float32)[:, None, :],
|
||||
"logpi": np.zeros((len(Y), 1), np.float32), "lam": cell["lam"]}
|
||||
tcfg = P["training"]["model"] | P["training"]["optimizer"]
|
||||
f_c = P["metrics"]["bands"]["f_c_hz"]
|
||||
rows = []
|
||||
for seed in seeds:
|
||||
preds = train_predict(cell["X"], cell["Xte"], spec, tcfg, seed, budgets, device)
|
||||
for b, (mu, sg) in preds.items():
|
||||
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
|
||||
for wt, r in zip(cell["R"].test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)):
|
||||
rows.append(key | {"seed": seed, "method": "B3p", "budget": b, "test_well": wt.name} | r)
|
||||
diag = [key | {"well": o["name"], "B3p_warp_rmse_ms": e, "config": cfg_name(k)} for o, e in zip(cell["obs"], err)]
|
||||
return rows, diag
|
||||
|
||||
|
||||
def budget_job(job) -> tuple[str, float]:
|
||||
rid, N, seeds, device, P, out_dir = job
|
||||
import torch
|
||||
torch.set_num_threads(2)
|
||||
t0 = time.time()
|
||||
k = selected()["R10"]
|
||||
cell = make_cell("R10", rid, 1.0, N, P)
|
||||
key = {"regime": "R10", "rid": rid, "c": 1.0, "n_train": N}
|
||||
rows, diag = train_cell(cell, k, seeds, P["training"]["budget_candidates"], device, P, key)
|
||||
stem = f"R10_r{rid}_c1_n{N}"
|
||||
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
|
||||
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False)
|
||||
return stem, time.time() - t0
|
||||
|
||||
|
||||
def train_job(job) -> tuple[str, float]:
|
||||
regime, rid, c, N, seeds, device, P, out_dir, extra = job
|
||||
import torch
|
||||
torch.set_num_threads(2)
|
||||
t0 = time.time()
|
||||
k = selected()[regime]
|
||||
budget = json.loads((OUT / "budget.json").read_text())["B3p"]
|
||||
cell = make_cell(regime, rid, c, N, P, **extra)
|
||||
key = {"regime": regime, "rid": rid, "c": c, "n_train": N}
|
||||
rows, diag = train_cell(cell, k, seeds, [budget], device, P, key)
|
||||
stem = f"{regime}_r{rid}_c{c:g}_n{N}"
|
||||
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
|
||||
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False)
|
||||
return stem, time.time() - t0
|
||||
|
||||
|
||||
def run_pool(fn, jobs, workers: int, label: str) -> None:
|
||||
print(f"{label}: {len(jobs)} jobs, {workers} workers", flush=True)
|
||||
if not jobs:
|
||||
return
|
||||
t0 = time.time()
|
||||
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
|
||||
futs = [ex.submit(fn, j) for j in jobs]
|
||||
for i, f in enumerate(as_completed(futs), 1):
|
||||
stem, dt = f.result()
|
||||
print(f"[{i}/{len(jobs)}] {stem} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# summary
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def registered_runs(base: Path, regimes, rids) -> pd.DataFrame:
|
||||
rows = []
|
||||
for regime in regimes:
|
||||
for f in sorted((base / "train" / regime / "cells").glob("r*_c*_n*.csv")):
|
||||
if f.name.endswith("_diag.csv"):
|
||||
continue
|
||||
d = pd.read_csv(f)
|
||||
if int(d.rid.iloc[0]) not in rids:
|
||||
continue
|
||||
d = d[d.method.isin(list(REG_BUD)) & (d.budget == d.method.map(REG_BUD))]
|
||||
rows.append(d.assign(regime=regime))
|
||||
d = pd.concat(rows, ignore_index=True)
|
||||
num = [c for c in d.columns if c not in ("regime", "rid", "c", "n_train", "seed", "method", "budget", "test_well")
|
||||
and pd.api.types.is_numeric_dtype(d[c])]
|
||||
return d.groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False)[num].mean()
|
||||
|
||||
|
||||
def summary() -> None:
|
||||
s18 = load_script("18_summarize_p2r.py")
|
||||
rng = np.random.default_rng(0)
|
||||
res = {"selected": selected(), "budget": json.loads((OUT / "budget.json").read_text())}
|
||||
tabs, ratios, warps = [], [], []
|
||||
for tag, base, rids, regimes in (("8-15", P2R, list(range(8, 16)), ["R10", "R0", "Rm5"]),
|
||||
("16-23", REP, list(range(16, 24)), ["R10", "R0", "Rm5"])):
|
||||
cd = OUT / ("train_p2r" if tag == "8-15" else "train_rep")
|
||||
files = sorted(f for f in cd.glob("*.csv") if not f.name.endswith("_diag.csv")) if cd.exists() else []
|
||||
if not files:
|
||||
continue
|
||||
b = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
b = b.groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False)[["band_rmse", "band_pcc", "rmse"]].mean()
|
||||
reg = registered_runs(base, regimes, rids)
|
||||
runs = pd.concat([reg, b], ignore_index=True)
|
||||
ver = {}
|
||||
for regime in regimes:
|
||||
run = runs[(runs.regime == regime) & runs.c.isin([0.0, 1.0])].drop(columns=["regime"])
|
||||
if "B3p" not in set(run.method) or run[run.method == "B3p"].rid.nunique() < len(rids):
|
||||
continue
|
||||
for cand in ("B3d-Sa", "M2-Sa"):
|
||||
for sname, comp in (("with_B3p", POINT + ["B3p"]), ("with_B3d_B3p", POINT + ["B3d", "B3p"]),
|
||||
("point_ties", POINT)):
|
||||
cells, gv = s18.h2a_cells(run, cand, comp, rng, N_BOOT)
|
||||
c1 = cells[cells.c == 1.0]
|
||||
ver[f"{regime}/{cand}/{sname}"] = {"c1_pass": int(c1.cell_pass.sum()), "c1_cells": int(len(c1)),
|
||||
"zero_drift_macro_ratio": gv["zero_drift_macro_ratio"],
|
||||
"zero_drift_guard": gv["zero_drift_guard"],
|
||||
"best": {int(r.n_train): r.best for r in c1.itertuples()}}
|
||||
tabs.append(cells.assign(rids=tag, regime=regime, candidate=cand, competitors=sname))
|
||||
for (c, n), g in run.groupby(["c", "n_train"]):
|
||||
for x, y in (("B3d-Sa", "B3p"), ("M2-Sa", "B3p"), ("B3p", "B3b"), ("B3p", "B3c")):
|
||||
r = ci.intervals(ci.per_rid(g, x), ci.per_rid(g, y), rng)
|
||||
ratios.append({"rids": tag, "regime": regime, "c": c, "n_train": n, "num": x, "den": y} | r)
|
||||
k = sum(v["c1_pass"] for kk, v in ver.items() if kk.endswith("/B3d-Sa/with_B3p"))
|
||||
n_cells = sum(v["c1_cells"] for kk, v in ver.items() if kk.endswith("/B3d-Sa/with_B3p"))
|
||||
reading = None
|
||||
if n_cells == 6:
|
||||
reading = ("the headline survives a practitioner tie" if k >= 5 else ("narrowed" if k >= 3 else "does not survive"))
|
||||
res[tag] = {"B3d-Sa_vs_point+B3p_c1_pass": f"{k}/{n_cells}", "reading" if tag == "8-15" else "replication": reading,
|
||||
"per_regime": ver}
|
||||
dg = pd.concat([pd.read_csv(f) for f in sorted(cd.glob("*_diag.csv"))], ignore_index=True)
|
||||
dr = []
|
||||
for regime in regimes:
|
||||
for f in sorted((base / "train" / regime / "cells").glob("r*_c*_n*_diag.csv")):
|
||||
x = pd.read_csv(f)
|
||||
if int(x.rid.iloc[0]) in rids:
|
||||
dr.append(x.assign(regime=regime))
|
||||
dr = pd.concat(dr, ignore_index=True)
|
||||
w = dg.merge(dr, on=["regime", "rid", "c", "n_train", "well"], how="left")
|
||||
warps.append(w.groupby(["regime", "c", "n_train"])[["B3p_warp_rmse_ms", "B3c-R_warp_rmse_ms", "B3d-Sa_warp_rmse_ms"]]
|
||||
.mean().reset_index().assign(rids=tag))
|
||||
tab = pd.concat(tabs, ignore_index=True) if tabs else pd.DataFrame()
|
||||
tab.to_csv(OUT / "h2a_with_b3p.csv", index=False)
|
||||
rt = pd.DataFrame(ratios)
|
||||
rt.to_csv(OUT / "ratios.csv", index=False)
|
||||
wp = pd.concat(warps, ignore_index=True) if warps else pd.DataFrame()
|
||||
wp.to_csv(OUT / "warp_rmse.csv", index=False)
|
||||
(OUT / "reading.json").write_text(json.dumps(res, indent=1, default=float))
|
||||
dev = pd.read_csv(OUT / "dev_warp_rmse.csv")
|
||||
cols = ["rids", "regime", "candidate", "competitors", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi",
|
||||
"seeds_improve", "rids_improve", "cell_pass"]
|
||||
rcols = ["rids", "regime", "c", "n_train", "num", "den", "ratio", "pct_lo", "pct_hi", "t_lo", "t_hi"]
|
||||
txt = ["# E2: practitioner-grade deterministic tie B3p (exploratory)", "", "```",
|
||||
json.dumps({k: (v if k not in ("8-15", "16-23") else {kk: vv for kk, vv in v.items() if kk != "per_regime"})
|
||||
for k, v in res.items()}, indent=1, default=float), "```", "",
|
||||
"## Development warp RMSE (ms; pooled over training wells of 900–905, c 0/1/2, N 4/16)", "",
|
||||
dev.round(3).to_markdown(index=False), "", "## Warp RMSE on the evaluation cells (ms)", "",
|
||||
wp.round(3).to_markdown(index=False) if len(wp) else "(none)", "", "## H2a cell rule with B3p", "",
|
||||
tab[cols].round(3).to_markdown(index=False) if len(tab) else "(none)", "", "## Ratios", "",
|
||||
rt[rcols].round(3).to_markdown(index=False) if len(rt) else "(none)"]
|
||||
(OUT / "summary.md").write_text("\n".join(txt))
|
||||
print("\n".join(txt[:30]))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--stage", choices=["tune", "select", "budget", "train", "summary"], required=True)
|
||||
ap.add_argument("--set", choices=["p2r", "rep"], default="p2r")
|
||||
ap.add_argument("--device", default="cuda:0")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
args = ap.parse_args()
|
||||
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS"):
|
||||
os.environ.setdefault(k, "2")
|
||||
sha = check_declaration()
|
||||
P = run_d2.load_protocol(check=True)
|
||||
print(f"declaration {sha[:12]} and protocol_p2 match ({time.strftime('%FT%TZ', time.gmtime())})", flush=True)
|
||||
if args.stage == "tune":
|
||||
d = OUT / "tune"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
jobs = [(r, rid, c, n, P, d) for r in REGIMES for rid in DEV_RIDS for c in (0.0, 1.0, 2.0) for n in (16, 4)
|
||||
if not (d / f"{r}_r{rid}_c{c:g}_n{n}.csv").exists()]
|
||||
run_pool(tune_job, jobs, args.workers, "E2 tune")
|
||||
elif args.stage == "select":
|
||||
select()
|
||||
elif args.stage == "budget":
|
||||
d = OUT / "budget"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
jobs = [(rid, n, [0, 1], args.device, P, d) for rid in (900, 901) for n in (4, 16)
|
||||
if not (d / f"R10_r{rid}_c1_n{n}.csv").exists()]
|
||||
run_pool(budget_job, jobs, args.workers, "E2 budget")
|
||||
df = pd.concat([pd.read_csv(f) for f in sorted(d.glob("*.csv")) if not f.name.endswith("_diag.csv")], ignore_index=True)
|
||||
b = run_d2.select_budgets(df)
|
||||
mean = df.groupby(["budget", "rid", "n_train", "seed"]).rmse.mean().groupby("budget").mean()
|
||||
(OUT / "budget.json").write_text(json.dumps({"B3p": b["B3p"], "mean_rmse": mean.to_dict()}, indent=1))
|
||||
print("B3p budget:", b, mean.round(4).to_dict())
|
||||
elif args.stage == "train":
|
||||
if args.set == "p2r":
|
||||
d = OUT / "train_p2r"
|
||||
cells = [(r, rid, c, n) for r in REGIMES for c in (0.0, 1.0, 2.0) for n in (16, 4) for rid in range(8, 16)]
|
||||
else:
|
||||
d = OUT / "train_rep"
|
||||
cells = [(r, rid, c, n) for r in ("R10", "R0", "Rm5") for c in (0.0, 1.0) for n in (16, 4) for rid in range(16, 24)]
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
jobs = [(r, rid, c, n, SEEDS, args.device, P, d, {}) for r, rid, c, n in cells
|
||||
if not (d / f"{r}_r{rid}_c{c:g}_n{n}.csv").exists()]
|
||||
run_pool(train_job, jobs, args.workers, f"E2 train {args.set}")
|
||||
else:
|
||||
summary()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("PYTHONHASHSEED", "0")
|
||||
main()
|
||||
636
scripts/54_gp_anchor_noise.py
Normal file
636
scripts/54_gp_anchor_noise.py
Normal file
@@ -0,0 +1,636 @@
|
||||
"""GP review E1 (declared in docs/research/gp-review-experiments.md, hashed before realizations 24-31 were generated;
|
||||
exploratory; outside every lock and the reproduction archives): the true anchor error varies, with and without a
|
||||
per-well bulk component, and the registration states sigma_a correctly or at 7 ms.
|
||||
|
||||
Anchor data model: t_k = boundary time + sigma_true * eps_k + beta_w, eps_k the realization's own draws (eps_a) and
|
||||
beta_w = sigma_B * z_w, z_w ~ N(0, 1) from default_rng([rid, crc32(well name), 2417]). It is implemented by replacing
|
||||
D2Realization.observe in the worker process (only the anchor times change). Conditions with "-fix" fit the drift
|
||||
hyperparameters at sigma_a = 7 ms and then set sigma_a to sigma_reg (the pattern of scripts/47). Every other step runs
|
||||
through the locked scripts/14 run_job and scripts/15 run_cell, unchanged.
|
||||
|
||||
--stage fingerprints SHA-256 fingerprints of realizations 24-31 (as scripts/46) and a check of the replacement
|
||||
-> outputs/gp_review/e1/{fingerprints.json, patch_check.json}; required before any posterior
|
||||
--stage post 1024-particle posteriors (estR), R10, c = 1, N = 4, 16 -> e1/<cond>/posterior/R10/
|
||||
--stage train the seven registered methods at their registered budgets, seeds 0-4 -> e1/<cond>/train/R10/cells/
|
||||
--stage arms SMC-MAP (budget 250, seeds 0-4) and B3d-Sa at seed 0 (reproduction check) -> e1/<cond>/arms/
|
||||
--stage b3p B3p (E2 selection and budget) once per anchor model (it does not use sigma_reg) -> e1/b3p/<anchor>/
|
||||
--stage summary P1-P5 and the declared readings -> e1/summary/
|
||||
Every stage skips jobs whose CSV exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
import zlib
|
||||
from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
for _k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
|
||||
os.environ.setdefault(_k, "2")
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
t2 = load_script("32_t2_mechanism.py")
|
||||
ci = load_script("43_referee_r5_ci.py")
|
||||
run_d2 = t2.run_d2
|
||||
|
||||
DECL = REPO_ROOT / "docs" / "research" / "gp-review-experiments.md"
|
||||
DECL_HASH = REPO_ROOT / "docs" / "research" / "gp-review-experiments.sha256"
|
||||
ROOT = outputs_dir() / "gp_review" / "e1"
|
||||
E2 = outputs_dir() / "gp_review" / "e2"
|
||||
BUDGETS_JSON = outputs_dir() / "p2" / "diag" / "train" / "budgets.json"
|
||||
RIDS = list(range(24, 32))
|
||||
NS = [16, 4]
|
||||
C = 1.0
|
||||
SNR, DENS = 10.0, "full"
|
||||
SEEDS = [0, 1, 2, 3, 4]
|
||||
PARTICLES = 1024
|
||||
REG_BUD = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250}
|
||||
SEVEN = list(REG_BUD)
|
||||
POINT = ["B3b", "B3c", "B3c-R"]
|
||||
ARM_BUDGET = 250
|
||||
BULK_SEED = 2417
|
||||
N_BOOT = 2000
|
||||
# condition -> (sigma_true, sigma_B, sigma_reg, drift hyperparameters)
|
||||
CONDITIONS = {
|
||||
"iid7-reg7": (7.0, 0.0, 7.0, "refit"),
|
||||
"iid4-reg4": (4.0, 0.0, 4.0, "refit"),
|
||||
"iid4-reg7": (4.0, 0.0, 7.0, "refit"),
|
||||
"iid2-reg2": (2.0, 0.0, 2.0, "refit"),
|
||||
"iid2-reg7": (2.0, 0.0, 7.0, "refit"),
|
||||
"iid1-reg1": (1.0, 0.0, 1.0, "refit"),
|
||||
"iid1-reg7": (1.0, 0.0, 7.0, "refit"),
|
||||
"bulk-reg2": (2.0, 5.0, 2.0, "refit"),
|
||||
"bulk-reg5.4": (2.0, 5.0, math.sqrt(29.0), "refit"),
|
||||
"bulk-reg7": (2.0, 5.0, 7.0, "refit"),
|
||||
"iid2-reg2-fix": (2.0, 0.0, 2.0, "fix"),
|
||||
"bulk-reg2-fix": (2.0, 5.0, 2.0, "fix"),
|
||||
}
|
||||
ANCHOR_MODELS = {"iid7": (7.0, 0.0), "iid4": (4.0, 0.0), "iid2": (2.0, 0.0), "iid1": (1.0, 0.0), "bulk": (2.0, 5.0)}
|
||||
P5_PAIRS = {"iid4": ("iid4-reg7", "iid4-reg4"), "iid2": ("iid2-reg7", "iid2-reg2"), "iid1": ("iid1-reg7", "iid1-reg1"),
|
||||
"bulk": ("bulk-reg7", "bulk-reg5.4")}
|
||||
S1 = ["iid4-reg7", "iid2-reg7", "iid1-reg7"]
|
||||
S2 = ["iid4-reg4", "iid2-reg2", "iid1-reg1"]
|
||||
S3 = {"2": "bulk-reg2", "5.39": "bulk-reg5.4", "7": "bulk-reg7"}
|
||||
|
||||
|
||||
def anchor_model(cond: str) -> str:
|
||||
s_true, s_b = CONDITIONS[cond][:2]
|
||||
return next(k for k, v in ANCHOR_MODELS.items() if v == (s_true, s_b))
|
||||
|
||||
|
||||
def cdir(cond: str) -> Path:
|
||||
return ROOT / cond
|
||||
|
||||
|
||||
def check_declaration() -> str:
|
||||
expected = DECL_HASH.read_text().split()[0]
|
||||
actual = hashlib.sha256(DECL.read_bytes()).hexdigest()
|
||||
if actual != expected:
|
||||
raise SystemExit(f"{DECL.name} differs from its recorded SHA-256 ({actual[:12]} != {expected[:12]})")
|
||||
return actual
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# in-process replacements (declared): D2Realization.observe (anchor times only), pipeline.fit_cell_hyper ("-fix")
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
LOG = {"anchors": [], "hyper": []}
|
||||
|
||||
|
||||
def bulk_z(rid: int, name: str) -> float:
|
||||
return float(np.random.default_rng([rid, zlib.crc32(name.encode()), BULK_SEED]).standard_normal())
|
||||
|
||||
|
||||
def patch_observe(s_true: float, s_b: float) -> None:
|
||||
from ml_porosity.data import synth_d2
|
||||
|
||||
D = synth_d2.D2Realization
|
||||
if not hasattr(D, "_gp_orig_observe"):
|
||||
D._gp_orig_observe = D.observe
|
||||
orig = D._gp_orig_observe
|
||||
|
||||
def observe(self, w, c, snr_db, sigma_a_ms, anchor_density="full"):
|
||||
o = orig(self, w, c, snr_db, s_true, anchor_density)
|
||||
beta = s_b * bulk_z(self.rid, w.name) if s_b > 0 else 0.0
|
||||
if s_b > 0:
|
||||
o["t_k"] = o["t_k"] + beta
|
||||
LOG["anchors"].append({"well": w.name, "beta_ms": beta, "n_anchor": int(len(o["t_k"]))})
|
||||
return o
|
||||
|
||||
D.observe = observe
|
||||
|
||||
|
||||
def patch(cond: str, reg_settings: bool = False) -> None:
|
||||
"""Apply the replacements of `cond` in this process (idempotent; resets every earlier condition)."""
|
||||
from ml_porosity.registration import pipeline
|
||||
|
||||
s_true, s_b, s_reg, hyp = CONDITIONS[cond]
|
||||
patch_observe(s_true, s_b)
|
||||
if not hasattr(pipeline, "_gp_orig_fit"):
|
||||
pipeline._gp_orig_fit = pipeline.fit_cell_hyper
|
||||
orig = pipeline._gp_orig_fit
|
||||
|
||||
def fit(R, obs, reg, seed=0):
|
||||
if hyp == "fix":
|
||||
h, info = orig(R, obs, reg | {"sigma_a_ms": 7.0}, seed)
|
||||
h = dataclasses.replace(h, sigma_a_ms=reg["sigma_a_ms"])
|
||||
else:
|
||||
h, info = orig(R, obs, reg, seed)
|
||||
LOG["hyper"].append(h.as_dict() | {"sigma_a_reg_in": float(reg["sigma_a_ms"]), "mode": hyp})
|
||||
return h, info
|
||||
|
||||
pipeline.fit_cell_hyper = fit
|
||||
if not hasattr(run_d2, "_gp_orig_reg"):
|
||||
run_d2._gp_orig_reg = run_d2.reg_settings
|
||||
if reg_settings: # build_cell/register of the arms stage: registration sigma_a
|
||||
run_d2.reg_settings = lambda P: run_d2._gp_orig_reg(P) | {"sigma_a_ms": s_reg}
|
||||
else:
|
||||
run_d2.reg_settings = run_d2._gp_orig_reg
|
||||
|
||||
|
||||
def st_post(cond: str) -> dict:
|
||||
return {"snr_db": SNR, "anchor_density": DENS, "sigma_a_reg": CONDITIONS[cond][2], "wavelets": ["estR"],
|
||||
"smc_seed": None}
|
||||
|
||||
|
||||
def st_train(cond: str) -> dict:
|
||||
bud = json.loads(BUDGETS_JSON.read_text())
|
||||
assert all(int(bud[m]) == b for m, b in REG_BUD.items()), "budgets.json differs from the registered budgets"
|
||||
return {"snr_db": SNR, "anchor_density": DENS, "sigma_a_reg": CONDITIONS[cond][2], "variants": ["a"],
|
||||
"methods": SEVEN, "save_preds": True, "budgets": {m: int(bud[m]) for m in SEVEN}}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# fingerprints and replacement check
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def realization(P: dict, rid: int):
|
||||
import yaml
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
|
||||
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
|
||||
return D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
|
||||
|
||||
|
||||
def stage_fingerprints(P: dict) -> None:
|
||||
"""Fingerprints with the unmodified observe (definition of scripts/46), then the replacement check."""
|
||||
import scipy
|
||||
from ml_porosity.data import synth_d2
|
||||
|
||||
ROOT.mkdir(parents=True, exist_ok=True)
|
||||
if (ROOT / "fingerprints.json").exists():
|
||||
print("fingerprints.json exists; not rewritten")
|
||||
else:
|
||||
if any((ROOT / c / "posterior").exists() for c in CONDITIONS):
|
||||
raise SystemExit("posteriors exist without fingerprints.json")
|
||||
sha = lambda chunks: (lambda h: ([h.update(np.ascontiguousarray(np.asarray(a)).tobytes()) for a in chunks], h.hexdigest())[1])(hashlib.sha256())
|
||||
fields = ("seis_clean", "noise_unit", "phi_t", "z_g", "z_b", "boundaries_t", "eps_a")
|
||||
keys = ("seis", "phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true")
|
||||
out = {"meta": {"numpy": np.__version__, "scipy": scipy.__version__, "d2_config": P["inputs"]["d2_config"]["path"],
|
||||
"declaration": check_declaration(), "written_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())},
|
||||
"rids": {}}
|
||||
for rid in RIDS:
|
||||
R = realization(P, rid)
|
||||
obs = [R.observe(w, c, 10, 7.0, "full") for c in (0.0, 1.0, 2.0) for w in R.test + R.pool[:4]]
|
||||
out["rids"][str(rid)] = {"wells": {k: sha(getattr(w, k) for w in R.wells) for k in fields},
|
||||
"obs": {k: sha(o[k] for o in obs) for k in keys}}
|
||||
print(f"fingerprint r{rid}", flush=True)
|
||||
(ROOT / "fingerprints.json").write_text(json.dumps(out, indent=1))
|
||||
# replacement check: iid7 reproduces observe bit for bit; the bulk model adds one constant per well; other
|
||||
# fields never change
|
||||
D = synth_d2.D2Realization
|
||||
orig = getattr(D, "_gp_orig_observe", D.observe)
|
||||
chk = {"rids": {}}
|
||||
ok_all = True
|
||||
for rid in RIDS[:2]:
|
||||
R = realization(P, rid)
|
||||
wells = R.pool[:16]
|
||||
base7 = [orig(R, w, C, SNR, 7.0, DENS) for w in wells]
|
||||
base2 = [orig(R, w, C, SNR, 2.0, DENS) for w in wells]
|
||||
patch_observe(7.0, 0.0)
|
||||
p7 = [R.observe(w, C, SNR, 7.0, DENS) for w in wells]
|
||||
patch_observe(2.0, 5.0)
|
||||
pb = [R.observe(w, C, SNR, 7.0, DENS) for w in wells]
|
||||
same7 = all(all(np.array_equal(np.asarray(a[k]), np.asarray(b[k])) for k in a if k != "name") for a, b in zip(base7, p7))
|
||||
others = all(all(np.array_equal(np.asarray(a[k]), np.asarray(b[k])) for k in a if k not in ("name", "t_k"))
|
||||
for a, b in zip(base2, pb))
|
||||
offs = [np.unique(np.round(b["t_k"] - a["t_k"], 9)) for a, b in zip(base2, pb)]
|
||||
const = all(len(u) == 1 for u in offs)
|
||||
betas = [float(u[0]) for u in offs]
|
||||
want = [5.0 * bulk_z(rid, w.name) for w in wells]
|
||||
match = bool(np.allclose(betas, want, atol=1e-9))
|
||||
ok = same7 and others and const and match
|
||||
ok_all &= ok
|
||||
chk["rids"][str(rid)] = {"iid7_identical": same7, "bulk_other_fields_identical": others, "bulk_constant_per_well": const,
|
||||
"bulk_offsets_match": match, "beta_ms": [round(b, 4) for b in betas],
|
||||
"beta_sd_ms": float(np.std(betas, ddof=1))}
|
||||
chk["pass"] = bool(ok_all)
|
||||
(ROOT / "patch_check.json").write_text(json.dumps(chk, indent=1))
|
||||
print(json.dumps(chk, indent=1))
|
||||
if not ok_all:
|
||||
raise SystemExit("replacement check failed")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# jobs (each worker applies the replacements of its job's condition)
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def post_job(job) -> tuple[str, float]:
|
||||
cond, rid, N, P, device, mem_gb = job
|
||||
patch(cond)
|
||||
s14 = load_script("14_diag_posterior.py")
|
||||
d = cdir(cond) / "posterior" / "R10"
|
||||
LOG["anchors"].clear(), LOG["hyper"].clear()
|
||||
t0 = time.time()
|
||||
tag = s14.job_tag(rid, C, N, 0)
|
||||
s14.run_job((rid, C, N, 0, PARTICLES, P, d, device, mem_gb, st_post(cond)))
|
||||
(d / f"{tag}_e1.json").write_text(json.dumps({"condition": cond, "hyper": LOG["hyper"], "anchors": LOG["anchors"]}, indent=1))
|
||||
return f"{cond}/{tag}", time.time() - t0
|
||||
|
||||
|
||||
def train_job(job) -> tuple[str, float]:
|
||||
cond, rid, N, P, device = job
|
||||
patch(cond)
|
||||
s15 = load_script("15_diag_train.py")
|
||||
d = cdir(cond) / "train" / "R10" / "cells"
|
||||
_, dt = s15.run_cell((rid, C, N, SEEDS, 0, P, device, cdir(cond) / "posterior" / "R10", d, st_train(cond)))
|
||||
return f"{cond}/r{rid}_c1_n{N}", dt
|
||||
|
||||
|
||||
def arms_job(job) -> tuple[str, float]:
|
||||
cond, rid, N, P, device = job
|
||||
import torch
|
||||
|
||||
torch.set_num_threads(2)
|
||||
from ml_porosity.models.bank_train import train_predict
|
||||
from ml_porosity.registration.ties import warp_errors
|
||||
|
||||
patch(cond, reg_settings=True)
|
||||
s44 = load_script("44_point_tie_arm.py")
|
||||
t2.P2R = cdir(cond) # build_cell reads <cond>/posterior/R10/
|
||||
s44.P2R = cdir(cond) # point_warps reads the tempering gamma there
|
||||
t0 = time.time()
|
||||
cell = t2.build_cell("R10", rid, C, N, P, with_register=True)
|
||||
R, out, wells = cell["R"], cell["out"], cell["wells"]
|
||||
if abs(cell["reg"]["sigma_a_ms"] - CONDITIONS[cond][2]) > 1e-12:
|
||||
raise RuntimeError("registration sigma_a was not applied")
|
||||
stem = f"r{rid}_c1_n{N}"
|
||||
key = dict(condition=cond, regime="R10", rid=rid, c=C, n_train=N)
|
||||
m0, s0 = out["norm"]
|
||||
lam = out["lam"]
|
||||
tcfg = P["training"]["model"] | P["training"]["optimizer"]
|
||||
f_c = P["metrics"]["bands"]["f_c_hz"]
|
||||
nb = lambda a: ((np.asarray(a) - m0) / s0).astype(np.float32)
|
||||
pw = s44.point_warps(cell, "R10", rid, C, N)
|
||||
one = np.zeros((N, 1), np.float32)
|
||||
bank = lambda Y: {"kind": "bank", "Y": Y, "logpi": one, "lam": lam}
|
||||
specs = {"SMC-MAP": bank(nb(np.stack([cell["lab"](w["y_aa"], pw[w["name"]]["SMC-MAP"]) for w in wells]))),
|
||||
"B3d-Sa": bank(nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])))}
|
||||
diag = []
|
||||
for w in wells:
|
||||
err = lambda t: warp_errors(np.atleast_2d(t), R.tau_fine, w["o"]["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
diag.append(key | {"well": w["name"], "SMC-MAP_warp_rmse_ms": err(pw[w["name"]]["SMC-MAP"]),
|
||||
"B3d-Sa_warp_rmse_ms": err(w["tm"]), "map_rank_frac_ll": pw[w["name"]]["map_rank_frac_ll"]})
|
||||
rows = []
|
||||
for seed in SEEDS:
|
||||
for m, sp in specs.items():
|
||||
if m == "B3d-Sa" and seed != 0: # reproduction check of the scripts/15 rows
|
||||
continue
|
||||
for b, (mu, sg) in train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, [ARM_BUDGET], device).items():
|
||||
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
|
||||
for wt, r in zip(R.test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)):
|
||||
rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": wt.name} | r)
|
||||
d = cdir(cond) / "arms"
|
||||
pd.DataFrame(diag).to_csv(d / f"{stem}_diag.csv", index=False)
|
||||
pd.DataFrame(rows).to_csv(d / f"{stem}.csv", index=False) # written last: marks the job complete
|
||||
return f"{cond}/{stem}", time.time() - t0
|
||||
|
||||
|
||||
def b3p_job(job) -> tuple[str, float]:
|
||||
amodel, rid, N, P, device = job
|
||||
import torch
|
||||
|
||||
torch.set_num_threads(2)
|
||||
patch_observe(*ANCHOR_MODELS[amodel])
|
||||
s53 = load_script("53_gp_practitioner_tie.py")
|
||||
t0 = time.time()
|
||||
k = s53.selected()["R10"]
|
||||
budget = int(json.loads((E2 / "budget.json").read_text())["B3p"])
|
||||
cell = s53.make_cell("R10", rid, C, N, P, snr=SNR, dens=DENS)
|
||||
key = {"anchor_model": amodel, "regime": "R10", "rid": rid, "c": C, "n_train": N}
|
||||
rows, diag = s53.train_cell(cell, k, SEEDS, [budget], device, P, key)
|
||||
d = ROOT / "b3p" / amodel
|
||||
stem = f"r{rid}_c1_n{N}"
|
||||
pd.DataFrame(diag).to_csv(d / f"{stem}_diag.csv", index=False)
|
||||
pd.DataFrame(rows).to_csv(d / f"{stem}.csv", index=False)
|
||||
return f"b3p/{amodel}/{stem}", time.time() - t0
|
||||
|
||||
|
||||
def run_pool(fn, jobs, workers: int, label: str) -> None:
|
||||
print(f"{label}: {len(jobs)} jobs, {workers} workers", flush=True)
|
||||
if not jobs:
|
||||
return
|
||||
t0 = time.time()
|
||||
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
|
||||
futs = [ex.submit(fn, j) for j in jobs]
|
||||
for i, f in enumerate(as_completed(futs), 1):
|
||||
stem, dt = f.result()
|
||||
print(f"[{i}/{len(jobs)}] {stem} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
|
||||
|
||||
|
||||
def interleave(conds, rids) -> list[tuple]:
|
||||
"""Long jobs (N = 16) first; conditions interleaved so that partial results cover every condition."""
|
||||
return [(cond, rid, N) for N in NS for rid in rids for cond in conds]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# summary
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def side(r: dict, m: str = "pct") -> str:
|
||||
return "below" if r[f"{m}_hi"] < 1 else ("above" if r[f"{m}_lo"] > 1 else "contains")
|
||||
|
||||
|
||||
def load_runs() -> pd.DataFrame:
|
||||
parts = []
|
||||
for cond in CONDITIONS:
|
||||
cd = cdir(cond) / "train" / "R10" / "cells"
|
||||
for f in sorted(cd.glob("r*_c*_n*.csv")) if cd.exists() else []:
|
||||
if f.name.endswith("_diag.csv"):
|
||||
continue
|
||||
d = pd.read_csv(f)
|
||||
parts.append(d[d.method.isin(SEVEN) & (d.budget == d.method.map(REG_BUD))].assign(condition=cond))
|
||||
ad = cdir(cond) / "arms"
|
||||
for f in sorted(ad.glob("r*_c*_n*.csv")) if ad.exists() else []:
|
||||
if f.name.endswith("_diag.csv"):
|
||||
continue
|
||||
d = pd.read_csv(f)
|
||||
parts.append(d[d.method == "SMC-MAP"].drop(columns=["regime"], errors="ignore"))
|
||||
bd = ROOT / "b3p" / anchor_model(cond)
|
||||
for f in sorted(bd.glob("r*_c*_n*.csv")) if bd.exists() else []:
|
||||
if f.name.endswith("_diag.csv"):
|
||||
continue
|
||||
d = pd.read_csv(f)
|
||||
parts.append(d.drop(columns=["regime", "anchor_model"], errors="ignore").assign(condition=cond))
|
||||
if not parts:
|
||||
return pd.DataFrame()
|
||||
d = pd.concat(parts, ignore_index=True)
|
||||
keys = ["condition", "rid", "c", "n_train", "method", "seed", "budget"]
|
||||
num = [c for c in d.columns if c not in keys + ["test_well"] and pd.api.types.is_numeric_dtype(d[c])]
|
||||
return d.groupby(keys, as_index=False)[num].mean()
|
||||
|
||||
|
||||
def selfcheck() -> dict:
|
||||
rows = []
|
||||
for cond in CONDITIONS:
|
||||
ad = cdir(cond) / "arms"
|
||||
for f in sorted(ad.glob("r*_c*_n*.csv")) if ad.exists() else []:
|
||||
if f.name.endswith("_diag.csv"):
|
||||
continue
|
||||
a = pd.read_csv(f)
|
||||
a = a[(a.method == "B3d-Sa") & (a.seed == 0)]
|
||||
t = cdir(cond) / "train" / "R10" / "cells" / f.name
|
||||
if not t.exists():
|
||||
continue
|
||||
r = pd.read_csv(t)
|
||||
r = r[(r.method == "B3d-Sa") & (r.seed == 0) & (r.budget == ARM_BUDGET)]
|
||||
mg = a.merge(r, on=["test_well"], suffixes=("", "_reg"))
|
||||
dev = max(float((mg[c] - mg[f"{c}_reg"]).abs().max()) for c in ("band_rmse", "rmse", "nll"))
|
||||
rows.append({"condition": cond, "cell": f.stem, "n": len(mg), "abs_dev_max": dev})
|
||||
if not rows:
|
||||
return {"n_cells": 0}
|
||||
d = pd.DataFrame(rows)
|
||||
return {"n_cells": int(len(d)), "n_pass": int((d.abs_dev_max <= 1e-9).sum()), "abs_dev_max": float(d.abs_dev_max.max())}
|
||||
|
||||
|
||||
def posterior_table() -> pd.DataFrame:
|
||||
rows = []
|
||||
for cond in CONDITIONS:
|
||||
d = cdir(cond) / "posterior" / "R10"
|
||||
for f in sorted(d.glob("r*_c1_n*_s0.csv")) if d.exists() else []:
|
||||
g = pd.read_csv(f)
|
||||
smc = g[(g.method == "SMC_g_acf") & (g.wavelet == "estR")]
|
||||
row = {"condition": cond, "rid": int(g.rid.iloc[0]), "n_train": int(g.n_train.iloc[0]),
|
||||
"SMC_warp_rmse_ms": float(smc.warp_rmse_ms.mean()), "SMC_cov90": float(smc.warp_cov90.mean()),
|
||||
"SMC_width90_ms": float(smc.warp_width90_ms.mean())}
|
||||
for m in ("B3b", "B3c", "B3d"):
|
||||
row[f"{m}_warp_rmse_ms"] = float(g[(g.method == m) & (g.wavelet == "est")].warp_rmse_ms.mean())
|
||||
e = d / f.name.replace(".csv", "_e1.json")
|
||||
if e.exists():
|
||||
h = json.loads(e.read_text())["hyper"]
|
||||
if h:
|
||||
row |= {f"hyp_{k}": h[-1][k] for k in ("m_g", "sigma_g", "ell_ms", "sigma_a_ms") if k in h[-1]}
|
||||
rows.append(row)
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def stage_summary() -> None:
|
||||
out = ROOT / "summary"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
rng = np.random.default_rng(20261117)
|
||||
runs = load_runs()
|
||||
if runs.empty:
|
||||
print("E1: no cells yet")
|
||||
return
|
||||
sc = selfcheck()
|
||||
rat = []
|
||||
for (cond, N), g in runs.groupby(["condition", "n_train"]):
|
||||
have = set(g.method)
|
||||
mean = lambda m: g[g.method == m].band_rmse.mean()
|
||||
sets = {"point_ties": POINT, "with_B3p": POINT + ["B3p"], "with_B3d": POINT + ["B3d"],
|
||||
"with_B3d_B3p": POINT + ["B3d", "B3p"]}
|
||||
pairs = {}
|
||||
for sname, comp in sets.items():
|
||||
if set(comp) <= have:
|
||||
pairs[f"P1/{sname}"] = ("B3d-Sa", min(comp, key=mean))
|
||||
pairs[f"P1-M2/{sname}"] = ("M2-Sa", min(comp, key=mean))
|
||||
pairs[f"P1-MAP/{sname}"] = ("SMC-MAP", min(comp, key=mean))
|
||||
pairs |= {"P2": ("B3d-Sa", "B3d"), "P3": ("M2-Sa", "B3d-Sa"), "MAP/B3d-Sa": ("SMC-MAP", "B3d-Sa"),
|
||||
"Oracle/B3d-Sa": ("Oracle", "B3d-Sa")}
|
||||
for tag, (x, y) in pairs.items():
|
||||
if x not in have or y not in have:
|
||||
continue
|
||||
sx, sy = ci.per_rid(g, x), ci.per_rid(g, y)
|
||||
if len(sx) < len(RIDS) or len(sy) < len(RIDS):
|
||||
continue
|
||||
rat.append({"condition": cond, "n_train": N, "cmp": tag, "num": x, "den": y} | ci.intervals(sx, sy, rng))
|
||||
for pname, (a, b) in P5_PAIRS.items(): # paired over realizations, same anchors
|
||||
for N in NS:
|
||||
ga = runs[(runs.condition == a) & (runs.n_train == N)]
|
||||
gb = runs[(runs.condition == b) & (runs.n_train == N)]
|
||||
for m in ("B3d-Sa", "M2-Sa", "SMC-MAP"):
|
||||
sa, sb = ci.per_rid(ga, m), ci.per_rid(gb, m)
|
||||
if len(sa) == len(RIDS) and len(sb) == len(RIDS):
|
||||
rat.append({"condition": f"{a}|{b}", "n_train": N, "cmp": f"P5/{pname}", "num": f"{m}@{a}",
|
||||
"den": f"{m}@{b}"} | ci.intervals(sa, sb, rng))
|
||||
df = pd.DataFrame(rat)
|
||||
for m in ("pct", "bca", "t"):
|
||||
df[f"{m}_vs_1"] = [side(r, m) for _, r in df.iterrows()]
|
||||
df.to_csv(out / "ratios.csv", index=False)
|
||||
|
||||
def reading(cond: str, tag: str) -> str:
|
||||
d = df[(df.condition == cond) & (df.cmp == tag)]
|
||||
if len(d) < len(NS):
|
||||
return "incomplete"
|
||||
s = set(d.pct_vs_1)
|
||||
if s == {"below"}:
|
||||
return "gain holds"
|
||||
if "above" in s:
|
||||
return "reversed"
|
||||
if s == {"contains"}:
|
||||
return "gain lost"
|
||||
return "partial"
|
||||
|
||||
readings = {}
|
||||
for sname in ("point_ties", "with_B3p", "with_B3d", "with_B3d_B3p"):
|
||||
tag = f"P1/{sname}"
|
||||
r = {cond: reading(cond, tag) for cond in CONDITIONS}
|
||||
st = lambda conds: ("incomplete" if any(r[c] == "incomplete" for c in conds)
|
||||
else "holds" if all(r[c] == "gain holds" for c in conds) else "does not hold")
|
||||
readings[sname] = {"per_condition": r,
|
||||
"S1_more_accurate_than_assumed": st(S1),
|
||||
"S2_sigma_a_stated_correctly": st(S2),
|
||||
"S3_bulk": {k: st([c]) for k, c in S3.items()}}
|
||||
pt = posterior_table()
|
||||
if not pt.empty:
|
||||
pt.to_csv(out / "posterior_cells.csv", index=False)
|
||||
p4 = pt.groupby(["condition", "n_train"]).mean(numeric_only=True).drop(columns=["rid"]).reset_index()
|
||||
p4["n_rid"] = pt.groupby(["condition", "n_train"]).rid.nunique().values
|
||||
p4.to_csv(out / "p4_posterior.csv", index=False)
|
||||
else:
|
||||
p4 = pd.DataFrame()
|
||||
warp = []
|
||||
for cond in CONDITIONS:
|
||||
for sub, cols in (("train/R10/cells", ["B3c-R_warp_rmse_ms", "B3d-Sa_warp_rmse_ms"]), ("arms", ["SMC-MAP_warp_rmse_ms"])):
|
||||
d = cdir(cond) / sub
|
||||
for f in sorted(d.glob("*_diag.csv")) if d.exists() else []:
|
||||
g = pd.read_csv(f)
|
||||
for c_ in cols:
|
||||
if c_ in g:
|
||||
warp.append({"condition": cond, "n_train": int(g.n_train.iloc[0]), "rid": int(g.rid.iloc[0]),
|
||||
"method": c_.replace("_warp_rmse_ms", ""), "warp_rmse_ms": float(g[c_].mean())})
|
||||
d = ROOT / "b3p" / anchor_model(cond)
|
||||
for f in sorted(d.glob("*_diag.csv")) if d.exists() else []:
|
||||
g = pd.read_csv(f)
|
||||
warp.append({"condition": cond, "n_train": int(g.n_train.iloc[0]), "rid": int(g.rid.iloc[0]), "method": "B3p",
|
||||
"warp_rmse_ms": float(g.B3p_warp_rmse_ms.mean())})
|
||||
wt = pd.DataFrame(warp)
|
||||
if not wt.empty:
|
||||
wt = wt.groupby(["condition", "n_train", "method"]).warp_rmse_ms.mean().unstack("method").reset_index()
|
||||
wt.to_csv(out / "warp_rmse.csv", index=False)
|
||||
means = runs.groupby(["condition", "n_train", "method"]).agg(band_rmse=("band_rmse", "mean"), n_rid=("rid", "nunique"),
|
||||
coverage_90=("coverage_90", "mean")).reset_index()
|
||||
means.to_csv(out / "means.csv", index=False)
|
||||
verdict = {"selfcheck_B3d-Sa_seed0": sc, "readings": readings,
|
||||
"complete": {cond: {int(N): int(runs[(runs.condition == cond) & (runs.n_train == N) & (runs.method == "B3d-Sa")].rid.nunique())
|
||||
for N in NS} for cond in CONDITIONS}}
|
||||
(out / "verdict.json").write_text(json.dumps(verdict, indent=1))
|
||||
cols = ["condition", "n_train", "cmp", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "pct_vs_1"]
|
||||
order = {c: i for i, c in enumerate(CONDITIONS)}
|
||||
key = lambda s: s.map(lambda v: order.get(v, 99)) if s.name == "condition" else s
|
||||
txt = ["# E1: anchor-noise misspecification on realizations 24-31 (exploratory)", "",
|
||||
"Declared in docs/research/gp-review-experiments.md (E1). R10, c = 1, registration seed 0, training seeds 0-4.",
|
||||
"Ratios: mean band RMSE over realizations; intervals: percentile bootstrap over the 8 realizations (primary), BCa, t.", "",
|
||||
"```", json.dumps(verdict, indent=1), "```", ""]
|
||||
for title, pat in (("P1: SMC mean against the best deterministic tie", "P1/"), ("P1 for M2-Sa and SMC-MAP", "P1-"),
|
||||
("P2, P3 and others", "P2|P3|MAP/|Oracle/"), ("P5: misstated sigma_reg (paired)", "P5/")):
|
||||
d = df[df.cmp.str.contains(pat) & ~(df.cmp.str.startswith("P1-") if pat == "P1/" else False)]
|
||||
if len(d):
|
||||
txt += [f"## {title}", "", d.sort_values(["condition", "cmp", "n_train"], key=key)[cols].round(3).to_markdown(index=False), ""]
|
||||
if len(p4):
|
||||
txt += ["## P4: SMC posterior and point-tie warp RMSE (ms, training wells, main window)", "",
|
||||
p4.round(3).to_markdown(index=False), ""]
|
||||
if not wt.empty:
|
||||
txt += ["## Warp RMSE of the methods trained here (ms)", "", wt.round(3).to_markdown(index=False), ""]
|
||||
txt += ["## Mean band RMSE (p.u.)", "", means.pivot_table(index=["condition", "n_train"], columns="method",
|
||||
values="band_rmse").round(4).to_markdown(), ""]
|
||||
(out / "summary.md").write_text("\n".join(txt))
|
||||
print("\n".join(txt[:8]))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--stage", choices=["fingerprints", "post", "train", "arms", "b3p", "summary"], required=True)
|
||||
ap.add_argument("--device", default="cuda:0")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--gpu-mem-gb", type=float, default=1.5)
|
||||
ap.add_argument("--conds", nargs="+", default=list(CONDITIONS), choices=list(CONDITIONS))
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=RIDS)
|
||||
args = ap.parse_args()
|
||||
sha = check_declaration()
|
||||
P = run_d2.load_protocol(check=True)
|
||||
print(f"declaration {sha[:12]} and protocol_p2 match ({time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())})", flush=True)
|
||||
if args.stage == "fingerprints":
|
||||
stage_fingerprints(P)
|
||||
return
|
||||
if args.stage == "summary":
|
||||
stage_summary()
|
||||
return
|
||||
if not (ROOT / "fingerprints.json").exists() or not json.loads((ROOT / "patch_check.json").read_text())["pass"]:
|
||||
raise SystemExit("run --stage fingerprints first (fingerprints and replacement check)")
|
||||
rids = [r for r in args.rids if r in RIDS]
|
||||
if args.stage == "post":
|
||||
jobs = []
|
||||
for cond, rid, N in interleave(args.conds, rids):
|
||||
d = cdir(cond) / "posterior" / "R10"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
if not (d / f"r{rid}_c1_n{N}_s0.csv").exists():
|
||||
jobs.append((cond, rid, N, P, args.device, args.gpu_mem_gb))
|
||||
run_pool(post_job, jobs, args.workers, "E1 posteriors")
|
||||
elif args.stage == "train":
|
||||
jobs = []
|
||||
for cond, rid, N in interleave(args.conds, rids):
|
||||
d = cdir(cond) / "train" / "R10" / "cells"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
ready = (cdir(cond) / "posterior" / "R10" / f"r{rid}_c1_n{N}_s0.csv").exists()
|
||||
if ready and not (d / f"r{rid}_c1_n{N}.csv").exists():
|
||||
jobs.append((cond, rid, N, P, args.device))
|
||||
run_pool(train_job, jobs, args.workers, "E1 training (seven registered methods)")
|
||||
elif args.stage == "arms":
|
||||
jobs = []
|
||||
for cond, rid, N in interleave(args.conds, rids):
|
||||
d = cdir(cond) / "arms"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
ready = (cdir(cond) / "posterior" / "R10" / f"r{rid}_c1_n{N}_s0.csv").exists()
|
||||
if ready and not (d / f"r{rid}_c1_n{N}.csv").exists():
|
||||
jobs.append((cond, rid, N, P, args.device))
|
||||
run_pool(arms_job, jobs, args.workers, "E1 arms (SMC-MAP)")
|
||||
elif args.stage == "b3p":
|
||||
if not (E2 / "budget.json").exists() or not (E2 / "selected.json").exists():
|
||||
raise SystemExit("E2 select and budget must finish first")
|
||||
amodels = sorted({anchor_model(c) for c in args.conds})
|
||||
jobs = []
|
||||
for am in amodels:
|
||||
d = ROOT / "b3p" / am
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
jobs += [(am, rid, N, P, args.device) for N in NS for rid in rids if not (d / f"r{rid}_c1_n{N}.csv").exists()]
|
||||
run_pool(b3p_job, jobs, args.workers, "E1 B3p")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
36
scripts/55_gp_field_table.py
Normal file
36
scripts/55_gp_field_table.py
Normal file
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Per-well field table (review item W9). Reads outputs/gp_review/a7/a7_wells.csv (descriptive,
|
||||
exploratory, outside every lock) and writes LaTeX rows to outputs/gp_review/tables/field_wells.tex."""
|
||||
import pandas as pd, numpy as np, pathlib
|
||||
root = pathlib.Path(__file__).resolve().parents[1]
|
||||
d = pd.read_csv(root / "outputs/gp_review/a7/a7_wells.csv")
|
||||
d = d[d.reference == "calibrated"]
|
||||
NAME = {"B3b": "calibrated sonic", "B3c": "correlation tie", "B3c-R": "phase-estimated correlation"}
|
||||
def f(x, n=2): return "--" if pd.isna(x) else f"{x:.{n}f}"
|
||||
rows = []
|
||||
for (fld, split), g in d.groupby(["field", "split"], sort=False):
|
||||
for _, r in g.iterrows():
|
||||
c = r.gate_competitor
|
||||
# gate metric: band RMSE on F3, total RMSE on Volve (outputs/p3, outputs/p4/summary/gate_gd.json)
|
||||
m = "band_rmse" if fld == "F3" else "rmse"
|
||||
comp_b = r[f"{c}_{m}"]; bank_b = r[f"M2-Sa_{m}"]; mean_b = r[f"B3d-Sa_{m}"]
|
||||
rows.append(dict(field=fld, split=split.replace("nested LOWO", "nested leave-one-well-out").replace("lowo", "leave-one-well-out").replace("slot", "slot"),
|
||||
well=r.well, comp=NAME[c], comp_b=comp_b, mean_b=mean_b, bank_b=bank_b,
|
||||
bank_pcc=r["M2-Sa_band_pcc"], const=r.const_rmse,
|
||||
win=bank_b < comp_b))
|
||||
out = []
|
||||
prev = None
|
||||
for r in rows:
|
||||
key = (r["field"], r["split"])
|
||||
if key != prev:
|
||||
out.append(r"\midrule" if prev else "")
|
||||
out.append(rf"\multicolumn{{7}}{{l}}{{\emph{{{r['field']}, {r['split']}}}}} \\")
|
||||
prev = key
|
||||
out.append(f"{r['well']} & {r['comp']} & {f(r['comp_b'])} & {f(r['mean_b'])} & {f(r['bank_b'])} & {f(r['bank_pcc'])} & {f(r['const'])} \\\\")
|
||||
tex = "\n".join(o for o in out if o != "")
|
||||
(root / "outputs/gp_review/tables").mkdir(parents=True, exist_ok=True)
|
||||
(root / "outputs/gp_review/tables/field_wells.tex").write_text(tex + "\n")
|
||||
w = pd.DataFrame(rows)
|
||||
for k, g in w.groupby(["field", "split"], sort=False):
|
||||
print(k, "bank better than selected tie at", int(g.win.sum()), "of", len(g), "wells")
|
||||
print(tex)
|
||||
24
scripts/56_gp_misspec_table.py
Normal file
24
scripts/56_gp_misspec_table.py
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Misspecification table for the journal article (review item W4). Reads the locked summaries in
|
||||
outputs/bench/summary/ (s2_h2a.csv, s2_smc.csv) and outputs/gp_review/ is not needed; writes LaTeX rows to
|
||||
outputs/gp_review/tables/misspec.tex. Descriptive; no new computation."""
|
||||
import pandas as pd, pathlib
|
||||
root = pathlib.Path(__file__).resolve().parents[1]
|
||||
h = pd.read_csv(root / "outputs/bench/summary/s2_h2a.csv")
|
||||
m = pd.read_csv(root / "outputs/bench/summary/s2_smc.csv")
|
||||
h = h[h.regime == "R10"]; m = m[m.regime == "R10"]
|
||||
NAME = [("rp_L1", "Rock physics, mild"), ("rp_L2", "Rock physics, strong"),
|
||||
("wv_L1", "Wavelet phase, mild"), ("wv_L2", "Wavelet phase, strong"),
|
||||
("wv_Q", "Attenuation"), ("dr_L1", "Scaled warp prior"), ("dr_L2", "Out-of-family warp")]
|
||||
NOM = {4: (0.857, 0.805, 0.922), 16: (0.782, 0.748, 0.813)} # Table S9, hash-locked nominal cell
|
||||
NOMSMC = {4: (1.20, 0.85), 16: (0.63, 0.89)} # Table S15 (warp RMSE ms, cov90)
|
||||
def cell(r): return f"{r.ratio:.3f} [{r.ratio_lo:.3f}, {r.ratio_hi:.3f}]"
|
||||
rows = [f"Nominal (assumed model) & {NOM[4][0]:.3f} [{NOM[4][1]:.3f}, {NOM[4][2]:.3f}] & {NOM[16][0]:.3f} [{NOM[16][1]:.3f}, {NOM[16][2]:.3f}] "
|
||||
f"& {NOMSMC[4][0]:.2f} / {NOMSMC[16][0]:.2f} & {NOMSMC[4][1]:.2f} / {NOMSMC[16][1]:.2f} \\\\", r"\midrule"]
|
||||
for key, lab in NAME:
|
||||
a = h[(h.preset == key) & (h.n_train == 4)].iloc[0]; b = h[(h.preset == key) & (h.n_train == 16)].iloc[0]
|
||||
s4 = m[(m.preset == key) & (m.n_train == 4)].iloc[0]; s16 = m[(m.preset == key) & (m.n_train == 16)].iloc[0]
|
||||
rows.append(f"{lab} & {cell(a)} & {cell(b)} & {s4.warp_rmse_ms:.2f} / {s16.warp_rmse_ms:.2f} & {s4.warp_cov90:.2f} / {s16.warp_cov90:.2f} \\\\")
|
||||
(root / "outputs/gp_review/tables").mkdir(parents=True, exist_ok=True)
|
||||
(root / "outputs/gp_review/tables/misspec.tex").write_text("\n".join(rows) + "\n")
|
||||
print("\n".join(rows))
|
||||
34
scripts/run_gp_review.sh
Executable file
34
scripts/run_gp_review.sh
Executable file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# GP review, Phases 2-3 (declared in docs/research/gp-review-analyses.md and gp-review-experiments.md, hashed before
|
||||
# the first run; exploratory; outside every lock and the reproduction archives).
|
||||
# scripts/run_gp_review.sh a # A1-A9 on existing outputs (scripts/51)
|
||||
# scripts/run_gp_review.sh e5 # E5: posterior-mean labels with the Gaussian likelihood (scripts/52)
|
||||
# scripts/run_gp_review.sh e6 # E6: seven registered methods at 125/250/500 iterations (scripts/52)
|
||||
# scripts/run_gp_review.sh e4 # E4: point tie optimizing the SMC target (scripts/52)
|
||||
# scripts/run_gp_review.sh e3 # E3: one shift per well (only if A3 is not sufficient; scripts/52)
|
||||
# scripts/run_gp_review.sh e2 tune|budget|train # E2: practitioner-grade tie (scripts/53)
|
||||
# scripts/run_gp_review.sh e1 <stage> # E1: anchor-noise misspecification on realizations 24-31 (scripts/54)
|
||||
# scripts/run_gp_review.sh summary # summaries of every finished experiment
|
||||
# Every stage skips jobs that already have a CSV, so any stage can be restarted with the same command.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
DEVICE="${DEVICE:-cuda:0}"
|
||||
WORKERS="${WORKERS:-4}"
|
||||
THREADS="${THREADS:-2}"
|
||||
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
|
||||
NUMBA_NUM_THREADS=$THREADS VECLIB_MAXIMUM_THREADS=$THREADS PYTHONHASHSEED=0
|
||||
stage="$1"; shift
|
||||
echo "== gp_review $stage $* ($(date -u +%FT%TZ))"
|
||||
case "$stage" in
|
||||
a) CUDA_VISIBLE_DEVICES= "$PY" scripts/51_gp_review.py "$@" ;;
|
||||
e3|e4|e5|e6) "$PY" scripts/52_gp_experiments.py --stage "$stage" --device "$DEVICE" --workers "$WORKERS" "$@" ;;
|
||||
e2) "$PY" scripts/53_gp_practitioner_tie.py --stage "$1" --device "$DEVICE" --workers "$WORKERS" "${@:2}" ;;
|
||||
e1) "$PY" scripts/54_gp_anchor_noise.py --stage "$1" --device "$DEVICE" --workers "$WORKERS" "${@:2}" ;;
|
||||
summary)
|
||||
CUDA_VISIBLE_DEVICES= "$PY" scripts/52_gp_experiments.py --stage summary
|
||||
[[ -f scripts/53_gp_practitioner_tie.py ]] && CUDA_VISIBLE_DEVICES= "$PY" scripts/53_gp_practitioner_tie.py --stage summary || true
|
||||
[[ -f scripts/54_gp_anchor_noise.py ]] && CUDA_VISIBLE_DEVICES= "$PY" scripts/54_gp_anchor_noise.py --stage summary || true ;;
|
||||
*) echo "unknown stage $stage" >&2; exit 2 ;;
|
||||
esac
|
||||
echo "== gp_review $stage done ($(date -u +%FT%TZ))"
|
||||
Reference in New Issue
Block a user