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

View File

@@ -204,7 +204,7 @@ def h2b() -> None:
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}})$",
bx.set(xlim=(lo, hi), ylim=(lo, hi), aspect="equal", xlabel=r"population 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$"),

View File

@@ -0,0 +1,282 @@
"""Build the P4 Volve well dataset (6 deviated wells) in the seismic time domain.
python scripts/23_build_volve_wells.py [--config configs/d3_volve.yaml]
Outputs (outputs/volve/):
volve_wells.npz flat keys "<well>/<item>", no allow_pickle needed. Time series lie on `ext_window_ms`;
`main_mask` marks the main window.
Public for a held-out well (built without its logs or picks):
times_ms, main_mask, kb_msl, survey/{md,inc,azi,tvd,x,y}
blind/<key>/{seismic_patch,md,il,xl,beyond}
input along the well path placed in time by the mean TVDSS–TWT relation of the calibrated
TDRs of the wells in <key> (`blind_key`), for every non-empty set of other wells
Private (the well's own logs and picks):
il, xl, x, y nearest bin and position at the middle of the label interval (display only)
log/md, log/<curve> depth-domain logs over the valid DT range (DT µs/m, RHOB kg/m³)
anchors_{md,tvd,twt_ms,surface,in_dt}
tdr/<name>/{md,twt_ms}, support/<name> TDR and the MD range [lo, hi] over which it places logs
<name>/<curve> log in time under TDR <name>, NaN outside its support
reference/{seismic_patch,md,tvd,il,xl,beyond}
input along the path placed by the calibrated TDR: training wells, and the
calibration-assisted setting of plan §5.2 for a test well
volve_wells_summary.json configuration and per-well QC. No statistic of the label values is computed.
"""
from __future__ import annotations
import argparse
import itertools
import json
import numpy as np
import yaml
from ml_porosity.data.deviated import (anchor_tdr, calibrated_vertical_tdr, composite_patch, path_at_times,
tdr_from_tvdss, tvdss_td_model, vertical_sonic_tdr)
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.seismic_io import SeismicCube
from ml_porosity.data.tdr import TDR, calibrate_to_anchors, sonic_tdr
from ml_porosity.data.volve_io import read_checkshot, read_horizon, read_well_picks
from ml_porosity.data.volve_wells import VolveWell, blind_key, blind_training_wells, load_volve_well
from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root
def r_(v, nd: int = 2):
"""Rounded float or list of floats for the JSON summary."""
a = np.round(np.asarray(v, dtype=float), nd)
return a.tolist() if a.ndim else float(a)
def rel_rms(a: np.ndarray, b: np.ndarray) -> float:
"""RMS(a − b) / RMS(b)."""
return float(np.sqrt(np.mean((a - b) ** 2) / np.mean(b ** 2)))
def build_tdrs(w: VolveWell, cfg: dict) -> tuple[dict[str, TDR], dict[str, tuple[float, float]]]:
"""TDRs of `w` and the MD range over which each places logs (no extrapolation of a TDR carries a log)."""
p4 = cfg["p4"]
lo, hi = w.valid_range("DT")
seg = w.logs.loc[lo:hi]
md, dt = seg.index.to_numpy(), seg["DT"].to_numpy()
za, ta = w.anchors.md.to_numpy(), w.anchors.twt_ms.to_numpy()
k = np.flatnonzero((za >= lo) & (za <= hi))[0]
tdrs, support = {}, {}
for name in p4["tdrs"]:
if name == "calibrated":
tdrs[name], support[name] = calibrated_vertical_tdr(w.traj, md, dt, za, ta, p4["edge_m"]), (lo, hi)
elif name == "sonic":
tdrs[name], support[name] = vertical_sonic_tdr(md, w.traj.at(md)[0], dt, za[k], ta[k]), (lo, hi)
elif name == "anchors":
tdrs[name], support[name] = anchor_tdr(w.traj, za, ta), (za[0], za[-1])
else:
raise ValueError(f"unsupported TDR: {name}")
for kind in p4["wells"][w.name].get("checkshots", []):
cs = read_checkshot(volve_root() / cfg["well_logs_dir"] / cfg["checkshots"][w.pick_name][kind])
tdrs[kind] = TDR.from_pairs(cs[["md", "twt_ms"]].to_numpy(), kind, drop_flat=True)
support[kind] = (float(cs.md.min()), float(cs.md.max()))
return tdrs, support
def survey_qc(w: VolveWell, picks, support: tuple[float, float]) -> dict:
tr, head = w.traj, w.header
r = tr.recompute()
s = np.linspace(*support, 200)
inc = np.interp(s, tr.md, tr.inc)
p = picks[(picks.well == w.pick_name) & picks.md.between(tr.md[0], tr.md[-1]) & picks.x.notna()]
tvd, x, y = tr.at(p.md)
return {"stations": len(tr.md), "md": r_([tr.md[0], tr.md[-1]]), "bh_tvd": r_(tr.tvd[-1]),
"header_bh_md_tvd": [head.get("Bottom Hole MD"), head.get("Bottom Hole TVD")],
"drilled_from": head.get("Drilled From"), "kick_off": head.get("Kick Off Depth"),
"recompute_max_dtvd_m": r_(np.abs(r[:, 2] - tr.tvd).max(), 3),
"recompute_max_dxy_m": r_(np.hypot(r[:, 0] - tr.x, r[:, 1] - tr.y).max(), 3),
"min_tvd_step_m": r_(np.diff(tr.tvd).min(), 3), "max_inc_deg": r_(tr.inc.max(), 1),
"inc_over_label_deg": r_([inc.min(), inc.max()], 1), "max_dls_deg_30m": r_(tr.dls().max()),
"picks_vs_survey": {"n": len(p), "max_dtvd_m": r_(np.abs(p.tvd - tvd).max(), 3),
"max_dxy_m": r_(np.hypot(p.x - x, p.y - y).max(), 3)}}
def anchor_qc(w: VolveWell, tdrs: dict[str, TDR], support: tuple[float, float]) -> dict:
"""Drift and stretch of the vertical sonic at the anchors, against the MD-integrated sonic of the F3 code."""
lo, hi = w.valid_range("DT")
seg = w.logs.loc[lo:hi]
A = w.anchors
za, ta = A.md.to_numpy(), A.twt_ms.to_numpy()
inside = (za >= lo) & (za <= hi)
zi, ti = za[inside], ta[inside]
cal, son = tdrs["calibrated"], tdrs["sonic"]
md_son = sonic_tdr(seg.index.to_numpy(), seg["DT"].to_numpy(), zi[0], ti[0])
md_cal = calibrate_to_anchors(md_son, zi, ti)
s = seg.index.to_numpy()[(seg.index >= support[0]) & (seg.index <= support[1])]
tvd_a = w.traj.at(za)[0]
fp = w.excluded[w.excluded.qlf.eq("FP") & w.excluded.md.between(lo, hi)]
return {"kept": [{"surface": r.surface, "qlf": r.qlf, "md": r.md, "twt_ms": r.twt_ms, "in_dt": bool(i)}
for r, i in zip(A.itertuples(), inside)],
"excluded": [{"surface": r.surface, "qlf": r.qlf, "md": r.md, "twt_ms": r.twt_ms, "reason": r.reason}
for r in w.excluded.itertuples()],
"calibrated_max_abs_misfit_ms": r_(np.abs(cal.time_at(za) - ta).max(), 4),
"sonic_drift_ms": r_(son.time_at(zi) - ti),
"stretch_vertical": r_(np.diff(ti) / np.diff(son.time_at(zi)), 3),
"stretch_md_sonic": r_(np.diff(ti) / np.diff(md_son.time_at(zi)), 3),
"vint_between_anchors_m_s": r_(2000.0 * np.diff(tvd_a) / np.diff(ta), 0),
"fp_misfit_ms": {r.surface: r_(cal.time_at(r.md) - r.twt_ms) for r in fp.itertuples()},
"md_minus_vertical_calibrated_ms": r_([np.min(md_cal.time_at(s) - cal.time_at(s)),
np.max(md_cal.time_at(s) - cal.time_at(s))]),
"label_below_last_anchor_m": r_(max(support[1] - za[-1], 0.0), 1),
"anchors_above_dt": A.surface[za < lo].tolist()}
def checkshot_qc(w: VolveWell, cfg: dict, cal: TDR, support: tuple[float, float]) -> dict:
out = {}
for kind, rel in cfg["checkshots"].get(w.pick_name, {}).items():
cs = read_checkshot(volve_root() / cfg["well_logs_dir"] / rel)
cs = cs[cs.md.between(w.traj.md[0], w.traj.md[-1])]
d = cal.time_at(cs.md) - cs.twt_ms.to_numpy()
lab = cs.md.between(*support).to_numpy()
upper = cs.twt_ms.between(2000, 2300).to_numpy()
za, ta = w.anchors.md.to_numpy(), w.anchors.twt_ms.to_numpy()
ok = (za >= cs.md.min()) & (za <= cs.md.max())
out[kind] = {"n": len(cs), "md": r_([cs.md.min(), cs.md.max()]),
"max_tvdss_vs_survey_m": r_(np.abs(cs.tvdss - w.traj.tvdss(cs.md)).max()),
"calibrated_minus_cs_label_ms": r_([d[lab].min(), d[lab].max()]) if lab.any() else None,
"calibrated_minus_cs_2000_2300ms": r_([d[upper].min(), d[upper].max()]) if upper.any() else None,
"picks_minus_cs_ms": r_(ta[ok] - np.interp(za[ok], cs.md, cs.twt_ms))}
return out
def path_qc(path: dict, il: np.ndarray, xl: np.ndarray, sel: np.ndarray, dt: float) -> dict:
"""Lateral extent and drift rate of the path over the samples `sel` (steps across gaps in `sel` excluded)."""
step = np.hypot(np.diff(il), np.diff(xl))[sel[:-1] & sel[1:]]
return {"extent_bins": r_(np.hypot(np.ptp(il[sel]), np.ptp(xl[sel]))),
"max_bins_per_10ms": r_(step.max() * 10.0 / dt, 3) if step.size else 0.0,
"beyond_td_frac": r_(path["beyond"][sel].mean(), 3)}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--config", default=str(REPO_ROOT / "configs" / "d3_volve.yaml"))
cfg = yaml.safe_load(open(ap.parse_args().config))
p4, root = cfg["p4"], volve_root()
names, label, rad = list(p4["wells"]), p4["label"], p4["patch_radius"]
centre = (2 * rad + 1) ** 2 // 2
picks = read_well_picks(root / cfg["picks"])
geom = read_horizon(root / cfg["horizons_twt"] / cfg["grid_horizon"]).geometry()
wells = {n: load_volve_well(n, cfg, picks) for n in names}
built = {n: build_tdrs(w, cfg) for n, w in wells.items()}
cal = {n: built[n][0]["calibrated"] for n in names}
z = np.arange(np.floor(min(w.traj.tvdss(w.traj.md[0]) for w in wells.values())),
np.ceil(max(w.traj.tvdss(w.traj.md[-1]) for w in wells.values())) + 1.0)
arrays: dict[str, np.ndarray] = {}
summary = {"config": {k: cfg[k] for k in ("cube", "picks", "grid_horizon", "anchor_exclude_surfaces")} | {"p4": p4},
"grid": {"x_coef": geom.x_coef, "y_coef": geom.y_coef, "bin_m": geom.bin_spacing()}, "wells": {}}
cache: dict = {}
with SeismicCube(root / cfg["cube"]) as cube:
win = cube.window(*p4["ext_window_ms"])
t = cube.times_ms[win]
main = (t >= p4["main_window_ms"][0]) & (t <= p4["main_window_ms"][1])
summary["samples"] = {"ext": int(t.size), "main": int(main.sum()), "dt_ms": cube.dt_ms}
for n, w in wells.items():
tdrs, support = built[n]
lab = w.label_support(label)
tr = w.traj
_, x0, y0 = tr.at(0.5 * (lab[0] + lab[1]))
il0, xl0 = geom.nearest_bin(float(x0), float(y0))
lo, hi = w.valid_range("DT")
seg = w.logs.loc[lo:hi]
A = w.anchors
a = {"times_ms": t, "main_mask": main, "kb_msl": np.float64(tr.kb_msl),
"il": np.int32(il0), "xl": np.int32(xl0), "x": np.float64(x0), "y": np.float64(y0),
"log/md": seg.index.to_numpy(dtype=float),
"anchors_md": A.md.to_numpy(), "anchors_tvd": A.tvd.to_numpy(), "anchors_twt_ms": A.twt_ms.to_numpy(),
"anchors_surface": A.surface.to_numpy(dtype=str), "anchors_in_dt": A.md.between(lo, hi).to_numpy()}
a |= {f"survey/{k}": getattr(tr, k) for k in ("md", "inc", "azi", "tvd", "x", "y")}
a |= {f"log/{c}": seg[c].to_numpy(dtype=float) for c in p4["curves"]}
labels = {}
for name, tdr in tdrs.items():
a[f"tdr/{name}/md"], a[f"tdr/{name}/twt_ms"] = tdr.md, tdr.twt_ms
a[f"support/{name}"] = np.asarray(support[name], dtype=float)
part = w.logs.loc[support[name][0]:support[name][1]]
for c in p4["curves"]:
a[f"{name}/{c}"] = log_to_time(part.index.to_numpy(), part[c].to_numpy(), tdr, t, **p4["resample"])
ok = np.isfinite(a[f"{name}/{label}"])
labels[name] = {"n_main": int(ok[main].sum()), "n_outside_main": int(ok[~main].sum()),
"t_ms": r_([t[ok].min(), t[ok].max()], 0) if ok.any() else None}
# input along the calibrated path (reference) and along the blind paths
ref = path_at_times(tr, cal[n], t)
il, xl = geom.xy_to_bin(ref["x"], ref["y"])
patch = composite_patch(cube, il, xl, t, rad, p4["patch_method"], cache)
a |= {"reference/seismic_patch": patch, "reference/md": ref["md"], "reference/tvd": ref["tvd"],
"reference/il": il, "reference/xl": xl, "reference/beyond": ref["beyond"]}
nearest = composite_patch(cube, il, xl, t, rad, "nearest", cache)
vertical = cube.patch(il0, xl0, rad)[:, win]
sel_lab = np.isfinite(a[f"calibrated/{label}"])
others = [v for v in names if v != n]
for k in range(1, len(others) + 1):
for S in itertools.combinations(others, k):
tb = tdr_from_tvdss(tr, z, tvdss_td_model([wells[v].traj for v in S], [cal[v] for v in S], z))
pb = path_at_times(tr, tb, t)
ib, jb = geom.xy_to_bin(pb["x"], pb["y"])
key = f"blind/{blind_key(S)}"
a |= {f"{key}/seismic_patch": composite_patch(cube, ib, jb, t, rad, p4["patch_method"], cache),
f"{key}/md": pb["md"], f"{key}/il": ib, f"{key}/xl": jb, f"{key}/beyond": pb["beyond"]}
blind = {}
za, ta = A.md.to_numpy(), A.twt_ms.to_numpy()
s = seg.index.to_numpy()[(seg.index >= lab[0]) & (seg.index <= lab[1])]
for scheme in p4["blind_schemes"]:
S = blind_training_wells(n, scheme, p4)
key = f"blind/{blind_key(S)}"
tb = tdr_from_tvdss(tr, z, tvdss_td_model([wells[v].traj for v in S], [cal[v] for v in S], z))
pb = path_at_times(tr, tb, t)
off = np.hypot(pb["x"] - ref["x"], pb["y"] - ref["y"])[sel_lab]
blind[scheme] = {"training_wells": list(S),
"td_misfit_at_anchors_ms": r_([np.mean(tb.time_at(za) - ta),
np.abs(tb.time_at(za) - ta).max()]),
"minus_calibrated_over_label_ms": r_([np.min(tb.time_at(s) - cal[n].time_at(s)),
np.max(tb.time_at(s) - cal[n].time_at(s))]),
"max_offset_from_reference_m": r_(off.max(), 1),
"rel_rms_vs_reference_main": r_(rel_rms(a[f"{key}/seismic_patch"][centre][main],
patch[centre][main]), 3)}
dt_lab = w.logs.loc[lab[0]:lab[1], "DT"]
ok_dt = dt_lab.notna().to_numpy()
# beyond this range the calibrated TDR (and so the reference path) is an extension at constant velocity
constrained = [min(lo, za[0]), max(hi, za[-1])]
info = {"survey": survey_qc(w, picks, lab),
"logs": w.qc | {"dt_md": r_([lo, hi], 1), "label_md": r_(lab, 1),
"label_twt_ms": r_(cal[n].time_at(np.asarray(lab)), 1),
"calibrated_constrained_twt_ms": r_(cal[n].time_at(np.asarray(constrained)), 1),
"dt_nan_frac_in_label": r_(1 - ok_dt.mean(), 3),
"dt_longest_gap_in_label_m": r_(np.diff(dt_lab.index.to_numpy()[ok_dt]).max(), 2)},
"anchors": anchor_qc(w, tdrs, lab),
"checkshots": checkshot_qc(w, cfg, cal[n], lab),
"label_samples": labels,
"bin": [il0, xl0], "xy": r_([x0, y0], 1),
"path": {"label": path_qc(ref, il, xl, sel_lab, cube.dt_ms),
"main": path_qc(ref, il, xl, main, cube.dt_ms),
"ext": path_qc(ref, il, xl, np.ones_like(main), cube.dt_ms)},
"seismic": {"rel_rms_bilinear_vs_nearest_main": r_(rel_rms(nearest[centre][main],
patch[centre][main]), 3),
"rel_rms_vertical_vs_composite_main": r_(rel_rms(vertical[centre][main],
patch[centre][main]), 3),
"rel_rms_vertical_vs_composite_label": r_(rel_rms(vertical[centre][sel_lab],
patch[centre][sel_lab]), 3)},
"blind": blind}
summary["wells"][n] = info
arrays |= {f"{n}/{k}": v for k, v in a.items()}
q = info["anchors"]
print(f"{n}: {len(A)} anchors ({sum(r['in_dt'] for r in q['kept'])} in DT), label {lab[0]:.1f}–{lab[1]:.1f} m"
f" = {labels['calibrated']['n_main']} samples, {q['label_below_last_anchor_m']:.0f} m below last"
f" anchor; path {info['path']['label']['extent_bins']:.1f} bins over the label;"
f" blind lowo/slot misfit {blind['lowo']['td_misfit_at_anchors_ms'][1]:.1f}/"
f"{blind['slot']['td_misfit_at_anchors_ms'][1]:.1f} ms max")
out = outputs_dir() / "volve"
out.mkdir(parents=True, exist_ok=True)
np.savez_compressed(out / "volve_wells.npz", **arrays)
(out / "volve_wells_summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False, default=float))
print(f"-> {out / 'volve_wells.npz'} ({len(arrays)} arrays)")
if __name__ == "__main__":
main()

69
scripts/24_run_volve.py Normal file
View File

@@ -0,0 +1,69 @@
"""P4 Volve: lock -> register -> train -> summarize (configs/protocol_volve.yaml).
Full run on the run machine: python scripts/24_run_volve.py all --device cuda:0 --workers 4
Then the σ_a arms: python scripts/24_run_volve.py all --arms sensitivity, then summarize --arms all
Smoke (CPU, reduced settings, outputs/p4/smoke): register/train only until the protocol is locked; never a result.
"""
from __future__ import annotations
import argparse
import os
import traceback
os.environ.setdefault("OMP_NUM_THREADS", "2")
os.environ.setdefault("MKL_NUM_THREADS", "2")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "2")
os.environ.setdefault("NUMBA_NUM_THREADS", "2")
os.environ.setdefault("PYTHONHASHSEED", "0")
os.environ.setdefault("PYTHONUTF8", "1")
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
def main() -> None:
from ml_porosity.paths import outputs_dir
from ml_porosity.volve.protocol import freeze, load_protocol
from ml_porosity.volve.runner import benchmark, progress, run
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("stage", choices=["status", "benchmark", "lock", "register", "train", "summarize", "all"])
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--arms", choices=["primary", "sensitivity", "all"], default="primary")
ap.add_argument("--smoke", action="store_true")
ap.add_argument("--benchmark-steps", type=int, default=100)
args = ap.parse_args()
if args.workers < 1:
ap.error("--workers must be positive")
p = load_protocol()
root = outputs_dir() / "p4" / ("smoke" if args.smoke else "")
if os.name == "nt":
import ctypes
# Prevent automatic system sleep only while this process is alive.
ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
try:
if args.stage == "status":
path = root / "progress.json"
print(path.read_text(encoding="utf-8") if path.exists() else "P4 has not started.")
elif args.stage == "benchmark":
print(benchmark(p, args.device, args.benchmark_steps))
elif args.stage == "lock":
print(freeze())
else:
stages = ["register", "train", "summarize"] if args.stage == "all" else [args.stage]
if args.smoke and args.stage == "all":
stages = ["register", "train"] # summarize needs the lock, see runner.run
for stage in stages:
run(stage, p, args.device, args.workers, args.smoke, args.arms)
except Exception as exc:
if args.stage not in ("status", "lock", "benchmark"):
progress(root, status=f"error in {args.stage}; completed jobs can resume", error=str(exc))
traceback.print_exc()
raise SystemExit(1)
finally:
if os.name == "nt":
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
if __name__ == "__main__":
main()

