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:
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()
|
||||
Reference in New Issue
Block a user