"""Check D-1 (the F3 label definition) against the measured NLOG density. python scripts/08_d1_label_check.py The demo PHIE at F03-2, F03-4, F06-1 is a linear function of DT (plan §1.2d). This script compares the porosity from measured density φ_D = (2650 − RHOB)/1600 (RHOB from the NLOG LAS) with the sonic label PHIE_DT = −0.2018 + 0.0011·DT in the 600–1100 ms window, on the same 4 ms grid as the training labels: - F02-1, F03-4: demo wells, calibrated TD from outputs/f3_wells.npz; NLOG depth aligned by DT correlation; - F03-03, F03-06: NLOG wells outside the demo set, TD from the TZ file (assuming MD − APD ≈ TVDSS in the shallow section); - F03-2, F06-1: measured NLOG RHOB starts at 1641 and 1836 m MD, below the window, so no φ_D. Also reports in-window quality indicators: |DRHO| and caliper (from the composite LAS; no bit size yet, so no washout conclusion). Outputs: outputs/d1/label_check.csv, summary.json """ from __future__ import annotations import json import lasio import numpy as np import pandas as pd from scipy import signal from ml_porosity.data.las_io import load_well from ml_porosity.data.resample import log_to_time from ml_porosity.data.tdr import TDR from ml_porosity.paths import REPO_ROOT, nlog_root, outputs_dir # (composite LAS with RHOB/DRHO, composite LAS with CALI in feet, TZ file); original NLOG names carry a well prefix NLOG_FILES = { "F02-1": ("F02-01__8727_f0201_1976_comp.las", "F02-01-S1__F021_Composite-TOTAL~LF1.las", None), "F03-4": ("F03-04__7035_f0304_1976_comp.las", "F03-04__F034_Composite-TOTAL~LF1.las", None), "F03-03": ("F03-03__7034_f0303_1974_comp.las", "F03-03__F033_Composite-TOTAL~LF1.las", "F03-03__F03-3_TZ_TM5.txt"), "F03-06": ("F03-06__7037_f0306_1978_comp.las", "F03-06__F036_Composite-TOTAL~LF1.las", "F03-06__F03-6_TZ_TM5.txt"), } WINDOW_MS = (600.0, 1100.0) T = np.arange(WINDOW_MS[0], WINDOW_MS[1] + 0.1, 4.0) SOS_BAND = signal.butter(4, 6 / 125, "high", output="sos") # seismic band > 6 Hz (plan §2.3) on the 4 ms grid def phi_d(rhob): return (2650.0 - rhob) / 1600.0 def phi_dt(dt): return -0.2018 + 0.0011 * dt def read_nlog(comp: str, composite: str) -> tuple[pd.DataFrame, float]: """MD (m, from LMF) → DT µs/m, RHOB and DRHO kg/m³, CALI inch; plus APD (m above MSL).""" raw = nlog_root() / "raw" las = lasio.read(raw / comp) df = las.df().sort_index() df.index = df.index.astype(float) df["DT"] /= 0.3048 df[["RHOB", "DRHO"]] *= 1000.0 c = lasio.read(raw / composite).df() df["CALI"] = np.interp(df.index, c.index.to_numpy(float) * 0.3048, c["CALI"].to_numpy(float), left=np.nan, right=np.nan) return df, float(las.params["APD"].value) def read_tz(path: str, apd: float) -> TDR: rows = [s.split()[1:3] for s in (nlog_root() / "raw" / path).read_text().splitlines() if s.startswith("T/Z")] tz = np.asarray(rows, dtype=float) return TDR.from_pairs(np.column_stack([tz[:, 1] + apd, tz[:, 0]]), "nlog_tz", drop_flat=True) def corr(a: np.ndarray, b: np.ndarray) -> float: ok = np.isfinite(a) & np.isfinite(b) return float(np.corrcoef(a[ok], b[ok])[0, 1]) def compare(a: np.ndarray, b: np.ndarray) -> dict: """a, b in p.u. on grid T; band r computed over the common contiguous segment.""" ok = np.isfinite(a) & np.isfinite(b) r = corr(a, b) i = np.flatnonzero(ok) seg = slice(i[0], i[-1] + 1) r_band = (float(np.corrcoef(signal.sosfiltfilt(SOS_BAND, a[seg]), signal.sosfiltfilt(SOS_BAND, b[seg]))[0, 1]) if ok[seg].all() else np.nan) return dict(n=int(ok.sum()), r=round(r, 3), r2=round(r * r, 3), bias_pu=round(float(np.mean(a[ok] - b[ok])), 2), rms_pu=round(float(np.sqrt(np.mean((a[ok] - b[ok]) ** 2))), 2), r_band=round(r_band, 3), std_a_pu=round(float(np.std(a[ok])), 2), std_b_pu=round(float(np.std(b[ok])), 2)) def quality(df: pd.DataFrame, d0: float, d1: float) -> dict: w = df.loc[d0:d1] drho, cal = w.DRHO.dropna().abs(), w.CALI.dropna() return dict(drho_gt50=round(float((drho > 50).mean()), 3), drho_gt100=round(float((drho > 100).mean()), 3), cali_median_in=round(float(cal.median()), 1), cali_p90_in=round(float(cal.quantile(0.9)), 1)) def main() -> None: out = outputs_dir() / "d1" out.mkdir(parents=True, exist_ok=True) Z = np.load(outputs_dir() / "f3_wells.npz") rows, summary = [], {"window_ms": WINDOW_MS, "wells": {}} for w, (comp, composite, tz) in NLOG_FILES.items(): df, apd = read_nlog(comp, composite) info = {"apd_m": apd} if tz is None: # demo well: align NLOG depth by DT against the demo LAS W = load_well(w) tdr = TDR(Z[f"{w}/tdr/calibrated/md"], Z[f"{w}/tdr/calibrated/twt_ms"], "calibrated") d0, d1 = tdr.depth_at(WINDOW_MS) g = np.arange(d0, d1, 0.1) dt_demo = np.interp(g, W.md, W.curve("DT")) shifts = np.round(np.arange(-8, 8.01, 0.1), 1) shift = float(max(shifts, key=lambda s: corr(np.interp(g + s, df.index, df.DT), dt_demo))) md = df.index.to_numpy() - shift info["depth_shift_nlog_to_demo_m"] = shift + 0.0 for c in ("DT", "RHOB"): a, b = np.interp(g, md, df[c]), np.interp(g, W.md, W.curve(c)) d = (a - b)[np.isfinite(a - b)] info[f"{c}_nlog_vs_demo"] = {"r": round(corr(a, b), 3), "bias": round(float(d.mean()), 1), "rms": round(float(np.sqrt(np.mean(d ** 2))), 1)} labels = {"PHIE_DT": log_to_time(W.md, phi_dt(W.curve("DT")), tdr, T), "PHIE": log_to_time(W.md, W.curve("PHIE"), tdr, T)} else: # new NLOG well: only the NLOG DT is available tdr = read_tz(tz, apd) d0, d1 = tdr.depth_at(WINDOW_MS) md, shift = df.index.to_numpy(), 0.0 labels = {"PHIE_DT": log_to_time(md, phi_dt(df.DT.to_numpy()), tdr, T)} info["window_md_m"] = [round(float(d0), 1), round(float(d1), 1)] info["quality"] = quality(df, d0 + shift, d1 + shift) phid = log_to_time(md, phi_d(df.RHOB.to_numpy()), tdr, T) for name, lab in labels.items(): rows.append(dict(well=w, label=name, demo=tz is None, **compare(100 * phid, 100 * lab))) summary["wells"][w] = info R = pd.DataFrame(rows) R.to_csv(out / "label_check.csv", index=False) summary["phi_d_vs_phie_dt"] = R[R.label == "PHIE_DT"].set_index("well")[["r2", "bias_pu", "rms_pu", "r_band"]].to_dict("index") (out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False)) print(R.to_string(index=False)) print(json.dumps(summary["wells"], indent=1, ensure_ascii=False)) print("written:", out.relative_to(REPO_ROOT) if out.is_relative_to(REPO_ROOT) else out) if __name__ == "__main__": main()