Files
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

145 lines
7.2 KiB
Python

"""P4 data views (plan §5.2): private arrays of the training wells, seismic-only blind inputs of every other well.
A restricted view (training_wells given) keeps, for a well outside the training set, only
times_ms, main_mask, kb_msl, survey/* the well path, known without its logs or picks
blind/<K>/{seismic_patch, md, il, xl, beyond} only for K ⊇ training_wells, well ∉ K
so its logs, picks, TDRs, reference path and the label-centred bin (il, xl, x, y: placed at the middle of the
label interval) are never loaded. Labels, the reference input and registration observations of such a well
raise RuntimeError. The full view (training_wells None) is for scoring only.
"""
from __future__ import annotations
import numpy as np
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.tdr import TDR
from ml_porosity.models.bank_train import zscore_patch
from ml_porosity.paths import outputs_dir
from ml_porosity.registration.warp_prior import WarpGrid
PUBLIC = frozenset({"times_ms", "main_mask", "kb_msl"})
PUBLIC_PREFIXES = ("survey/",)
def npz_path():
return outputs_dir() / "volve" / "volve_wells.npz"
def load_arrays(path=None) -> dict[str, np.ndarray]:
with np.load(npz_path() if path is None else path) as z:
return {k: z[k] for k in z.files}
def blind_members(key: str) -> frozenset[str]:
return frozenset(key.split("+"))
def visible(key: str, training_wells: frozenset[str] | None) -> bool:
"""Whether the flat npz key "<well>/<item>" belongs to a view on `training_wells`."""
well, item = key.split("/", 1)
if training_wells is None or well in training_wells:
return True
if item in PUBLIC or item.startswith(PUBLIC_PREFIXES):
return True
if item.startswith("blind/"):
members = blind_members(item.split("/")[1])
return well not in members and training_wells <= members
return False
class VolveData:
def __init__(self, protocol: dict, training_wells: tuple[str, ...] | None = None,
arrays: dict[str, np.ndarray] | None = None):
self.protocol = protocol
self.wells = list(protocol["data"]["wells"])
self.label = protocol["data"]["label"]
self.training_wells = None if training_wells is None else frozenset(training_wells)
if self.training_wells is not None and not self.training_wells <= set(self.wells):
raise ValueError("Unknown training well")
source = load_arrays() if arrays is None else arrays
self.arrays = {k: v for k, v in source.items()
if k.split("/", 1)[0] in self.wells and visible(k, self.training_wells)}
self.t = self.ext(self.wells[0], "times_ms")
self.main = self.ext(self.wells[0], "main_mask").astype(bool)
self.t_main = self.t[self.main]
self.dt = float(np.diff(self.t)[0])
for w in self.wells:
if not (np.array_equal(self.ext(w, "times_ms"), self.t)
and np.array_equal(self.ext(w, "main_mask").astype(bool), self.main)):
raise ValueError(f"Volve time axes differ: {w}")
r = protocol["registration"]
f = r["fine_dt_ms"]
self.grid = WarpGrid(*r["tau_range_ms"], r["warp_dtau_ms"])
self.tau = np.arange(r["tau_range_ms"][0], r["tau_range_ms"][1] + f / 2, f)
self.t_fine = np.arange(self.t[0] - 300, self.t[-1] + 300 + f / 2, f)
def is_training(self, well: str) -> bool:
return self.training_wells is None or well in self.training_wells
def ext(self, well: str, key: str) -> np.ndarray:
try:
return self.arrays[f"{well}/{key}"]
except KeyError:
raise KeyError(f"{well}/{key} is not in this data view") from None
def blind_keys(self, well: str) -> list[str]:
head = f"{well}/blind/"
return sorted({k[len(head):].split("/")[0] for k in self.arrays if k.startswith(head)})
def patch(self, well: str, key: str) -> np.ndarray:
"""(C, n_ext) seismic patch: key 'reference' (calibrated path, training wells only) or a blind key."""
if key == "reference":
if not self.is_training(well):
raise RuntimeError("The reference path of a held-out well uses its own picks and DT")
return self.ext(well, "reference/seismic_patch")
if well in blind_members(key):
raise RuntimeError(f"Blind key {key!r} contains its own well {well!r}")
return self.ext(well, f"blind/{key}/seismic_patch")
def X(self, well: str, key: str) -> np.ndarray:
"""Network input (C, L) on the main window."""
return zscore_patch(self.patch(well, key), self.main)
def y(self, well: str, reference: str, label: str | None = None) -> np.ndarray:
"""Label on the main window under TDR `reference`; NaN outside its support."""
if not self.is_training(well):
raise RuntimeError("Held-out labels are unavailable in a training data view")
return self.ext(well, f"{reference}/{label or self.label}")[self.main]
def training_observations(self, names: tuple[str, ...]) -> list[dict]:
"""Registration inputs of training wells on the sonic time axis τ (vertical sonic through the first anchor
in the DT range). Anchors: in the DT range and inside the ext window. `lik`: ext samples from the first to
the last finite calibrated AI sample (the tie likelihood is evaluated there only)."""
if self.training_wells is not None and not set(names) <= self.training_wells:
raise RuntimeError("Held-out logs and anchors are unavailable in a training data view")
r = self.protocol["registration"]
obs = []
for name in names:
sonic = TDR(self.ext(name, "tdr/sonic/md"), self.ext(name, "tdr/sonic/twt_ms"), "sonic")
md = self.ext(name, "log/md")
amd, att = self.ext(name, "anchors_md"), self.ext(name, "anchors_twt_ms")
keep = self.ext(name, "anchors_in_dt").astype(bool) & (att >= self.t[0]) & (att <= self.t[-1])
if keep.sum() < 1:
raise ValueError(f"No anchor in the DT range: {name}")
resampled, valid = {}, {}
for curve in ("AI", self.label):
v = log_to_time(md, self.ext(name, f"log/{curve}"), sonic, self.tau,
fine_dt_ms=r["log_fine_dt_ms"], cutoff_frac=r["log_cutoff_frac"])
good = np.isfinite(v)
if good.sum() < 2:
raise ValueError(f"No sonic-domain log: {name}/{curve}")
resampled[curve] = np.interp(self.tau, self.tau[good], v[good])
valid[curve] = good
ok = np.flatnonzero(np.isfinite(self.ext(name, "calibrated/AI")))
lik = np.zeros(self.t.size, bool)
lik[ok[0]: ok[-1] + 1] = True
seis = self.ext(name, "reference/seismic_patch")
obs.append({"name": name, "tau_k": sonic.time_at(amd[keep]), "t_k": att[keep].astype(float),
"ai_log": resampled["AI"], "labels": {self.label: resampled[self.label]},
"label_valid": {self.label: valid[self.label]}, "lik": lik,
"seis": seis[len(seis) // 2].astype(float)})
return obs