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:
2026-10-29 12:18:22 +00:00
parent 7da6b077b6
commit 0cfe202a8b
61 changed files with 7162 additions and 881 deletions

168
scripts/26_applicability.py Normal file
View File

@@ -0,0 +1,168 @@
"""Applicability conditions C1 and C2 (docs/research/applicability-teapot.md), retrospective on F3 and Volve.
Reads only frozen outputs (outputs/p2r, outputs/p3, outputs/p4); trains nothing and never reads an outer-test label:
labels are loaded through the data view of each outer fold's training wells (F3Data / VolveData with
training_wells=T_out), which raises on any held-out well.
C1 thresholds come from the D2 cells that confirmed H2a (c = 1, R10/R0/Rm5, N = 4/16, cell_pass): minimum over
those cells of the best competitor's mean band PCC and R².
python scripts/26_applicability.py # -> outputs/applicability/
"""
from __future__ import annotations
import json
import os
os.environ.setdefault("OMP_NUM_THREADS", "2")
os.environ.setdefault("MKL_NUM_THREADS", "2")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "2")
import numpy as np
import pandas as pd
import yaml
from ml_porosity.eval.metrics import band_metrics, point_metrics
from ml_porosity.paths import REPO_ROOT, outputs_dir
OUT = outputs_dir() / "applicability"
H2A_REGIMES = ("R10", "R0", "Rm5")
WIDE_MS = 1.5
def d2_thresholds() -> tuple[dict, pd.DataFrame]:
h2a = pd.read_csv(outputs_dir() / "p2r/summary/h2a.csv")
cells = h2a[(h2a.c == 1.0) & h2a.regime.isin(H2A_REGIMES) & h2a.n_train.isin([4, 16]) & h2a.cell_pass]
rows = []
for c in cells.itertuples():
r = pd.read_csv(outputs_dir() / f"p2r/train/{c.regime}/results.csv")
r = r[(r.c == c.c) & (r.n_train == c.n_train) & (r.method == c.best)]
rows.append(dict(regime=c.regime, c=c.c, n_train=c.n_train, best=c.best, band_pcc=r.band_pcc.mean(),
r2=r.r2.mean(), pcc=r.pcc.mean(), n_rows=len(r)))
t = pd.DataFrame(rows)
return dict(tau_band_pcc=float(t.band_pcc.min()), tau_r2=float(t.r2.min()), n_cells=len(t)), t
def summarize_pairs(rows: list[dict], keys: list[str]) -> pd.DataFrame:
df = pd.DataFrame(rows)
return df.groupby(keys)[["r2", "band_pcc", "ss_const", "rmse", "rmse_const"]].mean().reset_index()
def f3_c1() -> list[dict]:
from ml_porosity.f3.data import F3Data
from ml_porosity.f3.protocol import inner_folds
from ml_porosity.f3.runner import job_path, load_bundle
p = yaml.safe_load((REPO_ROOT / "configs/protocol_f3.yaml").read_text(encoding="utf-8"))
root = outputs_dir() / "p3"
label, sa, seeds = p["data"]["primary_label"], float(p["registration"]["sigma_a_ms"]), p["split"]["seeds"]
f_c = float(p["metrics"]["f_c_hz"])
gate = json.loads((root / "summary/gate_gc.json").read_text())
competitor = {w["well"]: w["competitor"] for w in gate["per_well"]}
sel = pd.read_csv(root / "summary/selection.csv")
rows = []
for u in p["data"]["wells"]:
outer_train = tuple(w for w in p["data"]["wells"] if w != u)
view = F3Data(p, training_wells=outer_train)
for method in (competitor[u], "M2-Sa"):
s = sel[(sel.test_well == u) & (sel.method == method) & (sel.label == label) & (sel.sigma_a_ms == sa)]
budget = {int(r.seed): int(r.budget) for r in s.itertuples()}
for v, t_in in inner_folds(p["data"]["wells"], u):
assert u not in t_in and v not in t_in
y = view.y(v, "calibrated", label)
y_tr = np.concatenate([view.y(w, "calibrated", label) for w in t_in])
mu = np.mean([(z := load_bundle(job_path(root, t_in, method, label, seed, sa)))
[f"{budget[seed]}/mu"][list(z["wells"]).index(v)] for seed in seeds], axis=0)
yp, mp, cst = 100 * y, 100 * mu, 100 * y_tr.mean()
m = point_metrics(yp, mp)
rmse_c = float(np.sqrt(np.mean((yp - cst) ** 2)))
rows.append(dict(dataset="F3", scheme="lowo", test_well=u, validation=v, method=method,
role="competitor" if method != "M2-Sa" else "M2-Sa", r2=m["r2"], rmse=m["rmse"],
band_pcc=band_metrics(yp, mp, f_c, view.dt)["band_pcc"], rmse_const=rmse_c,
ss_const=1 - m["rmse"] / rmse_c))
return rows
def volve_c1() -> list[dict]:
from ml_porosity.data.volve_wells import blind_key
from ml_porosity.volve.data import VolveData, load_arrays
from ml_porosity.volve.evaluation import desc_band
from ml_porosity.volve.folds import inner_folds, outer_folds, target_name
from ml_porosity.volve.protocol import load_protocol, source_config
from ml_porosity.volve.runner import job_path, load_bundle
p = load_protocol()
p4, root = source_config(p)["p4"], outputs_dir() / "p4"
label, ref, sa, seeds = p["data"]["label"], p["data"]["primary_reference"], float(p["registration"]["sigma_a_ms"]), p["split"]["seeds"]
m_cfg = p["metrics"]
gate = json.loads((root / "summary/gate_gd.json").read_text())
sel = pd.read_csv(root / "summary/selection.csv")
arrays = load_arrays()
rows = []
for scheme in p["split"]["schemes"]:
competitor = {w["well"]: w["competitor"] for w in gate["schemes"][scheme]["per_well"]}
for u, outer_train in outer_folds(p["data"]["wells"], scheme, p4):
view = VolveData(p, training_wells=outer_train, arrays=arrays)
for method in (competitor[u], "M2-Sa"):
s = sel[(sel.scheme == scheme) & (sel.test_well == u) & (sel.method == method) & (sel.sigma_a_ms == sa)]
budget = {int(r.seed): int(r.budget) for r in s.itertuples()}
for v, t_in in inner_folds(outer_train):
assert u not in t_in and v not in t_in
y = view.y(v, ref)
ok = np.isfinite(y)
y_tr = np.concatenate([view.y(w, ref) for w in t_in])
mus = []
for seed in seeds:
z = load_bundle(job_path(root, t_in, method, label, seed, sa))
mus.append(z[f"{budget[seed]}/mu"][list(z["targets"]).index(target_name(v, blind_key(t_in)))])
mu = np.mean(mus, axis=0)
yp, mp, cst = 100 * y, 100 * mu, 100 * np.nanmean(y_tr)
m = point_metrics(yp[ok], mp[ok])
rmse_c = float(np.sqrt(np.mean((yp[ok] - cst) ** 2)))
band = desc_band(yp, mp, m_cfg["f_c_hz"], view.dt, m_cfg["desc_band_min_samples"])
rows.append(dict(dataset="Volve", scheme=scheme, test_well=u, validation=v, method=method,
role="competitor" if method != "M2-Sa" else "M2-Sa", r2=m["r2"], rmse=m["rmse"],
band_pcc=band["band_pcc"], rmse_const=rmse_c, ss_const=1 - m["rmse"] / rmse_c))
return rows
def c2() -> list[dict]:
rows = []
for f in sorted((outputs_dir() / "p3/registration").glob("*_sa7.json")):
j = json.loads(f.read_text())
if j.get("no_anchors"):
continue
rows += [dict(dataset="F3", training_set=";".join(j["training_wells"]), well=d["well"],
sigma_post_ms=d["sigma_post_ms"]) for d in j["diagnostics"]]
r = pd.read_csv(outputs_dir() / "p4/summary/registration.csv")
r = r[r.sigma_a_ms == 7.0]
rows += [dict(dataset="Volve", training_set=t.training_wells, well=t.well, sigma_post_ms=t.sigma_post_ms)
for t in r.itertuples()]
return rows
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
tau, cells = d2_thresholds()
cells.to_csv(OUT / "d2_threshold_cells.csv", index=False)
pairs = pd.DataFrame(f3_c1() + volve_c1())
pairs.to_csv(OUT / "c1_pairs.csv", index=False)
sp = pd.DataFrame(c2())
sp.to_csv(OUT / "c2_sigma_post.csv", index=False)
verdict = dict(declaration_sha256=(REPO_ROOT / "docs/research/applicability-teapot.sha256").read_text().split()[0],
thresholds=tau, wide_ms=WIDE_MS, datasets={})
for (ds, scheme), g in pairs.groupby(["dataset", "scheme"]):
comp = g[g.role == "competitor"]
c1 = dict(n_pairs=len(comp), r2_in=float(comp.r2.mean()), band_pcc_in=float(comp.band_pcc.mean()),
ss_const=float(comp.ss_const.mean()),
m2_r2_in=float(g[g.role == "M2-Sa"].r2.mean()), m2_band_pcc_in=float(g[g.role == "M2-Sa"].band_pcc.mean()))
c1["pass"] = bool(c1["band_pcc_in"] >= tau["tau_band_pcc"] and c1["r2_in"] >= tau["tau_r2"] and c1["ss_const"] > 0)
med = float(sp[sp.dataset == ds].sigma_post_ms.median())
verdict["datasets"][f"{ds}/{scheme}"] = dict(C1=c1, C2=dict(sigma_post_median_ms=med, **{"pass": med >= WIDE_MS}))
(OUT / "verdict.json").write_text(json.dumps(verdict, indent=2))
print(json.dumps(verdict, indent=2))
if __name__ == "__main__":
main()