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:
281
ml_porosity/data/deviated.py
Normal file
281
ml_porosity/data/deviated.py
Normal file
@@ -0,0 +1,281 @@
|
||||
"""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)
|
||||
126
ml_porosity/data/volve_wells.py
Normal file
126
ml_porosity/data/volve_wells.py
Normal file
@@ -0,0 +1,126 @@
|
||||
"""P4 Volve wells: survey, petrophysical logs and TWT anchors of one wellbore (`p4` section of configs/d3_volve.yaml).
|
||||
|
||||
Logs are taken from the petrophysical interpretation (WLC_PETRO_COMPUTED_INPUT/OUTPUT LAS, MD from RKB) and
|
||||
converted to the F3 units: DT µs/m, RHOB kg/m³, AI = RHOB·Vp in (m/s)·(kg/m³). Anchors are the well picks with a
|
||||
TWT, minus the excluded surfaces and quality flags; picks at the same MD (e.g. SHETLAND GP. Top = Ekofisk Fm. Top)
|
||||
or within `min_sep_m` of a shallower anchor are one marker.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.data.deviated import Trajectory, read_compass_header
|
||||
from ml_porosity.data.las_io import read_las
|
||||
from ml_porosity.paths import volve_root
|
||||
|
||||
FT_M = 0.3048
|
||||
_UNITS = {"DT": {"us/ft"}, "RHOB": {"g/cm3"}, "NPHI": {"v/v", "v/v_decimal"}, "PHIF": {"v/v", "v/v_decimal"}}
|
||||
ANCHOR_COLUMNS = ["surface", "qlf", "md", "tvd", "tvdss", "twt_ms", "x", "y"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VolveWell:
|
||||
name: str # short name used in P4, e.g. "F-11 T2"
|
||||
pick_name: str # name in the well picks, e.g. "NO 15/9-F-11 T2"
|
||||
traj: Trajectory
|
||||
header: dict[str, str] # Compass survey header
|
||||
logs: pd.DataFrame # index MD (m RKB) within the survey; DT, RHOB, NPHI, GR, PHIF, AI
|
||||
anchors: pd.DataFrame # ANCHOR_COLUMNS, strictly increasing in MD and TWT
|
||||
excluded: pd.DataFrame # picks with a TWT that are not anchors: ANCHOR_COLUMNS + `reason`
|
||||
qc: dict = field(default_factory=dict) # loader counts: DT samples rejected, samples dropped beyond the survey
|
||||
|
||||
def valid_range(self, curve: str) -> tuple[float, float]:
|
||||
v = self.logs[curve].dropna()
|
||||
return float(v.index[0]), float(v.index[-1])
|
||||
|
||||
def label_support(self, label: str = "PHIF") -> tuple[float, float]:
|
||||
"""MD range of the label within the valid DT range: labels are never placed by an extrapolated TDR."""
|
||||
(a, b), (c, d) = self.valid_range(label), self.valid_range("DT")
|
||||
if max(a, c) >= min(b, d):
|
||||
raise ValueError(f"{self.name}: {label} and DT do not overlap")
|
||||
return max(a, c), min(b, d)
|
||||
|
||||
|
||||
def blind_training_wells(test: str, scheme: str, p4: dict) -> tuple[str, ...]:
|
||||
"""Wells whose data may be used when `test` is held out: `lowo` all others, `slot` all outside its slot group."""
|
||||
if scheme == "lowo":
|
||||
out = set(p4["wells"]) - {test}
|
||||
elif scheme == "slot":
|
||||
group = next(set(g) for g in p4["slot_groups"] if test in g)
|
||||
out = set(p4["wells"]) - group
|
||||
else:
|
||||
raise ValueError(f"unknown blind scheme {scheme!r}")
|
||||
return tuple(w for w in p4["wells"] if w in out)
|
||||
|
||||
|
||||
def blind_key(wells) -> str:
|
||||
"""npz key of the blind input placed in time by the TD model of `wells` (any order)."""
|
||||
return "+".join(sorted(wells))
|
||||
|
||||
|
||||
def well_anchors(picks: pd.DataFrame, pick_name: str, exclude_surfaces, exclude_qlf,
|
||||
min_sep_m: float = 0.0) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""(anchors, excluded) for one well from `read_well_picks` output. A pick at most `min_sep_m` below the last
|
||||
kept anchor is dropped, preferring picks without a quality flag at equal MD; picks at the same MD must agree
|
||||
in TWT."""
|
||||
p = picks[(picks.well == pick_name) & picks.twt_ms.notna()].copy()
|
||||
p["reason"] = ""
|
||||
p.loc[p.qlf.isin(exclude_qlf), "reason"] = "qlf " + p.qlf
|
||||
p.loc[p.surface.isin(exclude_surfaces), "reason"] = "surface"
|
||||
cand = p[p.reason == ""].assign(flagged=lambda d: d.qlf != "").sort_values(["md", "flagged"], kind="stable")
|
||||
keep: list = []
|
||||
for i, r in cand.iterrows():
|
||||
if keep and r.md - p.at[keep[-1], "md"] <= min_sep_m:
|
||||
first = p.loc[keep[-1]]
|
||||
if r.md == first.md and abs(r.twt_ms - first.twt_ms) > 0.1:
|
||||
raise ValueError(f"{pick_name}: picks at MD {r.md} disagree in TWT")
|
||||
p.at[i, "reason"] = (f"same MD as {first.surface}" if r.md == first.md
|
||||
else f"{r.md - first.md:.2f} m below {first.surface}")
|
||||
else:
|
||||
keep.append(i)
|
||||
anchors = p.loc[keep, ANCHOR_COLUMNS].reset_index(drop=True)
|
||||
if np.any(np.diff(anchors.twt_ms) <= 0):
|
||||
raise ValueError(f"{pick_name}: anchor TWT does not increase with MD")
|
||||
excluded = p.loc[p.reason != "", ANCHOR_COLUMNS + ["reason"]].sort_values("md", kind="stable")
|
||||
return anchors, excluded.reset_index(drop=True)
|
||||
|
||||
|
||||
def load_volve_well(name: str, cfg: dict, picks: pd.DataFrame) -> VolveWell:
|
||||
p4, spec, root = cfg["p4"], cfg["p4"]["wells"][name], volve_root()
|
||||
survey = root / p4["survey_dir"] / spec["survey"]
|
||||
traj = Trajectory.from_compass(survey, name)
|
||||
folder = root / cfg["well_logs_dir"] / spec["logs"] / p4["log_subdir"]
|
||||
li, ui, _ = read_las(folder / p4["las_input"])
|
||||
lo, uo, _ = read_las(folder / p4["las_output"])
|
||||
units = ui | {"PHIF": uo.get("PHIF", "")}
|
||||
for c, ok in _UNITS.items():
|
||||
if units.get(c, "").lower() not in ok:
|
||||
raise ValueError(f"{name}: unexpected unit {units.get(c)!r} for {c}")
|
||||
|
||||
# OUTPUT is sampled on the INPUT MD grid (0.1 m; 0.5 ft for F-12)
|
||||
key = np.round(li.index.to_numpy(), 3)
|
||||
phif = pd.Series(lo["PHIF"].to_numpy(), index=np.round(lo.index.to_numpy(), 3))
|
||||
if not phif.index.isin(key).all():
|
||||
raise ValueError(f"{name}: OUTPUT depths are not on the INPUT grid")
|
||||
dt_ft = li["DT"].to_numpy(dtype=float)
|
||||
lo_ft, hi_ft = p4["dt_valid_us_per_ft"]
|
||||
bad = np.isfinite(dt_ft) & ((dt_ft < lo_ft) | (dt_ft > hi_ft))
|
||||
dt = np.where(bad, np.nan, dt_ft) / FT_M
|
||||
rhob = li["RHOB"].to_numpy(dtype=float) * 1000.0
|
||||
logs = pd.DataFrame({"DT": dt, "RHOB": rhob, "NPHI": li["NPHI"].to_numpy(dtype=float),
|
||||
"GR": li["GR"].to_numpy(dtype=float), "PHIF": phif.reindex(key).to_numpy(dtype=float),
|
||||
"AI": rhob * 1e6 / dt}, index=pd.Index(li.index.to_numpy(dtype=float), name="MD"))
|
||||
|
||||
# Only positions on the survey can be placed in time. F-12 has GR down to 4187 m below its 3520 m TD.
|
||||
inside = (logs.index >= traj.md[0]) & (logs.index <= traj.md[-1])
|
||||
beyond = logs[~inside].notna().sum()
|
||||
if beyond[["DT", p4["label"]]].any():
|
||||
raise ValueError(f"{name}: DT or {p4['label']} beyond the survey {traj.md[0]}–{traj.md[-1]} m")
|
||||
anchors, excluded = well_anchors(picks, spec["picks"], cfg["anchor_exclude_surfaces"], p4["anchor_exclude_qlf"],
|
||||
p4["anchor_min_sep_m"])
|
||||
qc = {"n_dt_rejected": int(bad.sum()), "n_beyond_survey": {c: int(n) for c, n in beyond.items() if n}}
|
||||
return VolveWell(name, spec["picks"], traj, read_compass_header(survey), logs[inside], anchors, excluded, qc)
|
||||
Reference in New Issue
Block a user