Files
ML-Porosity/scripts/27_t3_power.py
lamlvh 0cfe202a8b 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>
2026-10-29 12:18:22 +00:00

134 lines
5.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""T3 (exploratory): power of a field test of n wells when the scoring reference is itself misregistered.
Declared in docs/research/applicability-teapot.md §3 (before this script ran). Uses only saved P2r predictions
(outputs/p2r/train/<regime>/cells/r<rid>_c1_n<N>.npz: y_true on the true warp, seed predictions). For each test
well, the reference is y_true read at t + s(t), s = a + b·x (x ∈ [-1, 1] over the window, a ~ N(0, σ_ref),
b ~ N(0, σ_ref/2)); the indicator is "seed-ensembled M2-Sa has lower band RMSE than the cell's best competitor".
Power at n wells: beta-binomial with the realization-level intra-class correlation of the indicator, for
(a) k-of-n with k = ceil(0.75 n) and (b) a one-sided sign test at α = 0.05.
python scripts/27_t3_power.py # -> outputs/t3/
"""
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
from scipy import stats
from ml_porosity.eval.metrics import band_metrics
from ml_porosity.paths import outputs_dir
OUT = outputs_dir() / "t3"
REGIMES = ("R10", "R0", "Rm5")
NS = (4, 16)
SIGMA_REF = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 8.0) # v1 grid (0, 2, 4, 8) extended 29/10, see declaration Deviation 1
DRAWS = 64
F_C, DT = 6.0, 4.0
N_TEST = np.arange(4, 41)
POWER = 0.80
def seed_mean(z, method: str) -> np.ndarray:
keys = [k for k in z.files if k.startswith(f"{method}/s") and k.endswith("/mu")]
if len(keys) != 5:
raise RuntimeError(f"{method}: expected 5 seeds, got {len(keys)}")
return np.mean([z[k] for k in keys], axis=0)
def warped(y: np.ndarray, s: np.ndarray) -> np.ndarray:
t = np.arange(y.size) * DT
return np.interp(t + s, t, y)
def indicators(rng: np.random.Generator) -> pd.DataFrame:
h2a = pd.read_csv(outputs_dir() / "p2r/summary/h2a.csv")
rows = []
for regime in REGIMES:
for n in NS:
best = h2a[(h2a.regime == regime) & (h2a.c == 1.0) & (h2a.n_train == n)].best.iloc[0]
for f in sorted((outputs_dir() / f"p2r/train/{regime}/cells").glob(f"r*_c1_n{n}.npz")):
rid = int(f.name.split("_")[0][1:])
with np.load(f) as z:
y, m2, cp = z["y_true"], seed_mean(z, "M2-Sa"), seed_mean(z, best)
x = np.linspace(-1, 1, y.shape[1])
for i in range(y.shape[0]):
for sr in SIGMA_REF:
for d in range(DRAWS if sr > 0 else 1):
s = rng.normal(0, sr) + rng.normal(0, sr / 2) * x if sr > 0 else np.zeros_like(x)
ref = warped(y[i], s)
a = band_metrics(ref, m2[i], F_C, DT)["band_rmse"]
b = band_metrics(ref, cp[i], F_C, DT)["band_rmse"]
rows.append(dict(regime=regime, n_train=n, best=best, rid=rid, well=i, sigma_ref=sr,
draw=d, ratio=a / b, better=a < b))
return pd.DataFrame(rows)
def icc(g: pd.DataFrame) -> float:
"""One-way ANOVA ICC of the binary indicator, groups = realizations (well-draw cells pooled)."""
k = g.groupby("rid").better
means, sizes = k.mean(), k.size()
n0, grand, m = sizes.mean(), g.better.mean(), len(sizes)
msb = (sizes * (means - grand) ** 2).sum() / (m - 1)
msw = ((g.better - g.rid.map(means)) ** 2).sum() / (len(g) - m)
return float(max((msb - msw) / (msb + (n0 - 1) * msw), 0.0)) if msb + msw > 0 else 0.0
def pass_prob(n: int, k: int, p: float, rho: float) -> float:
if rho <= 1e-9:
return float(stats.binom.sf(k - 1, n, p))
a, b = p * (1 / rho - 1), (1 - p) * (1 / rho - 1)
return float(stats.betabinom.sf(k - 1, n, a, b))
def sign_k(n: int, alpha: float = 0.05) -> int | None:
for k in range(n + 1):
if stats.binom.sf(k - 1, n, 0.5) <= alpha:
return k
return None
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
ind = indicators(np.random.default_rng(20261029))
ind.to_csv(OUT / "indicators.csv.gz", index=False)
cells, curves = [], []
for (regime, n_train, sr), g in ind.groupby(["regime", "n_train", "sigma_ref"]):
p, rho = float(g.better.mean()), icc(g)
cells.append(dict(regime=regime, n_train=n_train, sigma_ref=sr, p_better=p, icc=rho,
median_ratio=float(g.ratio.median()), n_rid=g.rid.nunique()))
for n in N_TEST:
ks = sign_k(int(n))
curves.append(dict(regime=regime, n_train=n_train, sigma_ref=sr, n_test=int(n),
power_k_of_n=pass_prob(int(n), int(np.ceil(0.75 * n)), p, rho),
power_sign=pass_prob(int(n), ks, p, rho) if ks is not None else 0.0))
cells, curves = pd.DataFrame(cells), pd.DataFrame(curves)
cells.to_csv(OUT / "cells.csv", index=False)
curves.to_csv(OUT / "power.csv", index=False)
nstar = []
for (regime, n_train, sr), g in curves.groupby(["regime", "n_train", "sigma_ref"]):
row = dict(regime=regime, n_train=n_train, sigma_ref=sr)
for rule in ("k_of_n", "sign"):
ok = g[g[f"power_{rule}"] >= POWER]
row[f"nstar_{rule}"] = int(ok.n_test.min()) if len(ok) else None
row[f"power4_{rule}"] = float(g[g.n_test == 4][f"power_{rule}"].iloc[0])
row[f"power6_{rule}"] = float(g[g.n_test == 6][f"power_{rule}"].iloc[0])
nstar.append(row)
nstar = pd.DataFrame(nstar).merge(cells, on=["regime", "n_train", "sigma_ref"])
nstar.to_csv(OUT / "nstar.csv", index=False)
(OUT / "meta.json").write_text(json.dumps(dict(regimes=REGIMES, n_train=NS, sigma_ref=SIGMA_REF, draws=DRAWS,
f_c_hz=F_C, power=POWER, seed=20261029), indent=2))
pd.set_option("display.width", 220)
print(nstar.round(3).to_string(index=False))
if __name__ == "__main__":
main()