Files
ML-Porosity/ml_porosity/data/las_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
4.3 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 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 (test 2/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}")