62
scripts/25_p4_posthoc.py Normal file
View File

@@ -0,0 +1,62 @@
"""P4 Volve post hoc description (not part of protocol_volve; computed after G-D, for scale only).
Reads the registered combined-ensemble predictions (outputs/p4/summary/predictions.npz) and the calibrated reference,
and writes outputs/p4/posthoc/:
wells.csv per scheme and outer well: label statistics, a constant prediction at the pooled label mean of the outer
training wells (no seismic), and, per method (σ_a = 7 ms), RMSE split into mean bias and the SD of the error.
macro.csv the same, unweighted mean over wells per scheme.
Nothing here chooses a method, budget or setting, and no G-D number is changed.
"""
from __future__ import annotations
import json
import numpy as np
import pandas as pd
from ml_porosity.paths import outputs_dir
from ml_porosity.volve.data import VolveData, load_arrays
from ml_porosity.volve.folds import outer_folds
from ml_porosity.volve.protocol import load_protocol, source_config
def main() -> None:
p = load_protocol()
ref, sa = p["data"]["primary_reference"], p["registration"]["sigma_a_ms"]
full = VolveData(p, arrays=load_arrays())
summary = outputs_dir() / "p4" / "summary"
index = json.loads((summary / "prediction_index.json").read_text(encoding="utf-8"))
with np.load(summary / "predictions.npz") as z:
mu = {i: 100 * z[f"{i}/mu"] for i, e in enumerate(index)
if str(e["seed"]) == "ensemble" and e["sigma_a_ms"] == sa}
rows = []
for scheme in p["split"]["schemes"]:
for test, train in outer_folds(p["data"]["wells"], scheme, source_config(p)["p4"]):
y = 100 * full.y(test, ref)
ok = np.isfinite(y)
pooled = np.concatenate([100 * full.y(w, ref) for w in train])
const = float(np.nanmean(pooled))
row = dict(scheme=scheme, well=test, n=int(ok.sum()), label_mean=float(y[ok].mean()),
label_sd=float(y[ok].std()), train_mean=const,
const_rmse=float(np.sqrt(np.mean((const - y[ok]) ** 2))), const_bias=const - float(y[ok].mean()))
for i, e in enumerate(index):
if i in mu and e["scheme"] == scheme and e["test_well"] == test:
err = mu[i][ok] - y[ok]
m = e["method"]
row |= {f"{m}/rmse": float(np.sqrt(np.mean(err ** 2))), f"{m}/bias": float(err.mean()),
f"{m}/err_sd": float(err.std()), f"{m}/pred_sd": float(mu[i][ok].std())}
rows.append(row)
wells = pd.DataFrame(rows)
out = outputs_dir() / "p4" / "posthoc"
out.mkdir(parents=True, exist_ok=True)
wells.to_csv(out / "wells.csv", index=False, float_format="%.4f")
numeric = wells.drop(columns=["well"])
macro = numeric.groupby("scheme").mean()
abs_bias = wells.filter(like="bias").abs().groupby(wells.scheme).mean().add_prefix("abs_")
macro.join(abs_bias).to_csv(out / "macro.csv", float_format="%.4f")
print(macro.join(abs_bias).T.to_string(float_format="%.3f"))
if __name__ == "__main__":
main()

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()

