"""Kiểm tra D-1 (định nghĩa nhãn F3) bằng density đo của NLOG. python scripts/08_d1_label_check.py PHIE của bộ demo ở F03-2, F03-4, F06-1 là hàm tuyến tính của DT (plan mục 1.2d). Script so porosity theo density đo φ_D = (2650 − RHOB)/1600 (RHOB từ LAS NLOG) với nhãn sonic PHIE_DT = −0.2018 + 0.0011·DT trong cửa sổ 600–1100 ms, trên lưới 4 ms như nhãn huấn luyện: - F02-1, F03-4: giếng demo, TD calibrated từ outputs/f3_wells.npz; độ sâu NLOG căn theo tương quan DT; - F03-03, F03-06: giếng NLOG ngoài bộ demo, TD theo file TZ (giả định MD − APD ≈ TVDSS ở đoạn nông); - F03-2, F06-1: RHOB đo của NLOG bắt đầu ở 1641 và 1836 m MD, dưới cửa sổ, nên không có φ_D. Kèm chỉ số chất lượng trong cửa sổ: |DRHO| và caliper (từ composite LAS; chưa có bit size nên chưa kết luận washout). Đầu ra: 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 # (LAS composite có RHOB/DRHO, LAS composite có CALI theo feet, file TZ); tên gốc NLOG có tiền tố giếng 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") # băng seismic > 6 Hz (plan mục 2.3) trên lưới 4 ms 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, từ LMF) → DT µs/m, RHOB và DRHO kg/m³, CALI inch; kèm APD (m trên 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 theo p.u. trên lưới T; r băng tính trên đoạn liên tục chung.""" 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: # giếng demo: căn độ sâu NLOG theo DT, so với LAS demo 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: # giếng NLOG mới: chỉ có DT của NLOG 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("ghi:", out.relative_to(REPO_ROOT) if out.is_relative_to(REPO_ROOT) else out) if __name__ == "__main__": main()