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>
269 lines
13 KiB
Python
269 lines
13 KiB
Python
"""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()
|