133
scripts/27_t3_power.py Normal file
View File

@@ -0,0 +1,133 @@
"""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()

View File

@@ -0,0 +1,170 @@
"""T0 inventory of the Teapot Dome (NPR-3, RMOTC) archive (docs/research/applicability-teapot.md §4).
Reads headers and curve support only: which wells have density / neutron / sonic, over which depths, where they
are, whether they fall inside the 3D footprint, and which files look like checkshots, VSP, time-depth tables,
tops or deviation surveys. Computes no porosity-versus-seismic relation and trains nothing, so it is not a look
at test labels. Self-contained (no ml_porosity import); run with `python -P` from the repo root so nothing inside the untrusted
archive can land on sys.path (`-I` would also hide segyio, which is in the user site-packages here).
python -P scripts/28_teapot_inventory.py --root data/Teapot/raw/rmotc --out outputs/teapot/inventory
"""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
import numpy as np
import pandas as pd
GROUPS = {
"density": ("RHOB", "RHOZ", "ZDEN", "DEN", "RHO", "DENS", "ZDNC"),
"neutron": ("NPHI", "NPOR", "CNL", "TNPH", "NPHS", "CNC", "NEU", "NPHIL"),
"sonic": ("DT", "DTC", "AC", "DT4P", "DTCO", "SON", "DELT"),
"dens_porosity": ("DPHI", "DPHZ", "PHID", "DPOR", "DPHS"),
"porosity": ("PHIE", "PHIT", "POR"),
"gamma": ("GR", "GRD", "GRR", "SGR", "CGR"),
}
SPECIAL = re.compile(r"check.?shot|checkshot|\bcs\b|vsp|velocity|vel_|t-?d|time.?depth|tdr|tops?|marker|"
r"formation|deviat|direction|survey|header|location|coord", re.I)
SEGY_EXT = {".sgy", ".segy", ".sgy.gz"}
def group_of(mnemonic: str) -> str | None:
m = re.sub(r"[^A-Z0-9]", "", mnemonic.upper())
for g, names in GROUPS.items():
if any(m == n or (m.startswith(n) and len(m) <= len(n) + 2) for n in names):
return g
return None
def header_value(las, *keys):
for section in (las.well, las.params):
for k in keys:
if k in section and str(section[k].value).strip() not in ("", "nan"):
return section[k].value
return None
def scan_las(path: Path) -> dict:
import lasio
las = lasio.read(path, ignore_header_errors=True, engine="normal")
depth = las.index.astype(float)
row = dict(file=str(path), well=str(header_value(las, "WELL") or path.stem), uwi=header_value(las, "UWI", "API"),
x=header_value(las, "X", "XCOORD", "XWELL", "EAST"), y=header_value(las, "Y", "YCOORD", "YWELL", "NORTH"),
lat=header_value(las, "LAT", "LATI"), lon=header_value(las, "LON", "LONG"),
loc=header_value(las, "LOC"), kb=header_value(las, "EKB", "KB", "ELZ", "EREF", "EDF"),
gl=header_value(las, "EGL", "GL", "ELEV"), depth_unit=str(las.index_unit),
strt=float(np.nanmin(depth)) if depth.size else np.nan,
stop=float(np.nanmax(depth)) if depth.size else np.nan, curves=";".join(c.mnemonic for c in las.curves))
for g in GROUPS:
row[f"{g}_curve"], row[f"{g}_top"], row[f"{g}_base"], row[f"{g}_n"] = None, np.nan, np.nan, 0
for c in las.curves[1:]:
g = group_of(c.mnemonic)
if g is None:
continue
ok = np.isfinite(c.data.astype(float))
if ok.sum() > row[f"{g}_n"]:
row[f"{g}_curve"], row[f"{g}_n"] = c.mnemonic, int(ok.sum())
row[f"{g}_top"], row[f"{g}_base"] = float(depth[ok].min()), float(depth[ok].max())
return row
def scan_segy(path: Path) -> tuple[dict, np.ndarray]:
import segyio
with segyio.open(path, ignore_geometry=True) as f:
n = f.tracecount
h = f.attributes
sc = np.asarray(h(segyio.TraceField.SourceGroupScalar)[:], float)
scale = np.where(sc < 0, -1 / np.where(sc == 0, 1, sc), np.where(sc == 0, 1, sc))
out = dict(file=str(path), traces=int(n), samples=int(len(f.samples)), dt_ms=float(segyio.tools.dt(f) / 1000),
t0_ms=float(f.samples[0]), t1_ms=float(f.samples[-1]))
for name, field in (("cdp_x", segyio.TraceField.CDP_X), ("cdp_y", segyio.TraceField.CDP_Y),
("src_x", segyio.TraceField.SourceX), ("src_y", segyio.TraceField.SourceY)):
v = np.asarray(h(field)[:], float) * scale
out[f"{name}_min"], out[f"{name}_max"] = float(v.min()), float(v.max())
for name, byte in (("il189", 189), ("xl193", 193), ("il9", 9), ("xl21", 21), ("il181", 181), ("xl185", 185)):
v = np.asarray(h(byte)[:], float)
out[f"{name}_min"], out[f"{name}_max"], out[f"{name}_unique"] = float(v.min()), float(v.max()), int(np.unique(v).size)
xs = np.asarray(h(segyio.TraceField.CDP_X)[:], float) * scale
ys = np.asarray(h(segyio.TraceField.CDP_Y)[:], float) * scale
return out, np.column_stack([xs, ys])
def inside_hull(points: np.ndarray, hull_xy: np.ndarray) -> np.ndarray:
from matplotlib.path import Path as MPath
from scipy.spatial import ConvexHull
hull = hull_xy[ConvexHull(hull_xy).vertices]
return MPath(hull).contains_points(points)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", type=Path, required=True)
ap.add_argument("--out", type=Path, required=True)
args = ap.parse_args()
args.out.mkdir(parents=True, exist_ok=True)
files = sorted(p for p in args.root.rglob("*") if p.is_file())
pd.DataFrame(dict(file=[str(p.relative_to(args.root)) for p in files], suffix=[p.suffix.lower() for p in files],
bytes=[p.stat().st_size for p in files])).to_csv(args.out / "files.csv", index=False)
special = [str(p.relative_to(args.root)) for p in files if SPECIAL.search(p.name) or SPECIAL.search(p.parent.name)]
(args.out / "special_files.txt").write_text("\n".join(special))
las_rows, errors = [], []
for p in files:
if p.suffix.lower() == ".las":
try:
las_rows.append(scan_las(p))
except Exception as exc: # malformed legacy LAS: record and continue
errors.append(dict(file=str(p), error=repr(exc)[:300]))
las = pd.DataFrame(las_rows)
pd.DataFrame(errors).to_csv(args.out / "las_errors.csv", index=False)
segy, hull = [], None
for p in files:
if "".join(p.suffixes).lower() in SEGY_EXT or p.suffix.lower() in SEGY_EXT:
try:
info, xy = scan_segy(p)
segy.append(info)
if hull is None or len(xy) > len(hull):
hull = xy[np.isfinite(xy).all(axis=1) & (np.abs(xy).sum(1) > 0)]
except Exception as exc:
segy.append(dict(file=str(p), error=repr(exc)[:300]))
pd.DataFrame(segy).to_csv(args.out / "segy.csv", index=False)
if len(las):
for c in ("x", "y"):
las[c] = pd.to_numeric(las[c], errors="coerce")
las["inside_3d"] = pd.Series(pd.NA, index=las.index, dtype="boolean")
ok = las[["x", "y"]].notna().all(axis=1)
if hull is not None and len(hull) >= 3 and ok.any():
las.loc[ok, "inside_3d"] = inside_hull(las.loc[ok, ["x", "y"]].to_numpy(), hull)
las.to_csv(args.out / "las_wells.csv", index=False)
has = lambda g: las[f"{g}_n"] > 0 if len(las) else pd.Series(dtype=bool)
summary = dict(
files=len(files), las_files=int(len(las)), las_errors=len(errors), segy_files=len(segy), segy_errors=sum("error" in r for r in segy),
unique_wells=int(las.well.nunique()) if len(las) else 0,
with_density=int(has("density").sum()) if len(las) else 0,
with_density_or_dphi=int((has("density") | has("dens_porosity")).sum()) if len(las) else 0,
with_neutron=int(has("neutron").sum()) if len(las) else 0,
with_sonic=int(has("sonic").sum()) if len(las) else 0,
with_density_and_sonic=int((has("density") & has("sonic")).sum()) if len(las) else 0,
with_coordinates=int(las[["x", "y"]].notna().all(axis=1).sum()) if len(las) else 0,
inside_3d=int(las.inside_3d.fillna(False).sum()) if len(las) and "inside_3d" in las else None,
inside_3d_density_and_sonic=int((las.inside_3d.fillna(False) & has("density") & has("sonic")).sum())
if len(las) and "inside_3d" in las else None,
special_files=len(special),
note="Counts are per LAS file; several files can belong to one well. Checkshot/VSP presence must be confirmed "
"by reading special_files.txt, not by these counts.")
(args.out / "summary.json").write_text(json.dumps(summary, indent=2))
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()

268
scripts/29_teapot_pilot.py Normal file
View File

@@ -0,0 +1,268 @@
"""Teapot pilot P-a (docs/research/applicability-teapot.md, Deviation 2): geometry, horizon coverage, σ_knot.
Dev wells only (projected inline ≤ 200); no porosity value is read. Knot = (time of a 3D horizon at the well,
depth of the matching formation top): Carlile ↔ CRLL, KF2 ↔ F2WC. σ̂_knot (M1, decisive) = pooled RMS of
t_obs − 2 z / V̂, with V̂ a leave-one-out quadratic trend in (inline, xline) of the average velocity 2 z / t and
z the TVD below the 5500 ft seismic datum. M2 (sonic interval check) and the 48-X-28 table are reported only.
python -P scripts/29_teapot_pilot.py # -> outputs/teapot/pilot_pa/
"""
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")
from pathlib import Path
import numpy as np
import pandas as pd
REPO = Path(__file__).resolve().parents[1]
RAW = REPO / "data/Teapot/raw/rmotc/DataSets"
WELLS_DIR, SEIS_DIR = RAW / "Well Log/CD Files", RAW / "Seismic/CD files"
OUT = REPO / "outputs/teapot/pilot_pa"
DATUM_FT, DEV_MAX_INLINE = 5500.0, 200.0
KNOTS = {"Carlile": "CRLL", "KF2": "F2WC"} # FormationCodes.doc (KF2) and name match (Carlile)
N_TEST = 115
SIGMA_TOL_MS, COVERAGE_MIN = 1.5, 0.80 # Deviation 2: N*(Rm5, N_train=16) <= 115 -> 1.5 ms
RNG = np.random.default_rng(20261029)
def headers() -> pd.DataFrame:
h = pd.read_excel(WELLS_DIR / "TeapotDomeWellHeaders02-09-10.xlsx", header=1)
h["api12"] = h["API Number"].astype(str).str[:12]
h = h.drop_duplicates("api12").set_index("api12")
return h.rename(columns={"Easting": "E", "Northing": "N", "Datum Elevation": "kb", "Well Number": "well"})
def horizons() -> tuple[pd.DataFrame, np.ndarray, np.ndarray]:
hz = pd.read_csv(SEIS_DIR / "3D_Seismic/3DHorizons.xyz", sep="\t", usecols=range(9))
a = np.c_[hz.X, hz.Y, np.ones(len(hz))]
return hz, np.linalg.lstsq(a, hz.inline, rcond=None)[0], np.linalg.lstsq(a, hz.xline, rcond=None)[0]
def project(e, n, ci, cx):
b = np.c_[np.asarray(e, float), np.asarray(n, float), np.ones(np.size(e))]
return b @ ci, b @ cx
def surveys() -> dict[str, np.ndarray]:
d = pd.read_excel(WELLS_DIR / "DirectionalSurveys_020910.xlsx", header=None)
api = pd.to_numeric(d[0], errors="coerce")
d = d[api.notna()].copy()
d[0] = api[api.notna()].astype(np.int64).astype(str).str[:12]
for c in (1, 2, 3): # a few MD cells carry text such as "2878+"
d[c] = pd.to_numeric(d[c].astype(str).str.rstrip("+"), errors="coerce")
d = d.dropna(subset=[1, 2, 3])
return {k: g[[1, 2, 3]].to_numpy() for k, g in d.groupby(0)}
def min_curvature(st: np.ndarray, md: float) -> tuple[float, float, float]:
"""TVD, dN, dE (ft) at measured depth md from (MD, inclination, azimuth) stations."""
st = st[np.argsort(st[:, 0])]
if st[0, 0] > 0:
st = np.vstack([[0, 0, 0], st])
if md > st[-1, 0]:
st = np.vstack([st, [md, st[-1, 1], st[-1, 2]]])
tvd = dn = de = 0.0
for (m1, i1, a1), (m2, i2, a2) in zip(st[:-1], st[1:]):
if m1 >= md:
break
if m2 > md: # inclination/azimuth held over the partial segment
m2, i2, a2 = md, i1 + (i2 - i1) * (md - m1) / (m2 - m1), a1 + (a2 - a1) * (md - m1) / (m2 - m1)
i1, i2, a1, a2 = np.radians([i1, i2, a1, a2])
dl = np.arccos(np.clip(np.cos(i2 - i1) - np.sin(i1) * np.sin(i2) * (1 - np.cos(a2 - a1)), -1, 1))
rf = 1.0 if dl < 1e-9 else 2 / dl * np.tan(dl / 2)
h = (m2 - m1) / 2 * rf
dn += h * (np.sin(i1) * np.cos(a1) + np.sin(i2) * np.cos(a2))
de += h * (np.sin(i1) * np.sin(a1) + np.sin(i2) * np.sin(a2))
tvd += h * (np.cos(i1) + np.cos(i2))
return tvd, dn, de
def horizon_grid(hz: pd.DataFrame, name: str) -> np.ndarray:
g = np.full((346, 189), np.nan)
s = hz[(hz.Horizon == name) & (hz.Time > 0)]
g[s.inline.to_numpy(int), s.xline.to_numpy(int)] = 1000 * s.Time.to_numpy()
return g
def sample(g: np.ndarray, il: float, xl: float) -> tuple[float, str]:
i0, x0 = int(np.floor(il)), int(np.floor(xl))
if 1 <= i0 < 345 and 1 <= x0 < 188:
q = g[i0:i0 + 2, x0:x0 + 2]
if np.isfinite(q).all():
fi, fx = il - i0, xl - x0
return float(q[0, 0] * (1 - fi) * (1 - fx) + q[1, 0] * fi * (1 - fx) + q[0, 1] * (1 - fi) * fx + q[1, 1] * fi * fx), "bilinear"
best = (np.inf, np.nan)
for di in (-1, 0, 1, 2):
for dx in (-1, 0, 1, 2):
i, x = i0 + di, x0 + dx
if 1 <= i <= 345 and 1 <= x <= 188 and np.isfinite(g[i, x]):
r = np.hypot(i - il, x - xl)
best = min(best, (r, g[i, x]))
return (float(best[1]), "nearest") if best[0] <= 1.5 else (np.nan, "none")
def quad(il, xl):
u, v = (np.asarray(il) - 250) / 100, (np.asarray(xl) - 94) / 100
return np.c_[np.ones_like(u), u, v, u * u, v * v, u * v]
def m1_residuals(k: pd.DataFrame) -> pd.DataFrame:
rows = []
for hname, g in k.dropna(subset=["t_ms", "z_ft"]).groupby("horizon"):
v = 2 * g.z_ft.to_numpy() / (g.t_ms.to_numpy() / 1000)
x = quad(g.il_top, g.xl_top)
for j in range(len(g)):
m = np.arange(len(g)) != j
coef = np.linalg.lstsq(x[m], v[m], rcond=None)[0]
vhat = float(x[j] @ coef)
rows.append(dict(api12=g.index[j], horizon=hname, t_ms=g.t_ms.iloc[j], v_obs=v[j], v_hat=vhat,
resid_ms=g.t_ms.iloc[j] - 2000 * g.z_ft.iloc[j] / vhat))
return pd.DataFrame(rows)
def boot_rms(r: pd.DataFrame, n: int = 4000) -> tuple[float, float]:
wells = r.api12.unique()
by = {w: r[r.api12 == w].resid_ms.to_numpy() for w in wells}
s = [np.sqrt(np.mean(np.concatenate([by[w] for w in RNG.choice(wells, len(wells))]) ** 2)) for _ in range(n)]
return float(np.quantile(s, 0.05)), float(np.quantile(s, 0.95))
def segy_check(k: pd.DataFrame) -> pd.DataFrame:
"""Horizon pick vs nearest same-polarity extremum of the 3D trace (QC only)."""
import segyio
with segyio.open(SEIS_DIR / "3D_Seismic/filt_mig.sgy", ignore_geometry=True) as f:
il = np.asarray(f.attributes(181)[:]); xl = np.asarray(f.attributes(185)[:])
idx = {(int(a), int(b)): i for i, (a, b) in enumerate(zip(il, xl))}
rows = []
for hname, g in k.dropna(subset=["t_ms"]).groupby("horizon"):
amps, offs = [], []
for r in g.itertuples():
tr = f.trace[idx[(int(round(r.il_top)), int(round(r.xl_top)))]]
j = int(round(r.t_ms / 2))
amps.append(tr[j]); offs.append((tr, j))
pol = np.sign(np.median(amps))
for (tr, j), api in zip(offs, g.index):
w = pol * tr[max(j - 6, 0):j + 7]
ext = [q for q in range(1, len(w) - 1) if w[q] >= w[q - 1] and w[q] >= w[q + 1]]
c = min(ext, key=lambda q: abs(q - min(j, 6)), default=None)
rows.append(dict(api12=api, horizon=hname, polarity=pol,
offset_ms=np.nan if c is None else 2.0 * (c - min(j, 6))))
return pd.DataFrame(rows)
def m2_sonic(k: pd.DataFrame, las: pd.DataFrame) -> pd.DataFrame:
import lasio
rows = []
wide = k.pivot_table(index=k.index, columns="horizon", values=["t_ms", "md_top", "tvd_top"])
for api, r in wide.iterrows():
s = las[(las.api12 == api) & (las.sonic_n > 0)]
s = s[(s.sonic_top <= r[("md_top", "Carlile")]) & (s.sonic_base >= r[("md_top", "KF2")])]
if s.empty or not np.isfinite([r[("t_ms", "Carlile")], r[("t_ms", "KF2")]]).all():
continue
f = s.iloc[0]
l = lasio.read(f.file, ignore_header_errors=True)
md, dt = l.index.astype(float), l[f.sonic_curve].astype(float)
m = (md >= r[("md_top", "Carlile")]) & (md <= r[("md_top", "KF2")]) & np.isfinite(dt) & (dt > 30) & (dt < 200)
if m.sum() < 20:
continue
one_way = np.trapezoid(dt[m], md[m]) * 1e-6 * (r[("tvd_top", "KF2")] - r[("tvd_top", "Carlile")]) / (
r[("md_top", "KF2")] - r[("md_top", "Carlile")])
rows.append(dict(api12=api, dt_horizon_ms=r[("t_ms", "KF2")] - r[("t_ms", "Carlile")], dt_sonic_ms=2000 * one_way,
sonic_coverage=float(m.mean())))
d = pd.DataFrame(rows)
if len(d):
k_ratio = float(np.median(d.dt_horizon_ms / d.dt_sonic_ms))
d["resid_ms"] = d.dt_horizon_ms - k_ratio * d.dt_sonic_ms
d.attrs["ratio"] = k_ratio
return d
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
h = headers()
hz, ci, cx = horizons()
h["il"], h["xl"] = project(h.E, h.N, ci, cx)
tops = pd.read_excel(WELLS_DIR / "TeapotDomeFormationLogTops.xls")
tops["api12"] = tops["API Number"].astype(str).str[:12]
tp = tops.pivot_table(index="api12", columns="Form Alias", values="Top MD", aggfunc="first")
las = pd.read_csv(REPO / "outputs/teapot/inventory/las_wells.csv")
las["api12"] = las.file.str.extract(r"/(\d{12})\d*_")[0]
cov = las.groupby("api12").agg(dtop=("density_top", "min"), dbase=("density_base", "max"))
x = h[["well", "il", "xl", "kb", "E", "N"]].join(tp[list(KNOTS.values())]).join(cov)
in3d = x.il.between(1, 345) & x.xl.between(1, 188)
W = x[in3d & x.CRLL.notna() & x.F2WC.notna() & (x.dtop <= x.CRLL) & (x.dbase >= x.F2WC)]
dev = W[W.il <= DEV_MAX_INLINE]
assert len(W) == 152 and len(W) - len(dev) == N_TEST, (len(W), len(dev))
# geometry: SEG-Y headers vs the affine projection
import segyio
with segyio.open(SEIS_DIR / "3D_Seismic/filt_mig.sgy", ignore_geometry=True) as f:
a = {b: np.asarray(f.attributes(b)[:], float) for b in (181, 185, 189, 193)}
pil, pxl = project(a[189], a[193], ci, cx)
geom = dict(max_abs_inline_err=float(np.abs(pil - a[181]).max()), max_abs_xline_err=float(np.abs(pxl - a[185]).max()))
surv = surveys()
knots = []
for api, r in dev.iterrows():
for hname, top in KNOTS.items():
md = float(r[top])
tvd, dn, de = min_curvature(surv[api], md) if api in surv else (md, 0.0, 0.0)
il, xl = project([r.E + de], [r.N + dn], ci, cx)
t, how = sample(horizon_grid(hz, hname), float(il[0]), float(xl[0]))
knots.append(dict(api12=api, well=r.well, horizon=hname, md_top=md, tvd_top=tvd, offset_ft=float(np.hypot(dn, de)),
surveyed=api in surv, il_top=float(il[0]), xl_top=float(xl[0]), kb=r.kb,
z_ft=tvd - r.kb + DATUM_FT, t_ms=t, pick=how))
k = pd.DataFrame(knots).set_index("api12")
k.to_csv(OUT / "knots_dev.csv")
both = k.groupby(level=0).t_ms.apply(lambda s: s.notna().all())
coverage = float(both.mean())
r1 = m1_residuals(k)
r1 = r1[r1.api12.isin(both[both].index)]
r1.to_csv(OUT / "m1_residuals.csv", index=False)
sigma = float(np.sqrt(np.mean(r1.resid_ms ** 2)))
lo, hi = boot_rms(r1)
mad = float(1.4826 * np.median(np.abs(r1.resid_ms - r1.resid_ms.median())))
qc = segy_check(k[k.index.isin(both[both].index)])
qc.to_csv(OUT / "pick_qc.csv", index=False)
m2 = m2_sonic(k[k.index.isin(both[both].index)], las)
m2.to_csv(OUT / "m2_sonic.csv", index=False)
td48 = None
if "48-X-28" in set(dev.well):
tab = pd.read_excel(SEIS_DIR / "TimeDepthTables.xls", sheet_name="48-X-28", header=None).iloc[2:, [1, 3]].astype(float).dropna()
kk = k[k.well == "48-X-28"]
td48 = [dict(horizon=q.horizon, t_horizon_ms=q.t_ms, t_table_ms=float(np.interp(q.tvd_top, tab[3], tab[1])))
for q in kk.itertuples()]
verdict = dict(
declaration_sha256=(REPO / "docs/research/applicability-teapot.sha256").read_text().split("\n")[1].split()[0],
n_W=len(W), n_dev=len(dev), n_test=N_TEST, geometry=geom,
pick_counts=k.pick.value_counts().to_dict(), coverage_both_horizons=coverage,
m1=dict(sigma_knot_ms=sigma, ci90=[lo, hi], robust_sigma_ms=mad, n_wells=int(r1.api12.nunique()),
per_horizon_rms_ms=r1.groupby("horizon").resid_ms.apply(lambda s: float(np.sqrt(np.mean(s ** 2)))).to_dict(),
sensitivity_two_knot_sigma_ref_ms=0.78 * sigma),
m2=dict(n_wells=len(m2), ratio=m2.attrs.get("ratio"),
sigma_knot_ms=float(m2.resid_ms.std(ddof=1) / np.sqrt(2)) if len(m2) > 2 else None),
pick_qc={hn: dict(median_abs_ms=float(s.abs().median()), within_2ms=float((s.abs() <= 2).mean()), n=int(s.size))
for hn, s in qc.groupby("horizon").offset_ms},
td_48x28=td48, sigma_tol_ms=SIGMA_TOL_MS, coverage_min=COVERAGE_MIN,
)
verdict["pass"] = bool(sigma <= SIGMA_TOL_MS and coverage >= COVERAGE_MIN)
(OUT / "verdict.json").write_text(json.dumps(verdict, indent=2, default=float))
print(json.dumps(verdict, indent=2, default=float))
if __name__ == "__main__":
main()

140
scripts/30_t4_coverage.py Normal file
View File

@@ -0,0 +1,140 @@
"""T4 (exploratory): why cleaner labels give lower coverage of seed-ensemble intervals (paper Proposition 5, prop:coverage).
Uses only saved P2r predictions (outputs/p2r/train/<regime>/cells/r<rid>_c<c>_n<N>.npz: y_true on the true warp
of the 8 test wells, per-seed mu and sigma of every method at its selected budget). For each method the 5-seed
ensemble has s_e^2 = s_al^2 + s_seed^2, with s_al^2 = mean_s sigma_s^2 (the heteroscedastic head) and
s_seed^2 = var_s mu_s (ddof 0, as in H3). Per (regime, c, N, method), averaged over wells and samples, then over
realizations:
rms_al, rms_seed, rms_e square roots of the mean s_al^2, s_seed^2, s_e^2
rmse, rmse_low, rmse_band error of the ensemble mean (total; below f_c and seismic band, split as in metrics.py)
kappa mean s_e^2 / mean e^2 (1: matched second moment); the dispersion ratio xi of the paper
cov90, cov90_al, cov90_seed coverage of the central 90% Gaussian interval with s_e, s_al only, s_seed only
dvar, dmse mean s_e^2 and mean e^2 minus the Oracle's in the same realization
Proposition 5(a): kappa_m - kappa_Oracle = (dvar - kappa_Oracle * dmse) / mse_m, so a misregistered source has the larger
kappa (and, for Gaussian standardized errors, the larger coverage) iff dvar > kappa_Oracle * dmse; dvar >= dmse with
kappa_Oracle <= 1 is sufficient. Also tabulated (budget_dev.csv): mean sigma, RMSE and coverage per training budget on
the P2 dev realizations 900/901, the only runs that saved every budget, to show the effect of training length.
Descriptive only: nothing here is a gate, and nothing is chosen with these numbers.
python scripts/30_t4_coverage.py # -> outputs/t4/
"""
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 split_bands
from ml_porosity.paths import outputs_dir
OUT = outputs_dir() / "t4"
REGIMES = ("R10", "R0", "Rm5", "R0h", "R10tb", "R10_sa3.5", "R10_sa14")
METHODS = ("Oracle", "B3d-Sa", "M2-Sa", "B3d", "B3c-R", "B3c", "B3b")
ENS = {m: ("B5" if m == "B3b" else f"{m}-ens") for m in METHODS}
F_C, DT = 6.0, 4.0
Z90 = stats.norm.ppf(0.95)
def seeds(z, method: str) -> tuple[np.ndarray, np.ndarray]:
keys = sorted(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.stack([z[k] for k in keys]).astype(float),
np.stack([z[k[:-2] + "sigma"] for k in keys]).astype(float))
def well_rows() -> pd.DataFrame:
rows = []
for regime in REGIMES:
for f in sorted((outputs_dir() / f"p2r/train/{regime}/cells").glob("r*_c*_n*.npz")):
rid, c, n = f.stem.split("_")
with np.load(f) as z:
y = z["y_true"].astype(float)
pred = {m: seeds(z, m) for m in METHODS}
for m, (mu, sg) in pred.items():
mu_e, v_al, v_seed = mu.mean(0), (sg**2).mean(0), mu.var(0)
for i in range(y.shape[0]):
ok = np.isfinite(y[i]) & np.isfinite(mu_e[i])
e = y[i] - mu_e[i]
lo, hi = split_bands(e[ok], F_C, DT)
v_e = v_al[i] + v_seed[i]
rows.append(dict(
regime=regime, rid=int(rid[1:]), c=float(c[1:]), n_train=int(n[1:]), method=ENS[m], well=i,
v_al=v_al[i][ok].mean(), v_seed=v_seed[i][ok].mean(), v_e=v_e[ok].mean(),
mse=np.mean(e[ok] ** 2), mse_low=np.mean(lo**2), mse_band=np.mean(hi**2),
cov90=np.mean(np.abs(e[ok]) <= Z90 * np.sqrt(v_e[ok])),
cov90_al=np.mean(np.abs(e[ok]) <= Z90 * np.sqrt(v_al[i][ok])),
cov90_seed=np.mean(np.abs(e[ok]) <= Z90 * np.sqrt(v_seed[i][ok]))))
return pd.DataFrame(rows)
def cells(w: pd.DataFrame) -> pd.DataFrame:
"""Mean over wells per realization; differences to the Oracle within the realization."""
keys = ["regime", "c", "n_train", "rid", "method"]
r = w.groupby(keys, as_index=False)[["v_al", "v_seed", "v_e", "mse", "mse_low", "mse_band", "cov90", "cov90_al",
"cov90_seed"]].mean()
o = r[r.method == "Oracle-ens"].set_index(keys[:-1])[["v_e", "mse"]]
r = r.join(o, on=keys[:-1], rsuffix="_oracle")
return r.assign(dvar=r.v_e - r.v_e_oracle, dmse=r.mse - r.mse_oracle, kappa=r.v_e / r.mse)
def summary(r: pd.DataFrame) -> pd.DataFrame:
g = r.groupby(["regime", "c", "n_train", "method"])
s = g[["v_al", "v_seed", "v_e", "mse", "mse_low", "mse_band", "cov90", "cov90_al", "cov90_seed", "kappa", "dvar",
"dmse"]].mean()
s["frac_dvar_ge_dmse"] = g.apply(lambda d: float(np.mean(d.dvar >= d.dmse)), include_groups=False)
s["n_rid"] = g.size()
for k in ("v_al", "v_seed", "v_e", "mse", "mse_low", "mse_band"):
s[k.replace("v_", "rms_") if k.startswith("v_") else k.replace("mse", "rmse")] = np.sqrt(s.pop(k))
return s.reset_index()
def budget_dev() -> pd.DataFrame:
d = pd.read_csv(outputs_dir() / "p2/dev/results.csv")
keys = ["c", "n_train", "method", "budget"]
return d.groupby(keys, as_index=False)[["mean_sigma", "rmse", "low_rmse", "band_rmse", "coverage_90"]].mean()
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
w = well_rows()
w.to_csv(OUT / "wells.csv.gz", index=False)
r = cells(w)
r.to_csv(OUT / "cells.csv", index=False)
s = summary(r)
s.to_csv(OUT / "summary.csv", index=False)
# Check against the registered H3 table (c = 1): ensemble coverage must reproduce it.
h3 = pd.read_csv(outputs_dir() / "p2r/summary/h3.csv")
chk = s[s.c == 1.0].merge(h3, on=["regime", "n_train", "method"], suffixes=("", "_h3"))
dev = float(np.abs(chk.cov90 - chk.coverage_90).max()) if len(chk) else float("nan")
budget_dev().to_csv(OUT / "budget_dev.csv", index=False)
non_oracle = r[r.method != "Oracle-ens"]
k_o = non_oracle.v_e_oracle / non_oracle.mse_oracle
meta = dict(regimes=REGIMES, methods=[ENS[m] for m in METHODS], f_c_hz=F_C, dt_ms=DT, z90=float(Z90),
n_well_rows=len(w), h3_cov90_max_abs_dev=dev, h3_rows_checked=len(chk),
frac_dvar_ge_dmse_all=float(np.mean(non_oracle.dvar >= non_oracle.dmse)),
frac_dvar_pos_all=float(np.mean(non_oracle.dvar > 0)),
frac_kappa_gt_oracle_all=float(np.mean(non_oracle.kappa > k_o)),
frac_cov90_gt_oracle_all=float(np.mean(non_oracle.cov90 > non_oracle.join(
r[r.method == "Oracle-ens"].set_index(["regime", "c", "n_train", "rid"]).cov90.rename("cov90_o"),
on=["regime", "c", "n_train", "rid"]).cov90_o)),
low_band_share_of_mse=float((r.mse_low / r.mse).mean()),
n_realization_cells=int(len(non_oracle)))
(OUT / "meta.json").write_text(json.dumps(meta, indent=1, default=float))
pd.set_option("display.width", 250)
cols = ["regime", "c", "n_train", "method", "rms_al", "rms_seed", "rms_e", "rmse", "rmse_low", "rmse_band", "kappa",
"cov90", "cov90_al", "cov90_seed", "frac_dvar_ge_dmse"]
print(s[(s.c == 1.0) & s.regime.isin(["R10", "R0", "Rm5"])][cols].round(3).to_string(index=False))
print(json.dumps(meta, indent=1, default=float))
if __name__ == "__main__":
main()

250
scripts/31_p2r_posthoc.py Normal file
View 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()

37
scripts/run_p4.ps1 Normal file
View File

@@ -0,0 +1,37 @@
param(
[ValidateSet('status','benchmark','lock','register','train','summarize','all')]
[string]$Stage = 'all',
[ValidatePattern('^(cuda:[0-9]+|cpu)$')][string]$Device = 'cuda:0',
[ValidateRange(1,8)][int]$Workers = 4,
[ValidateSet('primary','sensitivity','all')][string]$Arms = 'primary',
[switch]$Detach,
[switch]$Smoke
)
$ErrorActionPreference = 'Stop'
$p4Workspace = Split-Path -Parent $PSScriptRoot
$p4Python = Join-Path $p4Workspace '.venv/Scripts/python.exe'
$env:OMP_NUM_THREADS = '2'
$env:MKL_NUM_THREADS = '2'
$env:OPENBLAS_NUM_THREADS = '2'
$env:NUMBA_NUM_THREADS = '2'
$env:PYTHONUTF8 = '1'
$env:PYTHONHASHSEED = '0'
$env:CUBLAS_WORKSPACE_CONFIG = ':4096:8'
$p4Arguments = @('-X','utf8','-m','ml_porosity.runlog','-n',"p4_$Stage",'--',
$p4Python,'-X','utf8',(Join-Path $PSScriptRoot '24_run_volve.py'),$Stage,
'--device',$Device,'--workers',"$Workers",'--arms',$Arms)
if ($Smoke) { $p4Arguments += '--smoke' }
if ($Detach) {
$p4LogDirectory = Join-Path $p4Workspace 'logs/runs'
New-Item -ItemType Directory -Path $p4LogDirectory -Force | Out-Null
$p4Stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$p4QuotedArguments = $p4Arguments | ForEach-Object { '"' + $_.Replace('"','\"') + '"' }
$p4Process = Start-Process -FilePath $p4Python -ArgumentList $p4QuotedArguments -WorkingDirectory $p4Workspace `
-WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $p4LogDirectory "${p4Stamp}_p4_stdout.log") `
-RedirectStandardError (Join-Path $p4LogDirectory "${p4Stamp}_p4_stderr.log")
Write-Output "P4 detached: PID $($p4Process.Id). Track outputs/p4/progress.json (or -Stage status)."
} else {
Push-Location $p4Workspace
try { & $p4Python @p4Arguments; if ($LASTEXITCODE -ne 0) { throw "P4 exited with code $LASTEXITCODE" } }
finally { Pop-Location }
}

21
scripts/run_p4.sh Executable file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# P4 Volve (configs/protocol_volve.yaml) on the Linux GPU server; same stages as scripts/run_p4.ps1.
# scripts/run_p4.sh # register, train, summarize (primary σ_a arm)
# scripts/run_p4.sh benchmark | lock | status # runtime pilot, first lock, progress
# ARMS=sensitivity scripts/run_p4.sh register train # σ_a = 3.5 / 14 ms arms; then ARMS=all ... summarize
# DEVICE (default cuda:1), WORKERS (default 4) and THREADS per worker (default 2) can be overridden.
# register/train/summarize refuse to run unless the protocol, code, inputs and environment match the lock, and skip
# completed jobs whose fingerprints and checksums match, so the driver can be restarted.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
DEVICE="${DEVICE:-cuda:1}"
WORKERS="${WORKERS:-4}"
THREADS="${THREADS:-2}"
ARMS="${ARMS:-primary}"
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
NUMBA_NUM_THREADS=$THREADS PYTHONHASHSEED=0 PYTHONUTF8=1 CUBLAS_WORKSPACE_CONFIG=:4096:8
for stage in ${@:-register train summarize}; do
"$PY" -m ml_porosity.runlog -n "p4_${stage}_${ARMS}" -- "$PY" scripts/24_run_volve.py "$stage" \
--device "$DEVICE" --workers "$WORKERS" --arms "$ARMS"
done