Files
ML-Porosity/ml_porosity/data/deviated.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

282 lines
15 KiB
Python
Raw 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.
"""Deviated-well geometry and time–depth relationships (Volve, plan phase P4).
Conventions: MD and TVD are metres below the rotary kelly bushing (RKB); TVDSS = TVD − (KB − MSL), positive
down; X/Y are projected easting/northing (m) with grid north; times are two-way times (ms) from the seismic datum.
Seismic time is vertical time, whereas a sonic tool measures slowness along the borehole. The vertical sonic TDR
therefore integrates DT over TVD instead of MD (isotropic, flat-layer approximation). Anisotropy and dip are left
to the anchor calibration and, in RML, to the warp prior. All TDRs stay keyed by MD, so `log_to_time` and
`calibrate_to_anchors` apply unchanged.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from scipy import integrate
from ml_porosity.data.tdr import TDR, US_PER_M_TO_S_PER_M, _interp_extrap, calibrate_to_anchors
_COLUMNS = ("MD", "Inc", "Azim", "TVD")
_NODE_STEP_M = 1.0 # MD spacing of TDR nodes outside the logged interval (TVD is curved between survey stations)
def _tangent(inc_deg, azi_deg) -> np.ndarray:
"""Unit tangent (east, north, down) from inclination and grid azimuth in degrees."""
i, a = np.radians(inc_deg), np.radians(azi_deg)
return np.stack([np.sin(i) * np.sin(a), np.sin(i) * np.cos(a), np.cos(i)], axis=-1)
def _mc_step(t0: np.ndarray, t1: np.ndarray, dmd) -> np.ndarray:
"""Minimum-curvature displacement over arc length `dmd` between unit tangents t0 and t1 (exact on a circular arc)."""
beta = np.arccos(np.clip(np.sum(t0 * t1, axis=-1), -1.0, 1.0))
small = beta < 1e-9
rf = np.where(small, 1.0, 2.0 / np.where(small, 1.0, beta) * np.tan(beta / 2))
return 0.5 * np.asarray(dmd, dtype=float)[..., None] * (t0 + t1) * rf[..., None]
def read_compass_header(path: str | Path) -> dict[str, str]:
"""`key: value` lines above `SURVEY LIST` in a Compass survey export."""
head = {}
for s in Path(path).read_text(encoding="latin-1").splitlines():
if s.strip() == "SURVEY LIST":
return head
if ":" in s:
k, v = s.split(":", 1)
head[k.strip()] = v.strip()
raise ValueError(f"{path}: no SURVEY LIST section")
@dataclass(frozen=True)
class Trajectory:
"""Survey stations of one wellbore."""
name: str
md: np.ndarray # (N,) m RKB, strictly increasing
inc: np.ndarray # deg
azi: np.ndarray # deg from grid north
tvd: np.ndarray # m RKB
x: np.ndarray # easting (m)
y: np.ndarray # northing (m)
kb_msl: float = 0.0 # RKB elevation above MSL (m)
def __post_init__(self):
arrays = {k: np.asarray(getattr(self, k), dtype=float) for k in ("md", "inc", "azi", "tvd", "x", "y")}
n = arrays["md"].size
if n < 2 or any(a.shape != (n,) for a in arrays.values()):
raise ValueError("trajectory arrays must be 1-D of equal length ≥ 2")
if np.any(np.diff(arrays["md"]) <= 0):
raise ValueError(f"trajectory {self.name!r}: MD is not strictly increasing")
for k, a in arrays.items():
object.__setattr__(self, k, a)
@classmethod
def from_compass(cls, path: str | Path, name: str | None = None) -> Trajectory:
"""Read a Compass "ACTUAL" survey export (header, then `SURVEY LIST`, a column line, a unit line and
one row per station: MD, Inc, Azim, TVD, X/Y offsets, UTM E/N, DLS)."""
head = read_compass_header(path)
if head.get("Calculation Method") != "Minimum Curvature" or head.get("North Reference") != "Grid":
raise ValueError(f"{path}: expected minimum curvature and grid north, got {head.get('Calculation Method')!r}"
f" / {head.get('North Reference')!r}")
lines = Path(path).read_text(encoding="latin-1").splitlines()
start = next(k for k, s in enumerate(lines) if s.strip() == "SURVEY LIST")
if tuple(lines[start + 1].split()[:4]) != _COLUMNS or "UTM N/S" not in lines[start + 1]:
raise ValueError(f"{path}: unexpected survey columns {lines[start + 1]!r}")
if lines[start + 2].split()[:2] != ["m", "RKB"]:
raise ValueError(f"{path}: MD is not referenced to RKB")
rows = np.array([[float(v) for v in s.split()] for s in lines[start + 3:] if s.strip()])
if rows.ndim != 2 or rows.shape[1] != 9:
raise ValueError(f"{path}: expected 9 numeric columns per station")
md, inc, azi, tvd, _, _, x, y, _ = rows.T
kb = float(head["KB-MSL"].removesuffix("m"))
return cls(name or head.get("WELLBORE NAME", Path(path).name), md, inc, azi, tvd, x, y, kb)
def recompute(self) -> np.ndarray:
"""Station positions (x, y, tvd) by minimum curvature from the first station; QC against the listed ones."""
t = _tangent(self.inc, self.azi)
start = np.array([self.x[0], self.y[0], self.tvd[0]])
return np.vstack([start, start + np.cumsum(_mc_step(t[:-1], t[1:], np.diff(self.md)), axis=0)])
def dls(self) -> np.ndarray:
"""Dogleg severity (deg/30 m) of each survey interval."""
t = _tangent(self.inc, self.azi)
beta = np.arccos(np.clip(np.sum(t[:-1] * t[1:], axis=-1), -1.0, 1.0))
return np.degrees(beta) * 30.0 / np.diff(self.md)
def at(self, md) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""(tvd, x, y) at MD: minimum curvature between stations, anchored on the listed station coordinates
(the small closure residual of each interval is spread linearly over it). No extrapolation."""
md = np.asarray(md, dtype=float)
if np.any(md < self.md[0] - 1e-9) or np.any(md > self.md[-1] + 1e-9):
raise ValueError(f"trajectory {self.name!r}: MD outside the survey {self.md[0]}–{self.md[-1]} m")
i = np.clip(np.searchsorted(self.md, md, side="right") - 1, 0, self.md.size - 2)
dmd = self.md[i + 1] - self.md[i]
f = np.clip((md - self.md[i]) / dmd, 0.0, 1.0)
t = _tangent(self.inc, self.azi)
t0, t1 = t[i], t[i + 1]
beta = np.arccos(np.clip(np.sum(t0 * t1, axis=-1), -1.0, 1.0))
sb = np.sin(beta)
small = sb < 1e-9
w0 = np.where(small, 1 - f, np.sin((1 - f) * beta) / np.where(small, 1.0, sb))
w1 = np.where(small, f, np.sin(f * beta) / np.where(small, 1.0, sb))
tf = w0[..., None] * t0 + w1[..., None] * t1 # tangent at fraction f of the circular arc
tf = tf / np.linalg.norm(tf, axis=-1, keepdims=True)
p = np.stack([self.x, self.y, self.tvd], axis=-1)
closure = p[i + 1] - p[i] - _mc_step(t0, t1, dmd)
q = p[i] + _mc_step(t0, tf, f * dmd) + f[..., None] * closure
return q[..., 2], q[..., 0], q[..., 1]
def tvdss(self, md) -> np.ndarray:
return self.at(md)[0] - self.kb_msl
def vertical_sonic_tdr(md, tvd, dt_us_per_m, md0: float, t0_ms: float, name: str = "sonic") -> TDR:
"""Vertical-time sonic TDR through (md0, t0_ms): t(md) = t0 + 2·∫ DT dTVD from md0 to md.
Only valid DT samples are used (gaps are integrated as DT varying linearly between their ends). md0 must lie
within the valid DT range, and TVD must increase strictly along it (no well turning upwards)."""
md, tvd, dt = (np.asarray(v, dtype=float) for v in (md, tvd, dt_us_per_m))
ok = np.isfinite(dt) & (dt > 0) & np.isfinite(tvd)
md_v, tvd_v, dt_v = md[ok], tvd[ok], dt[ok]
if md_v.size < 2:
raise ValueError("no valid DT")
if np.any(np.diff(tvd_v) <= 0):
raise ValueError("TVD does not increase strictly over the logged interval")
if not md_v[0] <= md0 <= md_v[-1]:
raise ValueError(f"anchor MD {md0} lies outside the valid DT range {md_v[0]}–{md_v[-1]} m")
t = 2000.0 * integrate.cumulative_trapezoid(dt_v * US_PER_M_TO_S_PER_M, tvd_v, initial=0.0)
return TDR(md_v, t - np.interp(md0, md_v, t) + t0_ms, name)
def _sorted_anchors(anchor_md, anchor_twt_ms) -> tuple[np.ndarray, np.ndarray]:
za, ta = np.asarray(anchor_md, dtype=float), np.asarray(anchor_twt_ms, dtype=float)
order = np.argsort(za, kind="stable")
za, ta = za[order], ta[order]
if np.any(np.diff(za) <= 0) or np.any(np.diff(ta) <= 0):
raise ValueError("anchors must be strictly increasing in MD and TWT")
return za, ta
def _nodes(traj: Trajectory, lo: float, hi: float, extra=()) -> np.ndarray:
"""Survey stations, a regular MD grid and `extra` points strictly inside (lo, hi), clipped to the survey."""
grid = np.arange(np.ceil(traj.md[0]), traj.md[-1], _NODE_STEP_M)
z = np.union1d(np.union1d(grid, traj.md), np.asarray(extra, dtype=float))
return z[(z > lo) & (z < hi)]
def calibrated_vertical_tdr(traj: Trajectory, md, dt_us_per_m, anchor_md, anchor_twt_ms, edge_m: float = 30.0,
name: str = "calibrated") -> TDR:
"""Marker-calibrated vertical sonic TDR (the scoring reference of plan §5.2) over the whole survey.
Within the valid DT range: the vertical sonic through the first anchor in that range, stretched between
consecutive anchors in the range and bulk-shifted beyond them (`calibrate_to_anchors`). Outside the valid DT
range, which only places the well path in time and never carries labels: piecewise linear in TVD through the
anchors there, continued at the outermost segment's velocity; with no anchor on that side, constant vertical
velocity equal to the median sonic velocity over the adjacent `edge_m` of logged hole."""
md, dt = np.asarray(md, dtype=float), np.asarray(dt_us_per_m, dtype=float)
ok = np.isfinite(dt) & (dt > 0)
if ok.sum() < 2:
raise ValueError("no valid DT")
md_v, dt_v = md[ok], dt[ok]
m0, m1 = md_v[0], md_v[-1]
za, ta = _sorted_anchors(anchor_md, anchor_twt_ms)
inside = (za >= m0) & (za <= m1)
if inside.sum() < 2:
raise ValueError(f"{traj.name}: fewer than two anchors within the valid DT range {m0}–{m1} m")
base = vertical_sonic_tdr(md_v, traj.at(md_v)[0], dt_v, za[inside][0], ta[inside][0])
core = calibrate_to_anchors(base, za[inside], ta[inside], name)
def extend(nodes: np.ndarray, beyond: np.ndarray, edge_md: float, edge_t: float, edge_dt: np.ndarray):
if nodes.size == 0:
return nodes
zc = np.r_[traj.at(za[beyond])[0], traj.at(edge_md)[0]]
tc = np.r_[ta[beyond], edge_t]
zn = traj.at(nodes)[0]
if zc.size >= 2:
order = np.argsort(zc)
return _interp_extrap(zn, zc[order], tc[order])
return edge_t + 2000.0 * (zn - zc[0]) / float(np.median(1e6 / edge_dt))
up, down = za < m0, za > m1
md_up = _nodes(traj, -np.inf, m0, za[up])
md_down = _nodes(traj, m1, np.inf, za[down])
t_up = extend(md_up, up, m0, core.twt_ms[0], dt_v[md_v <= m0 + edge_m])
t_down = extend(md_down, down, m1, core.twt_ms[-1], dt_v[md_v >= m1 - edge_m])
return TDR(np.r_[md_up, core.md, md_down], np.r_[t_up, core.twt_ms, t_down], name)
def anchor_tdr(traj: Trajectory, anchor_md, anchor_twt_ms, name: str = "anchors") -> TDR:
"""Piecewise linear in TVD between anchors, without the sonic. Meaningful only within the anchor span."""
za, ta = _sorted_anchors(anchor_md, anchor_twt_ms)
nodes = np.union1d(_nodes(traj, za[0], za[-1]), za)
return TDR(nodes, np.interp(traj.at(nodes)[0], traj.at(za)[0], ta), name)
def path_at_times(traj: Trajectory, tdr: TDR, t_ms) -> dict[str, np.ndarray]:
"""Well position at each time of `t_ms` under `tdr`. Below TD (or above the first station) the position is
held at the end station, i.e. the path continues vertically; `beyond` flags those samples."""
md = tdr.depth_at(t_ms)
tvd, x, y = traj.at(np.clip(md, traj.md[0], traj.md[-1]))
return {"md": md, "tvd": tvd, "x": x, "y": y, "beyond": (md < traj.md[0]) | (md > traj.md[-1])}
def tvdss_td_model(trajs: list[Trajectory], tdrs: list[TDR], z) -> np.ndarray:
"""Mean TWT over wells at TVDSS `z`; each well's MD-keyed TDR is mapped through its own trajectory and
extrapolated linearly beyond its nodes. Used to place a held-out well in time without its own TD data."""
z = np.asarray(z, dtype=float)
out = []
for traj, tdr in zip(trajs, tdrs, strict=True):
md = tdr.md[(tdr.md >= traj.md[0]) & (tdr.md <= traj.md[-1])]
zs = traj.tvdss(md)
if np.any(np.diff(zs) <= 0):
raise ValueError(f"{traj.name}: TVDSS does not increase strictly along the TDR nodes")
out.append(_interp_extrap(z, zs, tdr.time_at(md)))
return np.mean(out, axis=0)
def tdr_from_tvdss(traj: Trajectory, z_model, t_model, name: str = "tvdss_model") -> TDR:
"""MD-keyed TDR of `traj` over its survey from a TVDSS → TWT function (z_model, t_model)."""
md = np.union1d(_nodes(traj, -np.inf, np.inf), traj.md)
return TDR(md, _interp_extrap(traj.tvdss(md), np.asarray(z_model, float), np.asarray(t_model, float)), name)
def composite_patch(cube, il, xl, times_ms, radius: int = 1, method: str = "bilinear",
cache: dict | None = None) -> np.ndarray:
"""Seismic patch along a well path, shape (C, L) with C = (2r+1)²: channel (di, dx), in the IL-major order of
`SeismicCube.patch`, holds at sample n the trace at (il[n] + di, xl[n] + dx) evaluated at times_ms[n], which
must lie on the cube's sample grid. 'bilinear' interpolates the four surrounding bins; 'nearest' takes the
nearest one. `cube` needs `times_ms`, `dt_ms` and `trace(il, xl)`; `cache` maps (il, xl) to traces."""
if method not in ("bilinear", "nearest"):
raise ValueError(f"unknown method {method!r}")
il, xl, t = (np.asarray(v, dtype=float) for v in (il, xl, times_ms))
k = np.rint((t - cube.times_ms[0]) / cube.dt_ms).astype(int)
if np.any(k < 0) or np.any(k >= len(cube.times_ms)) or not np.allclose(cube.times_ms[k], t, rtol=0, atol=1e-6):
raise ValueError("times_ms must lie on the cube's sample grid")
cache = {} if cache is None else cache
def add(out: np.ndarray, i: np.ndarray, j: np.ndarray, w: np.ndarray) -> None:
on = w > 0
for key in set(zip(i[on].tolist(), j[on].tolist())):
if key not in cache:
cache[key] = cube.trace(*key)
sel = on & (i == key[0]) & (j == key[1])
out[sel] += w[sel] * cache[key][k[sel]]
channels = []
for di in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
fi, fj = il + di, xl + dx
out = np.zeros(t.size)
if method == "nearest":
add(out, np.rint(fi).astype(int), np.rint(fj).astype(int), np.ones(t.size))
else:
i0, j0 = np.floor(fi).astype(int), np.floor(fj).astype(int)
wi, wj = fi - i0, fj - j0
for a, b, w in ((0, 0, (1 - wi) * (1 - wj)), (0, 1, (1 - wi) * wj),
(1, 0, wi * (1 - wj)), (1, 1, wi * wj)):
add(out, i0 + a, j0 + b, w)
channels.append(out)
return np.stack(channels).astype(np.float32)