Files
ML-Porosity/ml_porosity/data/las_io.py
holale 9976abc96b Complete P3 F3 evaluation and Windows execution
Implement the frozen F3 protocol, nested LOWO, posterior label banks,
ablations, diagnostics, checkpoint validation and full-volume inference.
Record the negative G-C result: improvement at 1/4 wells, coverage80 52.38%
and coverage90 60.91%, with unchanged thresholds and historical P2 results.

Add native Windows logging, the RTX 3060 environment lock, detached runs,
and an audited dashboard-lock recovery that preserves frozen scientific code.
Update report.html, the plan and agent guidance with completed P3 status.
Archive thesis sources under code_thesis with identical Git blobs and record
the original-output audit without committing large data or model artifacts.

Validation: 129 tests passed, 13 skipped; CUDA end-to-end smoke passed;
completion audit verified 1,320 checkpoint/prediction pairs, 28 registration
bundles and all 649 interior volume inlines. Scripts 04 and 09 were not rerun.

Co-authored-by: Codex <codex@openai.com>
2026-10-28 07:01:08 +07: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 (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}")