"""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)