"""Readers for F3 well data: LAS, markers, checkshots, tracks and TD models. Depth convention: MD is measured from KB (m). All four F3 wells are vertical, so MD = TVD + 0 relative to KB; TVDSS = MD − KB. """ from __future__ import annotations from dataclasses import dataclass, field from pathlib import Path import lasio import numpy as np import pandas as pd from ml_porosity.paths import f3_root, f3_wells_dir F3_WELLS = ("F02-1", "F03-2", "F03-4", "F06-1") # IL/XL locations used in the thesis (code_thesis/prepare_data.py:17–21); for auditing only, not used. LEGACY_IL_XL = {"F03-4": (362, 821), "F02-1": (418, 608), "F06-1": (283, 842)} @dataclass class Well: name: str x: float y: float kb: float logs: pd.DataFrame # index = MD (m), columns = mnemonics, NaN in place of NULL units: dict[str, str] = field(default_factory=dict) markers: pd.DataFrame | None = None # columns: md, name checkshot: pd.DataFrame | None = None # columns: md, twt_ms (marker TD, see plan §1.2e) @property def md(self) -> np.ndarray: return self.logs.index.to_numpy(dtype=float) def curve(self, name: str) -> np.ndarray: return self.logs[name].to_numpy(dtype=float) def read_las(path: str | Path) -> tuple[pd.DataFrame, dict[str, str], lasio.LASFile]: las = lasio.read(str(path)) df = las.df() df.index = df.index.astype(float) df.index.name = "MD" units = {c.mnemonic: (c.unit or "") for c in las.curves} return df, units, las def read_two_columns(path: str | Path, skip_header: bool = False) -> np.ndarray: """Read a two-column numeric file (depth, value). `skip_header=True` for OpendTect files (.wlt, .csmdl) whose header ends at the second `!` line.""" lines = Path(path).read_text(errors="replace").splitlines() if skip_header: bangs = [i for i, s in enumerate(lines) if s.strip() == "!"] lines = lines[bangs[1] + 1 :] if len(bangs) >= 2 else lines rows = [] for s in lines: parts = s.split() if len(parts) >= 2: try: rows.append((float(parts[0]), float(parts[1]))) except ValueError: continue return np.asarray(rows, dtype=float) def read_markers(path: str | Path) -> pd.DataFrame: rows = [] for s in Path(path).read_text(errors="replace").splitlines(): s = s.strip() if not s: continue depth, name = s.split(None, 1) rows.append((float(depth), name.strip())) return pd.DataFrame(rows, columns=["md", "name"]) def read_track(path: str | Path) -> np.ndarray: """Columns: X, Y, TVDSS (m), MD (m).""" return np.loadtxt(path) def load_well(name: str, wells_dir: Path | None = None) -> Well: d = wells_dir or f3_wells_dir() df, units, las = read_las(d / "Lasfiles" / f"{name}_logs.las") track = read_track(d / "Track" / f"{name}.track") x, y = float(track[0, 0]), float(track[0, 1]) kb = float(las.well["EKB"].value) markers = read_markers(d / "Tops" / f"{name}_markers.txt") # Checkshot files contain duplicate rows (several markers at the same depth) and are unsorted (F03-2, F03-4). cs = read_two_columns(d / "Checkshot" / f"{name}_TD.txt") checkshot = ( pd.DataFrame({"md": cs[:, 0], "twt_ms": cs[:, 1] * 1000.0}) .drop_duplicates() .sort_values("md", ignore_index=True) ) return Well(name, x, y, kb, df, units, markers, checkshot) def load_td_source(name: str, source: str) -> np.ndarray: """(MD m, TWT ms) pairs from a TD source. source: "checkshot" – Checkshot/*_TD.txt (marker times tied to horizons, seconds) "dt_model" – DT_model/*_TD.txt (ms; unknown provenance, offset from checkshot, plan §1.2c) "wlt" – WellInfo/*.wlt (OpendTect Depth2Time model, seconds) """ d = f3_wells_dir() if source == "checkshot": a = read_two_columns(d / "Checkshot" / f"{name}_TD.txt") return np.column_stack([a[:, 0], a[:, 1] * 1000.0]) if source == "dt_model": return read_two_columns(d / "DT_model" / f"{name}_TD.txt") if source == "wlt": a = read_two_columns(f3_root() / "WellInfo" / f"{name}.wlt", skip_header=True) return np.column_stack([a[:, 0], a[:, 1] * 1000.0]) raise ValueError(f"invalid TD source: {source}")