"""Readers for Volve data: horizons exported from OpenWorks, well picks (fixed-width columns) and VSP checkshots. Conventions: MD is measured from RKB (54.9 m above MSL), TVDSS and TWT from MSL; coordinates are ED50 / UTM 31N. The horizon grid is the ST10010 grid (12.5 × 12.5 m). Files labelled ST0202 also number IL/XL on this grid (affine discrepancy < 0.11 m within the well ROI). """ from __future__ import annotations from dataclasses import dataclass from functools import cached_property from pathlib import Path import numpy as np import pandas as pd from ml_porosity.data.geometry import SurveyGeometry VOLVE_RKB_M = 54.9 VOLVE_EPSG = 23031 # The 9 wells with PHIF (D3) plus F-15 A (no PHIF but a VSP checkshot), matching the ROI in docs/research/volve-inventory.md VOLVE_KEY_WELLS = ("NO 15/9-F-1", "NO 15/9-F-1 A", "NO 15/9-F-1 B", "NO 15/9-F-1 C", "NO 15/9-F-11 A", "NO 15/9-F-11 B", "NO 15/9-F-11 T2", "NO 15/9-F-12", "NO 15/9-F-15 A", "NO 15/9-F-15 D") @dataclass(frozen=True) class Horizon: survey: str name: str domain: str # "TIME" (TWT ms) or "DEPTH" (m) il: np.ndarray xl: np.ndarray x: np.ndarray y: np.ndarray z: np.ndarray def geometry(self) -> SurveyGeometry: return SurveyGeometry.from_points(self.il, self.xl, self.x, self.y, epsg=VOLVE_EPSG) @cached_property def lut(self) -> dict[tuple[int, int], float]: return {(int(i), int(j)): float(v) for i, j, v in zip(self.il, self.xl, self.z)} def at(self, il: float, xl: float, radius: int = 1) -> float: """Median z of the nodes within the (2·radius+1)² window around the nearest bin; NaN if there are no nodes.""" i0, j0 = int(np.rint(il)), int(np.rint(xl)) vals = [self.lut[k] for di in range(-radius, radius + 1) for dj in range(-radius, radius + 1) if (k := (i0 + di, j0 + dj)) in self.lut] return float(np.median(vals)) if vals else float("nan") def read_horizon(path: str | Path) -> Horizon: """`*.dat` file layout: `#` comment lines, 4 metadata lines (survey, name, interpreter, domain), followed by one `IL,XL,X,Y,Z` row per line. Some files leave the survey line empty (only `=`).""" meta, rows = [], [] with open(path, errors="replace") as fh: for line in fh: if line.startswith("#") or not line.strip(): continue parts = line.strip().split(",") if len(parts) == 5: try: rows.append([float(v) for v in parts]) continue except ValueError: pass meta.append(line.strip()) a = np.asarray(rows) survey, name, _, domain = (meta + [""] * 4)[:4] return Horizon(survey=survey, name=name, domain=domain, il=a[:, 0].astype(int), xl=a[:, 1].astype(int), x=a[:, 2], y=a[:, 3], z=a[:, 4]) PICK_COLUMNS = {"Well name": "well", "Surface name": "surface", "Obs#": "obs", "Qlf": "qlf", "MD": "md", "TVD": "tvd", "TVDSS": "tvdss", "TWT": "twt_ms", "Dip": "dip", "Azi": "azi", "Easting": "x", "Northing": "y", "Intrp": "interpreter"} def read_well_picks(path: str | Path) -> pd.DataFrame: """`Well_picks_Volve_v1.dat`: each well has a header line and a `---` dash line that defines the column widths. Qlf: ER eroded, FP faulted pick, FO faulted out, NL not logged, NR not reached.""" lines = Path(path).read_text(errors="replace").splitlines() spans, rows = None, [] for i, ln in enumerate(lines): if ln.strip().startswith("Well name") and i + 1 < len(lines) and lines[i + 1].strip().startswith("---"): dash = lines[i + 1] spans, j = [], 0 while j < len(dash): if dash[j] == "-": k = j while k < len(dash) and dash[k] == "-": k += 1 spans.append((j, k, ln[j:k + 1].strip())) j = k else: j += 1 elif spans and ln.startswith(" NO "): rows.append({PICK_COLUMNS[n]: ln[s:e + 1].strip() for s, e, n in spans}) df = pd.DataFrame(rows) for c in ("obs", "md", "tvd", "tvdss", "twt_ms", "dip", "azi", "x", "y"): df[c] = pd.to_numeric(df[c], errors="coerce") df["obs"] = df["obs"].astype(int) return df def read_checkshot(path: str | Path) -> pd.DataFrame: """`TZV_TIME_CHECKSHOT_*.ASC` (3 columns: MD, TVD-MSL, TWT ms). F-11 T2 records MD from RKB and F-15 A from MSL (`MDMSL`), so MD is referred to RKB. Returns columns md (RKB), tvdss (positive down) and twt_ms.""" text = Path(path).read_text(errors="replace") rows = [] for ln in text.splitlines(): p = ln.split() if len(p) == 3: try: rows.append([float(v) for v in p]) except ValueError: pass a = np.asarray(rows) md = a[:, 0] + (VOLVE_RKB_M if "MDMSL" in text else 0.0) return pd.DataFrame({"md": md, "tvdss": a[:, 1], "twt_ms": a[:, 2]})