Files
ML-Porosity/ml_porosity/data/volve_io.py
lamlvh cee2ff0859 P2 diagnosis on dev, P3 dev experiments, lock protocol_p3
- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:33 +00:00

122 lines
5.0 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.
"""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]})