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

314
tests/test_deviated.py Normal file
View File

@@ -0,0 +1,314 @@
import numpy as np
import pandas as pd
import pytest
import yaml
from ml_porosity.data.deviated import (Trajectory, anchor_tdr, calibrated_vertical_tdr, composite_patch,
path_at_times, tdr_from_tvdss, tvdss_td_model, vertical_sonic_tdr)
from ml_porosity.data.tdr import TDR, sonic_tdr
from ml_porosity.data.volve_wells import blind_key, blind_training_wells, well_anchors
from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root
CFG = yaml.safe_load((REPO_ROOT / "configs/d3_volve.yaml").read_text())
P4 = CFG["p4"]
SURVEYS = volve_root() / P4["survey_dir"]
NPZ = outputs_dir() / "volve" / "volve_wells.npz"
needs_data = pytest.mark.skipif(not SURVEYS.exists() or not (volve_root() / CFG["well_logs_dir"]).exists(),
reason="missing data/Volve surveys or well logs")
# ---------- synthetic, no data required ----------
def stations(md, inc, azi, kb=0.0, name="w") -> Trajectory:
"""Trajectory whose listed positions are the minimum-curvature positions from the origin."""
md, inc, azi = (np.asarray(v, dtype=float) for v in (md, inc, azi))
z = np.zeros_like(md)
p = Trajectory(name, md, inc, azi, z, z, z).recompute()
return Trajectory(name, md, inc, azi, p[:, 2], p[:, 0], p[:, 1], kb)
def line(inc=60.0, azi=45.0, md1=1000.0, kb=0.0) -> Trajectory:
md = np.arange(0.0, md1 + 1, 100.0)
return stations(md, np.full_like(md, inc), np.full_like(md, azi), kb)
def test_minimum_curvature_is_exact_on_a_circular_arc():
k, azi = np.radians(3.0) / 30.0, 30.0 # build rate 3°/30 m
s = np.arange(0.0, 601.0, 30.0)
h = lambda u: (1 - np.cos(k * u)) / k # noqa: E731 (horizontal displacement along the arc)
a = np.radians(azi)
tr = Trajectory("arc", s, np.degrees(k * s), np.full_like(s, azi), np.sin(k * s) / k, h(s) * np.sin(a),
h(s) * np.cos(a))
np.testing.assert_allclose(tr.recompute(), np.c_[tr.x, tr.y, tr.tvd], atol=1e-9)
np.testing.assert_allclose(tr.dls(), 3.0)
u = np.array([0.0, 7.3, 45.0, 299.9, 512.5, 600.0])
tvd, x, y = tr.at(u)
np.testing.assert_allclose(tvd, np.sin(k * u) / k, atol=1e-9)
np.testing.assert_allclose(np.c_[x, y], np.c_[h(u) * np.sin(a), h(u) * np.cos(a)], atol=1e-9)
def test_inclined_line_and_survey_bounds():
tr = line(inc=60.0, azi=45.0, kb=25.0)
md = np.array([0.0, 137.0, 999.0])
tvd, x, y = tr.at(md)
np.testing.assert_allclose(tvd, md * 0.5, atol=1e-9)
np.testing.assert_allclose(x, md * np.sin(np.radians(60)) * np.sqrt(0.5), atol=1e-9)
np.testing.assert_allclose(y, x, atol=1e-9)
np.testing.assert_allclose(tr.tvdss(md), md * 0.5 - 25.0, atol=1e-9)
np.testing.assert_allclose(tr.dls(), 0.0, atol=1e-6)
with pytest.raises(ValueError):
tr.at(1000.5)
with pytest.raises(ValueError):
Trajectory("bad", [0, 10, 10], [0, 0, 0], [0, 0, 0], [0, 10, 10], [0, 0, 0], [0, 0, 0])
def test_listed_stations_are_honoured():
"""Survey coordinates that disagree slightly with minimum curvature: `at` still returns the listed station."""
tr = line()
tr = Trajectory("w", tr.md, tr.inc, tr.azi, tr.tvd + 0.1 * np.arange(tr.md.size), tr.x, tr.y)
np.testing.assert_allclose(tr.at(tr.md)[0], tr.tvd, atol=1e-9)
def test_compass_parser(tmp_path):
rows = ["0.00 0.00 0.00 0.00 0.00 0.00 1000.00 2000.00 0.00",
"100.00 0.00 0.00 100.00 0.00 0.00 1000.00 2000.00 0.00",
"200.00 10.00 90.00 199.49 8.72 0.00 1008.72 2000.00 3.00"]
head = ["HEADER INFORMATION", "WELLBORE NAME: T-1", "Calculation Method: Minimum Curvature",
"Bottom Hole MD: 200.00m", "KB-MSL: 50.00m", "North Reference: Grid", "SURVEY LIST",
"MD Inc Azim TVD X-Offset (E/W) Y-Offset (N/S) UTM E/W UTM N/S DLS",
"m RKB deg deg m RKB m m m m deg/30m"]
f = tmp_path / "T-1_ACTUAL"
f.write_bytes("\r\n".join(head + rows).encode("latin-1"))
tr = Trajectory.from_compass(f)
assert tr.name == "T-1" and tr.kb_msl == 50.0
np.testing.assert_allclose(tr.md, [0, 100, 200])
np.testing.assert_allclose(tr.x, [1000, 1000, 1008.72])
assert np.abs(tr.recompute()[:, 2] - tr.tvd).max() < 0.01
f.write_text("\n".join([s.replace("Minimum Curvature", "Tangential") for s in head] + rows))
with pytest.raises(ValueError):
Trajectory.from_compass(f)
f.write_text("\n".join([s.replace("m RKB ", "m MSL ") for s in head] + rows))
with pytest.raises(ValueError):
Trajectory.from_compass(f)
def test_vertical_sonic_integrates_over_tvd():
tr = line(inc=60.0)
md = np.arange(100.0, 900.01, 0.5)
dt = np.full_like(md, 1e6 / 3000.0)
t = vertical_sonic_tdr(md, tr.at(md)[0], dt, md0=200.0, t0_ms=1000.0)
np.testing.assert_allclose(t.time_at(md), 1000.0 + 2000.0 * 0.5 * (md - 200.0) / 3000.0, atol=1e-6)
t_md = sonic_tdr(md, dt, 200.0, 1000.0) # MD integration counts the along-hole path: twice as long at 60°
np.testing.assert_allclose(t_md.time_at(md) - 1000.0, 2.0 * (t.time_at(md) - 1000.0), atol=1e-6)
with pytest.raises(ValueError):
vertical_sonic_tdr(md, tr.at(md)[0], dt, md0=50.0, t0_ms=1000.0)
@pytest.fixture
def curved():
md = np.arange(0.0, 1201.0, 30.0)
return stations(md, np.minimum(md / 15.0, 70.0), np.full_like(md, 120.0), kb=40.0)
def test_calibrated_tdr_honours_anchors(curved):
tr = curved
true = lambda m: 100.0 + 2000.0 * tr.at(m)[0] / 2400.0 # noqa: E731 (vertical velocity 2400 m/s)
md = np.arange(300.0, 900.01, 0.5)
dt = np.full_like(md, 1e6 / 2500.0) # sonic 4 % faster than the seismic
dt[(md > 500) & (md < 520)] = np.nan # internal gap
za = np.array([150.0, 400.0, 700.0])
t = calibrated_vertical_tdr(tr, md, dt, za, true(za), edge_m=30.0)
assert t.md[0] == tr.md[0] and t.md[-1] == tr.md[-1]
np.testing.assert_allclose(t.time_at(za), true(za), atol=1e-9)
m = np.linspace(400.0, 700.0, 31) # stretched between anchors: exact for constant velocities, at the nodes
m = m[(m <= 500) | (m >= 520)]
np.testing.assert_allclose(t.time_at(m), true(m), atol=1e-6)
assert abs(t.time_at(510.0) - true(510.0)) < 0.05 # across the gap the TDR is linear in MD, not in TVD
tvd = lambda v: tr.at(v)[0] # noqa: E731
m = np.array([750.0, 900.0, 1100.0]) # bulk shift below the last anchor, then constant-velocity extension
np.testing.assert_allclose(t.time_at(m), true(700.0) + 2000.0 * (tvd(m) - tvd(700.0)) / 2500.0, atol=1e-6)
m = np.array([150.0, 220.0, 300.0]) # linear in TVD between the anchor above the DT range and its top
t300 = true(400.0) - 2000.0 * (tvd(400.0) - tvd(300.0)) / 2500.0
np.testing.assert_allclose(t.time_at(m), np.interp(tvd(m), tvd([150.0, 300.0]), [true(150.0), t300]), atol=1e-6)
t2 = calibrated_vertical_tdr(tr, md, dt, za[1:], true(za[1:])) # no anchor above: edge velocity
np.testing.assert_allclose(t2.time_at(100.0), t300 - 2000.0 * (tvd(300.0) - tvd(100.0)) / 2500.0, atol=1e-6)
with pytest.raises(ValueError):
calibrated_vertical_tdr(tr, md, dt, za[:2], true(za[:2]))
a = anchor_tdr(tr, za, true(za))
assert a.md[0] == za[0] and a.md[-1] == za[-1]
np.testing.assert_allclose(a.time_at(np.array([200.0, 600.0])), true(np.array([200.0, 600.0])), atol=1e-6)
def test_path_is_held_below_td():
tr = line()
p = path_at_times(tr, TDR(np.array([0.0, 1000.0]), np.array([0.0, 1000.0])), np.array([500.0, 1200.0]))
np.testing.assert_allclose(p["md"], [500.0, 1200.0])
assert p["beyond"].tolist() == [False, True]
np.testing.assert_allclose([p["tvd"][1], p["x"][1]], [tr.tvd[-1], tr.x[-1]], atol=1e-9)
def test_tvdss_model_places_a_new_well():
v1, v2 = line(inc=0.0, md1=3000.0, kb=50.0), line(inc=0.0, md1=3000.0, kb=30.0)
t1 = TDR(v1.md, 1.0 * (v1.md - 50.0)) # TWT (ms) = 1.0·TVDSS
t2 = TDR(v2.md, 1.2 * (v2.md - 30.0))
z = np.arange(0.0, 2001.0)
model = tvdss_td_model([v1, v2], [t1, t2], z)
np.testing.assert_allclose(model, 1.1 * z)
w = line(inc=60.0, md1=3000.0, kb=40.0)
t = tdr_from_tvdss(w, z, model)
np.testing.assert_allclose(t.time_at(w.md), 1.1 * (0.5 * w.md - 40.0), atol=1e-6)
md = np.array([0.0, 1000.0, 2000.0])
up = stations(md, [0.0, 0.0, 150.0], [0.0, 0.0, 0.0]) # turns upwards: TVDSS is not monotone
dense = np.arange(0.0, 2001.0)
with pytest.raises(ValueError):
tvdss_td_model([up], [TDR(dense, dense)], z)
class FakeCube:
"""Linear amplitude field a(il, xl, t) = 10 + 2·il − 3·xl + 0.01·t."""
def __init__(self):
self.times_ms, self.dt_ms, self.calls = np.arange(0.0, 400.0, 4.0), 4.0, 0
def trace(self, il, xl):
self.calls += 1
return (10 + 2 * il - 3 * xl + 0.01 * self.times_ms).astype(np.float32)
def test_composite_patch():
cube, cache = FakeCube(), {}
il, xl, t = np.array([100.25, 100.5, 101.75]), np.array([50.0, 50.4, 49.9]), np.array([8.0, 12.0, 16.0])
p = composite_patch(cube, il, xl, t, radius=1, cache=cache)
assert p.shape == (9, 3) and p.dtype == np.float32
for c, (di, dx) in enumerate((di, dx) for di in (-1, 0, 1) for dx in (-1, 0, 1)):
np.testing.assert_allclose(p[c], 10 + 2 * (il + di) - 3 * (xl + dx) + 0.01 * t, atol=1e-3)
n = composite_patch(cube, il, xl, t, radius=1, method="nearest", cache=cache)
np.testing.assert_allclose(n[4], 10 + 2 * np.rint(il) - 3 * np.rint(xl) + 0.01 * t, atol=1e-3)
calls = cube.calls
composite_patch(cube, il, xl, t, radius=1, cache=cache)
assert cube.calls == calls
with pytest.raises(ValueError):
composite_patch(cube, il, xl, t + 1.0)
with pytest.raises(ValueError):
composite_patch(cube, il, xl, t, method="cubic")
def picks_table(rows) -> pd.DataFrame:
df = pd.DataFrame(rows, columns=["surface", "qlf", "md", "twt_ms"]).assign(well="W", x=0.0, y=0.0)
return df.assign(tvd=df.md, tvdss=-(df.md - 50.0))
def test_well_anchors():
rows = [("Seabed", "", 100.0, 130.0), ("A", "ER", 1000.0, 1000.0), ("A2", "", 1000.0, 1000.05),
("B", "", 1500.0, 1300.0), ("B2", "", 1500.5, 1300.3), ("C", "NL", 1800.0, 1450.0),
("D", "", 2000.0, np.nan), ("E", "", 2100.0, 1600.0)]
anchors, excluded = well_anchors(picks_table(rows), "W", ["Seabed"], ["NL", "NR"], min_sep_m=1.0)
assert anchors.surface.tolist() == ["A2", "B", "E"]
assert dict(zip(excluded.surface, excluded.reason)) == {
"Seabed": "surface", "A": "same MD as A2", "B2": "0.50 m below B", "C": "qlf NL"}
with pytest.raises(ValueError): # same MD, different TWT
well_anchors(picks_table([("A", "", 1000.0, 1000.0), ("A2", "", 1000.0, 1000.5)]), "W", [], [])
with pytest.raises(ValueError): # TWT decreases with MD
well_anchors(picks_table([("A", "", 1000.0, 1000.0), ("B", "", 1100.0, 990.0)]), "W", [], [])
def test_blind_training_wells():
assert blind_training_wells("F-1", "lowo", P4) == ("F-1 A", "F-1 B", "F-11 A", "F-11 T2", "F-12")
assert blind_training_wells("F-1 A", "slot", P4) == ("F-11 A", "F-11 T2", "F-12")
assert blind_training_wells("F-11 T2", "slot", P4) == ("F-1", "F-1 A", "F-1 B", "F-12")
assert blind_training_wells("F-12", "slot", P4) == blind_training_wells("F-12", "lowo", P4)
with pytest.raises(ValueError):
blind_training_wells("F-1", "nearest", P4)
assert blind_key(["F-12", "F-1 B", "F-1"]) == "F-1+F-1 B+F-12"
# ---------- Volve data ----------
LABEL_MD = {"F-1": (3319.7, 3598.9), "F-1 A": (3429.4, 3642.1), "F-1 B": (3229.4, 3424.6),
"F-11 A": (3575.0, 3723.3), "F-11 T2": (4334.7, 4522.3), "F-12": (3102.1, 3442.56)}
N_ANCHORS = {"F-1": 6, "F-1 A": 9, "F-1 B": 7, "F-11 A": 6, "F-11 T2": 8, "F-12": 8}
@pytest.fixture(scope="module")
def wells():
from ml_porosity.data.volve_io import read_well_picks
from ml_porosity.data.volve_wells import load_volve_well
picks = read_well_picks(volve_root() / CFG["picks"])
return picks, {n: load_volve_well(n, CFG, picks) for n in P4["wells"]}
def survey_rows(path) -> np.ndarray:
lines = path.read_text(encoding="latin-1").splitlines()
k = next(i for i, s in enumerate(lines) if s.strip() == "SURVEY LIST")
return np.array([[float(v) for v in s.split()] for s in lines[k + 3:] if s.strip()])
@needs_data
def test_surveys(wells):
for n, w in wells[1].items():
tr, head = w.traj, w.header
assert tr.md[-1] == pytest.approx(float(head["Bottom Hole MD"].removesuffix("m")), abs=0.005)
assert tr.tvd[-1] == pytest.approx(float(head["Bottom Hole TVD"].removesuffix("m")), abs=0.005)
assert tr.kb_msl == 54.9 and np.all(np.diff(tr.tvd) > 0)
r = tr.recompute()
assert np.abs(r[:, 2] - tr.tvd).max() < 0.02, n
assert np.hypot(r[:, 0] - tr.x, r[:, 1] - tr.y).max() < 0.5, n
dls = survey_rows(SURVEYS / P4["wells"][n]["survey"])[1:, 8]
assert np.abs(tr.dls() - dls).max() < 0.05, n
@needs_data
def test_picks_lie_on_the_surveys(wells):
"""Pick positions (another survey version) agree with the surveys well within a bin and a time sample."""
picks, ws = wells
for w in ws.values():
p = picks[(picks.well == w.pick_name) & picks.md.between(w.traj.md[0], w.traj.md[-1]) & picks.x.notna()]
tvd, x, y = w.traj.at(p.md)
assert len(p) >= 13 and np.abs(p.tvd - tvd).max() < 0.5 and np.hypot(p.x - x, p.y - y).max() < 1.5
@needs_data
def test_volve_wells(wells):
ws = wells[1]
for n, w in ws.items():
assert w.label_support(P4["label"]) == pytest.approx(LABEL_MD[n], abs=0.05), n
assert len(w.anchors) == N_ANCHORS[n], n
assert not w.anchors.qlf.isin(P4["anchor_exclude_qlf"]).any()
assert not w.anchors.surface.isin(CFG["anchor_exclude_surfaces"]).any()
dt = w.logs.DT.dropna()
assert dt.between(40 / 0.3048, 200 / 0.3048).all() and w.logs.RHOB.dropna().between(1000, 3500).all()
assert ws["F-12"].qc == {"n_dt_rejected": 4, "n_beyond_survey": {"GR": 4375}}
assert "Skagerrak Fm. Top" in ws["F-1"].excluded.surface[ws["F-1"].excluded.qlf == "FP"].tolist()
@needs_data
def test_calibrated_tdr_matches_the_f11t2_vsp(wells):
"""Marker-calibrated vertical sonic vs the F-11 T2 zero-offset VSP over the label support; the rig-source VSP
(left out) is ~35 ms early in the reservoir."""
from ml_porosity.data.volve_io import read_checkshot
w = wells[1]["F-11 T2"]
lo, hi = w.valid_range("DT")
seg = w.logs.loc[lo:hi]
cal = calibrated_vertical_tdr(w.traj, seg.index, seg.DT, w.anchors.md, w.anchors.twt_ms, P4["edge_m"])
a, b = w.label_support()
for kind, bound in (("NIVSP", (-3.0, 0.0)), ("OPTIMIZED", (-3.0, 0.0)), ("RSVSP", (30.0, 40.0))):
cs = read_checkshot(volve_root() / CFG["well_logs_dir"] / CFG["checkshots"][w.pick_name][kind])
cs = cs[cs.md.between(a, b)]
d = cal.time_at(cs.md.to_numpy()) - cs.twt_ms.to_numpy()
assert len(cs) >= 5 and bound[0] < d.min() and d.max() < bound[1], kind
@pytest.mark.skipif(not NPZ.exists(), reason="run scripts/23_build_volve_wells.py first")
def test_built_dataset():
D = np.load(NPZ)
n_ext = int(round((P4["ext_window_ms"][1] - P4["ext_window_ms"][0]) / 4)) + 1
for n in P4["wells"]:
assert D[f"{n}/times_ms"].shape == (n_ext,) and D[f"{n}/main_mask"].sum() == 126
blind = {k.split("/")[2] for k in D.files if k.startswith(f"{n}/blind/")}
assert len(blind) == 2 ** (len(P4["wells"]) - 1) - 1
assert all(n not in key.split("+") for key in blind)
for key in ["reference"] + [f"blind/{k}" for k in blind]:
p = D[f"{n}/{key}/seismic_patch"]
assert p.shape == (9, n_ext) and np.isfinite(p).all()
lab = np.isfinite(D[f"{n}/calibrated/{P4['label']}"])
assert lab.any() and not lab[~D[f"{n}/main_mask"]].any()