Complete P4 Volve; pivot the manuscript to theory + benchmark
P4 (Volve field case). Add the deviated-well and Volve well builders (ml_porosity/data/deviated.py, volve_wells.py), the ml_porosity/volve/ pipeline, scripts 23-25, the run_p4 drivers and tests. The protocol configs/protocol_volve.yaml was locked at 2026-10-29T01:17:42Z before the run (.sha256, .lock.json) and is committed here after the run. Gate G-D failed: M2-Sa beats the selected B3 at 2/6 wells (lowo) and 3/6 (slot), coverage90 is about 0.47, and no method has blind-well skill (R2 < 0). A post hoc constant at the training-well mean beats every network, so G-D had no power. The dropped P4x exploratory run is kept as a record only (exploratory/, docs/research/p4-exploratory.md). Applicability and Teapot Dome (exploratory, pre-declared). Scripts 26-29 and docs/research/applicability-*.md: F3 and Volve fail C1 and pass C2; T3 power needs 5-18 blind wells with an exact reference; Teapot T0 and pilot P-a failed, so Teapot is stopped. Raw Teapot data stay gitignored. Manuscript (Pivot 1, level A). Reframe paper/ as a theory and synthetic benchmark paper: Propositions 3-6, Corollaries 3-4, T4 coverage (script 30) and the post hoc H2b bound check (script 31), with F3/Volve moved to Appendix B. Correct two earlier claims: the Berkson and classical bounds differ by 1.5-4.6x at the f^4-weighted band, and the bank gain exceeds the registered classical bound (7/8 wide cells at N = 16) but only 3/8 under the post hoc Berkson bound. Docs. Sync plan, AGENTS.md, README, report.html, theory and technical overview. The length pass for the venue is dropped by the user (plan section 12 item 25); the length risk stays recorded as R9. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
250
scripts/31_p2r_posthoc.py
Normal file
250
scripts/31_p2r_posthoc.py
Normal file
@@ -0,0 +1,250 @@
|
||||
"""P2r post hoc description of the H2b gains (not part of protocol_p2r; computed after the P2r verdict).
|
||||
|
||||
Reads the registered summaries in outputs/p2r/summary/ (band_rmse.csv, h2b.csv, sigma_post.csv, blur.csv) and the
|
||||
Oracle test predictions of the main run (outputs/p2r/train/<regime>/cells/r*_c*_n*.npz), and writes to
|
||||
outputs/p2r/posthoc/:
|
||||
blur_ab.csv B per regime x N x structure x sigma, pooled over c, realizations and seeds as in the registered
|
||||
blur.csv; grid = True on the registered sigma grid, False at a cell's sigma_post or warp error
|
||||
bound.csv one row per regime x c x N:
|
||||
oracle, pm, rml mean band RMSE of Oracle, B3d-Sa (posterior-mean labels) and M2-Sa (RML on the SMC bank)
|
||||
o_pm, rml_pm, rml_o ratios of these; rml_pm equals the registered H2b ratio (ratio_lo, ratio_hi: its 95% CI)
|
||||
gap_closed (pm - rml) / (pm - oracle): share of the PM-Oracle gap closed by RML
|
||||
bound_post 1/B_a at sigma_post, as registered (h2b.csv, bound_1/B; linear interpolation on the grid)
|
||||
bound_warp 1/B_a at the RMS warp error of the SMC mean warp on the training wells
|
||||
beyond_grid_* the width lies beyond the 6 ms edge of the grid; np.interp then returns 1/B_a(6 ms),
|
||||
and the bound at the width is lower
|
||||
bound_post_a_exact, bound_{post,warp}_{b,b60} 1/B of that structure, evaluated at the width itself
|
||||
bound_{post,warp}_{a,b}_spec rho* of that structure from the spectra (below), at the width itself
|
||||
exceeds_<bound> rml_pm is below the bound; ci_below_<bound>: so is the upper end of its 95% CI
|
||||
meta.json checks and counts (below)
|
||||
Structures (Proposition 3 of the paper; Gaussian time error with standard deviation sigma, constant over the window):
|
||||
a classical: the optimum of a point label is m blurred by exp(-2 pi^2 sigma^2 f^2) (scripts/17 blur(), registered)
|
||||
b Berkson: m is the optimum of the point label blurred, so that optimum is m sharpened by exp(+2 pi^2 sigma^2 f^2);
|
||||
the natural idealization for labels at a posterior-mean warp (B3d-Sa)
|
||||
b60 b with the gain held at its 60 Hz value above 60 Hz (sensitivity: sharpening also amplifies the Oracle's own
|
||||
estimation error, so the plug-in B_b overstates the distortion of m and its bound allows too large a gain)
|
||||
B is the band RMSE of the filtered Oracle predictions over that of the unfiltered ones; in population 1/B is rho*
|
||||
(paper, eq. rhostar) with the Oracle predictions in place of m. The spectral estimate keeps only the part of the Oracle
|
||||
predictions that is coherent with the label: S_m = max(Re S_mu,y, 0), with S_mu,y the cross-periodogram of the Oracle
|
||||
predictions and the true labels (mean removed, reflect-padded to L as in blur()), and rho* = (1 + D/E)^(-1/2), where D
|
||||
sums S_m (1 - exp(-x))^2 (a) or S_m (exp(x) - 1)^2 (b) over the band f >= f_c, x = 2 pi^2 sigma^2 f^2, and E sums
|
||||
S_y - S_m over the band. It leaves out the Oracle noise that the plug-in B_b amplifies, but it understates S_m when the
|
||||
Oracle predictions are shrunk towards zero. At N = 16, meta.json also gives per regime the share of the band power of the
|
||||
Oracle predictions that is coherent with the label, the share of S_m below 25 Hz, the f^4-weighted median frequency of
|
||||
S_mu and S_m (where the fourth-order distortion sits), the ratio of the (b) to the (a) distortion integrals and the
|
||||
spectral rho* on the grid. Band RMSE is computed for all wells of a cell at once and checked against band_metrics().
|
||||
Nothing here changes a registered number, and nothing is chosen with these numbers.
|
||||
|
||||
python scripts/31_p2r_posthoc.py # -> outputs/p2r/posthoc/
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.eval.metrics import band_metrics, split_bands
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
SUMMARY = outputs_dir() / "p2r" / "summary"
|
||||
TRAIN = outputs_dir() / "p2r" / "train"
|
||||
OUT = outputs_dir() / "p2r" / "posthoc"
|
||||
F_CAP_HZ = 60.0
|
||||
DT_MS, L = 4.0, 512
|
||||
F = np.fft.rfftfreq(L, DT_MS / 1000)
|
||||
BOUNDS = ["post", "warp", "post_a_exact", "post_b", "warp_b", "post_b60", "warp_b60",
|
||||
"post_a_spec", "warp_a_spec", "post_b_spec", "warp_b_spec"]
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
sp13 = load_script("13_summarize_p2.py")
|
||||
sp17 = load_script("17_summarize_p2r_dev.py")
|
||||
|
||||
|
||||
def sharpen(P: np.ndarray, sigma_ms: float, f_cap_hz: float | None = None) -> np.ndarray:
|
||||
"""scripts/17 blur() with the inverse transfer exp(+2 pi^2 sigma^2 f^2), held at its f_cap_hz value above f_cap_hz."""
|
||||
n = P.shape[1]; a = L // 2 - n // 2
|
||||
m = P.mean(1, keepdims=True)
|
||||
Pp = np.pad(P - m, ((0, 0), (a, L - n - a)), mode="reflect")
|
||||
f = F if f_cap_hz is None else np.minimum(F, f_cap_hz)
|
||||
out = np.fft.irfft(np.fft.rfft(Pp) * np.exp(2 * np.pi ** 2 * (sigma_ms / 1000) ** 2 * f ** 2), L)
|
||||
return out[:, a:a + n] + m
|
||||
|
||||
|
||||
FILTERS = {"a": sp17.blur, "b": sharpen, "b60": lambda P, s: sharpen(P, s, F_CAP_HZ)}
|
||||
|
||||
|
||||
def fft_rows(P: np.ndarray) -> np.ndarray:
|
||||
"""rfft of each row with its mean removed, reflect-padded to L as in blur()."""
|
||||
n = P.shape[1]; a = L // 2 - n // 2
|
||||
return np.fft.rfft(np.pad(P - P.mean(1, keepdims=True), ((0, 0), (a, L - n - a)), mode="reflect"))
|
||||
|
||||
|
||||
def band_rmse(hY: np.ndarray, P: np.ndarray, f_c: float) -> float:
|
||||
"""Mean over wells (rows) of band_metrics(y, p, f_c)["band_rmse"]; split_bands filters along the last axis."""
|
||||
return float(np.mean(np.sqrt(np.mean((split_bands(P, f_c)[1] - hY) ** 2, axis=1))))
|
||||
|
||||
|
||||
def x_of(sigma_ms: float) -> np.ndarray:
|
||||
return 2 * np.pi ** 2 * (sigma_ms / 1000) ** 2 * F ** 2
|
||||
|
||||
|
||||
def rho_spec(s: dict[str, np.ndarray], sigma_ms: float, kind: str, band: np.ndarray) -> float:
|
||||
"""rho* of eq. rhostar from the spectra (module docstring), structure a or b."""
|
||||
x = x_of(sigma_ms)
|
||||
Sm = np.clip(s["cross"], 0.0, None)
|
||||
g = -np.expm1(-x) if kind == "a" else np.expm1(x)
|
||||
return float((1.0 + (g ** 2 * Sm)[band].sum() / (s["y"] - Sm)[band].sum()) ** -0.5)
|
||||
|
||||
|
||||
def b_table(widths: dict[tuple[str, int], set[float]], f_c: float) -> tuple[pd.DataFrame, dict, float]:
|
||||
"""B per (regime, N, kind, sigma) over the registered grid plus the given widths; mean periodograms of the Oracle
|
||||
predictions and the labels and their cross-periodogram; largest deviation of band_rmse() from band_metrics()."""
|
||||
rows, spec, dev = [], {}, 0.0
|
||||
for reg, N in sorted(widths):
|
||||
sig = sorted(set(sp17.BLUR_SIGMAS) | widths[(reg, N)])
|
||||
acc = {"mu": [], "y": [], "cross": []}
|
||||
for fn in sorted((TRAIN / reg / "cells").glob("r*_c*_n*.npz")):
|
||||
rid, c, n = sp13.parse_tag(fn.stem)
|
||||
if n != N:
|
||||
continue
|
||||
z = np.load(fn)
|
||||
Y = z["y_true"].astype(float)
|
||||
hY, FY = split_bands(Y, f_c)[1], fft_rows(Y)
|
||||
for k in (k for k in z.files if k.startswith("Oracle/") and k.endswith("/mu")):
|
||||
P0 = z[k].astype(float)
|
||||
assert np.isfinite(Y).all() and np.isfinite(P0).all(), fn
|
||||
FM = fft_rows(P0)
|
||||
acc["mu"].append((np.abs(FM) ** 2).mean(0))
|
||||
acc["y"].append((np.abs(FY) ** 2).mean(0))
|
||||
acc["cross"].append((FM * FY.conj()).real.mean(0))
|
||||
b0 = band_rmse(hY, P0, f_c)
|
||||
dev = max(dev, abs(b0 - np.mean([band_metrics(Y[i], P0[i], f_c)["band_rmse"] for i in range(len(Y))])))
|
||||
for kind, filt in FILTERS.items():
|
||||
for s in sig:
|
||||
rows.append({"source": reg, "n_train": N, "kind": kind, "sigma_ms": s, "rid": rid, "c": c,
|
||||
"ratio": band_rmse(hY, filt(P0, s), f_c) / b0})
|
||||
spec[(reg, N)] = {k: np.mean(v, 0) for k, v in acc.items()}
|
||||
b = pd.DataFrame(rows).groupby(["source", "n_train", "kind", "sigma_ms"])["ratio"].agg(
|
||||
["mean", "min", "max", "size"]).reset_index()
|
||||
b["grid"] = b.sigma_ms.isin(sp17.BLUR_SIGMAS)
|
||||
return b, spec, dev
|
||||
|
||||
|
||||
def main() -> None:
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
f_c = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text())["metrics"]["bands"]["f_c_hz"]
|
||||
band = F >= f_c
|
||||
br = pd.read_csv(SUMMARY / "band_rmse.csv").rename(columns={"setting": "regime"})
|
||||
h2b = pd.read_csv(SUMMARY / "h2b.csv")
|
||||
sp = pd.read_csv(SUMMARY / "sigma_post.csv").rename(columns={"setting": "regime"})
|
||||
bl = pd.read_csv(SUMMARY / "blur.csv")
|
||||
t = br[["regime", "c", "n_train", "Oracle", "B3d-Sa", "M2-Sa"]].rename(
|
||||
columns={"Oracle": "oracle", "B3d-Sa": "pm", "M2-Sa": "rml"})
|
||||
t = t.merge(sp[["regime", "c", "n_train", "sigma_post_ms", "warp_rmse_ms"]], on=["regime", "c", "n_train"])
|
||||
t = t.merge(h2b[["regime", "c", "n_train", "ratio", "ratio_lo", "ratio_hi", "wide", "cell_pass", "bound_1/B"]],
|
||||
on=["regime", "c", "n_train"])
|
||||
t = t.assign(o_pm=t.oracle / t.pm, rml_pm=t.rml / t.pm, rml_o=t.rml / t.oracle,
|
||||
gap_closed=(t.pm - t.rml) / (t.pm - t.oracle))
|
||||
edge = float(bl.sigma_ms.max())
|
||||
|
||||
def inv_b(r, width: float) -> float:
|
||||
b = bl[(bl.source == r.regime) & (bl.n_train == r.n_train)].sort_values("sigma_ms")
|
||||
return 1.0 / np.interp(width, b.sigma_ms, b["mean"])
|
||||
|
||||
t["bound_post"] = t.apply(lambda r: inv_b(r, r.sigma_post_ms), axis=1)
|
||||
t["bound_warp"] = t.apply(lambda r: inv_b(r, r.warp_rmse_ms), axis=1)
|
||||
t["beyond_grid_post"] = t.sigma_post_ms > edge
|
||||
t["beyond_grid_warp"] = t.warp_rmse_ms > edge
|
||||
|
||||
widths: dict[tuple[str, int], set[float]] = {}
|
||||
for r in t.itertuples():
|
||||
widths.setdefault((r.regime, r.n_train), set()).update({float(r.sigma_post_ms), float(r.warp_rmse_ms)})
|
||||
b, spec, dev = b_table(widths, f_c)
|
||||
b.to_csv(OUT / "blur_ab.csv", index=False)
|
||||
|
||||
def inv_at(r, kind: str, width: float) -> float:
|
||||
row = b[(b.source == r.regime) & (b.n_train == r.n_train) & (b.kind == kind) & (b.sigma_ms == width)]
|
||||
return 1.0 / float(row["mean"].iloc[0])
|
||||
|
||||
width_col = {"post": "sigma_post_ms", "warp": "warp_rmse_ms"}
|
||||
t["bound_post_a_exact"] = t.apply(lambda r: inv_at(r, "a", r.sigma_post_ms), axis=1)
|
||||
for w, col in width_col.items():
|
||||
for kind in ("b", "b60"):
|
||||
t[f"bound_{w}_{kind}"] = t.apply(lambda r: inv_at(r, kind, r[col]), axis=1)
|
||||
for kind in ("a", "b"):
|
||||
t[f"bound_{w}_{kind}_spec"] = t.apply(
|
||||
lambda r: rho_spec(spec[(r.regime, r.n_train)], r[col], kind, band), axis=1)
|
||||
for k in BOUNDS:
|
||||
t[f"exceeds_{k}"] = t.rml_pm < t[f"bound_{k}"]
|
||||
t[f"ci_below_{k}"] = t.ratio_hi < t[f"bound_{k}"]
|
||||
t = t.sort_values(["n_train", "c", "sigma_post_ms"]).reset_index(drop=True)
|
||||
t.to_csv(OUT / "bound.csv", index=False)
|
||||
|
||||
reg_a = b[(b.kind == "a") & b.grid].merge(bl, on=["source", "n_train", "sigma_ms"], suffixes=("", "_reg"))
|
||||
low25 = band & (F < 25.0)
|
||||
|
||||
def f4_median(S: np.ndarray) -> float:
|
||||
w = F ** 4 * S * band
|
||||
return float(F[np.searchsorted(np.cumsum(w) / w.sum(), 0.5)])
|
||||
|
||||
def ratio_ba(S: np.ndarray, s: float) -> float:
|
||||
x = x_of(s)
|
||||
return float((np.expm1(x) ** 2 * S)[band].sum() / (np.expm1(-x) ** 2 * S)[band].sum())
|
||||
|
||||
spectral = {}
|
||||
for (reg, N), s in spec.items():
|
||||
if N != 16:
|
||||
continue
|
||||
Sm = np.clip(s["cross"], 0.0, None)
|
||||
spectral[reg] = {
|
||||
"coherent_share_of_band_power": float(Sm[band].sum() / s["mu"][band].sum()),
|
||||
"coherent_share_below_25hz": float(Sm[low25].sum() / Sm[band].sum()),
|
||||
"f4_weighted_median_hz": {"oracle": f4_median(s["mu"]), "coherent": f4_median(Sm)},
|
||||
"integral_ratio_b_over_a": {"oracle": {str(g): ratio_ba(s["mu"], g) for g in sp17.BLUR_SIGMAS},
|
||||
"coherent": {str(g): ratio_ba(Sm, g) for g in sp17.BLUR_SIGMAS}},
|
||||
"rho_spec_a_b": {str(g): [rho_spec(s, g, "a", band), rho_spec(s, g, "b", band)]
|
||||
for g in sp17.BLUR_SIGMAS}}
|
||||
wide16 = t[(t.n_train == 16) & t.wide]
|
||||
c0 = t[(t.n_train == 16) & (t.c == 0.0)]
|
||||
|
||||
def cells(mask) -> list[str]:
|
||||
return [f"{r.regime} c={r.c:g}" for r in wide16[mask].itertuples()]
|
||||
|
||||
meta = dict(
|
||||
registered_ratio_max_abs_dev=float(np.abs(t.rml_pm - t.ratio).max()),
|
||||
registered_bound_max_abs_dev=float(np.abs(t.bound_post - t["bound_1/B"]).max()),
|
||||
registered_blur_max_abs_dev=float(np.abs(reg_a["mean"] - reg_a["mean_reg"]).max()),
|
||||
registered_blur_rows_checked=int(len(reg_a)),
|
||||
band_rmse_vs_band_metrics_max_abs_dev=dev,
|
||||
n16_wide_interp_vs_exact_bound_a_max_abs_dev=float(np.abs(wide16.bound_post - wide16.bound_post_a_exact).max()),
|
||||
blur_grid_edge_ms=edge,
|
||||
f_cap_hz=F_CAP_HZ,
|
||||
n16_wide_cells=int(len(wide16)),
|
||||
n16_wide={k: {"exceeds": int(wide16[f"exceeds_{k}"].sum()), "ci_below": int(wide16[f"ci_below_{k}"].sum()),
|
||||
"cells_exceeding": cells(wide16[f"exceeds_{k}"])} for k in BOUNDS},
|
||||
n16_c0_o_pm_range=[float(c0.o_pm.min()), float(c0.o_pm.max())],
|
||||
n16_spectra=spectral,
|
||||
transfer_ratio_exp_4pi2s2f2={f"{s}ms_{fr:g}Hz": float(np.exp(4 * np.pi ** 2 * (s / 1000) ** 2 * fr ** 2))
|
||||
for s, fr in ((2.0, 25.0), (2.5, 25.0), (2.0, 60.0), (2.5, 60.0))},
|
||||
)
|
||||
(OUT / "meta.json").write_text(json.dumps(meta, indent=1))
|
||||
pd.set_option("display.width", 250)
|
||||
cols = ["regime", "c", "sigma_post_ms", "warp_rmse_ms", "o_pm", "rml_pm", "ratio_hi"] + [f"bound_{k}" for k in BOUNDS]
|
||||
print(wide16[cols].round(3).to_string(index=False))
|
||||
print(c0[["regime", "o_pm", "rml_pm", "warp_rmse_ms"]].round(3).to_string(index=False))
|
||||
print(json.dumps(meta, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user