Files
ML-Porosity/scripts/23_build_volve_wells.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

283 lines
17 KiB
Python
Raw Permalink 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.
"""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()