"""QC dữ liệu minh giải Volve (Geophysical_Interpretations) trước khi có cube. python scripts/07_volve_interp_qc.py Kiểm tra: lưới các horizon, số anchor TWT của well picks tại 10 giếng D3 (9 giếng PHIF và F-15 A), độ lệch pick − horizon tại toạ độ pick, độ lệch pick − checkshot (F-11 T2, F-15 A), ROI theo IL/XL của lưới ST10010; nếu đã có cube: toạ độ header so với lưới horizon, và lag của cực trị biên độ trung bình dọc mỗi horizon (≈ 0 nếu trục thời gian đúng). Đầu ra: outputs/volve/{horizons,anchors,pick_vs_horizon,pick_vs_checkshot,horizon_lag}.csv, summary.json """ from __future__ import annotations import json import numpy as np import pandas as pd import yaml from ml_porosity.data.seismic_io import SeismicCube from ml_porosity.data.volve_io import read_checkshot, read_horizon, read_well_picks from ml_porosity.paths import REPO_ROOT, outputs_dir, volve_root def main() -> None: cfg = yaml.safe_load((REPO_ROOT / "configs" / "d3_volve.yaml").read_text()) root, out = volve_root(), outputs_dir() / "volve" out.mkdir(parents=True, exist_ok=True) hdir = root / cfg["horizons_twt"] summary = {} # lưới horizon rows, hors = [], {} for f in sorted(hdir.parent.rglob("*.dat")): h = read_horizon(f) g = h.geometry() res = np.hypot(*(np.array(g.bin_to_xy(h.il, h.xl)) - np.array([h.x, h.y]))).max() key = f.relative_to(hdir.parent).as_posix() hors[key] = h rows.append(dict(file=key, survey=h.survey, domain=h.domain, n=len(h.z), il_min=g.il_range[0], il_max=g.il_range[1], xl_min=g.xl_range[0], xl_max=g.xl_range[1], z_min=h.z.min(), z_max=h.z.max(), bin_m=np.round(g.bin_spacing(), 3).tolist(), affine_res_m=round(float(res), 3))) H = pd.DataFrame(rows) H.to_csv(out / "horizons.csv", index=False) geom = hors[f"{hdir.name}/{cfg['grid_horizon']}"].geometry() summary["grid"] = {"x_coef": geom.x_coef, "y_coef": geom.y_coef, "bin_m": geom.bin_spacing(), "max_affine_residual_m_all_horizons": float(H.affine_res_m.max())} # anchor TWT tại giếng chính P = read_well_picks(root / cfg["picks"]) P["il"], P["xl"] = geom.xy_to_bin(P.x, P.y) ok = (P.twt_ms.notna() & ~P.qlf.isin(cfg["anchor_exclude_qlf"]) & ~P.surface.isin(cfg["anchor_exclude_surfaces"])) A = P[ok & P.well.isin(cfg["wells"])].sort_values(["well", "md"]) A.to_csv(out / "anchors.csv", index=False) per_well = {} for w in cfg["wells"]: a = A[A.well == w].drop_duplicates("md") per_well[w] = {"n_anchors": len(a), "md": [a.md.min(), a.md.max()], "twt_ms": [a.twt_ms.min(), a.twt_ms.max()], "n_faulted": int((a.qlf == "FP").sum())} summary["anchors"] = per_well # TWT nông: cùng MD, khác nhánh khoan sh = P[P.surface.isin(["Utsira Fm. Top", "HORDALAND GP. Top"]) & P.twt_ms.notna()] summary["shallow_twt_spread_ms"] = {s: [float(g.twt_ms.min()), float(g.twt_ms.max())] for s, g in sh.groupby("surface")} # pick − horizon tại toạ độ pick C = [] for s, f in cfg["pick_horizons"].items(): h = hors[f"{hdir.name}/{f}"] for _, r in P[(P.surface == s) & P.twt_ms.notna() & P.x.notna() & (P.qlf != "NL")].iterrows(): z = h.at(r.il, r.xl, radius=1) if np.isfinite(z): C.append(dict(well=r.well, surface=s, qlf=r.qlf, key=r.well in cfg["wells"], il=r.il, xl=r.xl, pick_ms=r.twt_ms, horizon_ms=z, d_ms=r.twt_ms - z)) C = pd.DataFrame(C) C.to_csv(out / "pick_vs_horizon.csv", index=False) clean = C[C.key & (C.qlf == "")] summary["pick_minus_horizon_ms"] = { s: {"n": len(g), "median": round(float(g.d_ms.median()), 1), "mad": round(float((g.d_ms - g.d_ms.median()).abs().median()), 1), "max_abs": round(float(g.d_ms.abs().max()), 1)} for s, g in clean.groupby("surface")} # pick − checkshot (theo TVDSS để không phụ thuộc mốc MD) D = [] for w, files in cfg["checkshots"].items(): p = P[(P.well == w) & P.twt_ms.notna()] for kind, rel in files.items(): cs = read_checkshot(root / cfg["well_logs_dir"] / rel) q = p[(-p.tvdss >= cs.tvdss.min()) & (-p.tvdss <= cs.tvdss.max())] for _, r in q.iterrows(): D.append(dict(well=w, checkshot=kind, surface=r.surface, qlf=r.qlf, md=r.md, pick_ms=r.twt_ms, d_tvd_ms=r.twt_ms - np.interp(-r.tvdss, cs.tvdss, cs.twt_ms), d_md_ms=r.twt_ms - np.interp(r.md, cs.md, cs.twt_ms))) D = pd.DataFrame(D) D.to_csv(out / "pick_vs_checkshot.csv", index=False) deep = D[~D.surface.isin(cfg["anchor_exclude_surfaces"])] summary["pick_minus_checkshot_ms"] = {f"{w} {k}": [round(float(g.d_tvd_ms.min()), 1), round(float(g.d_tvd_ms.max()), 1)] for (w, k), g in deep.groupby(["well", "checkshot"])} # ROI theo IL/XL x0, x1, y0, y1 = cfg["roi_xy"] il, xl = geom.xy_to_bin([x0, x1, x1, x0], [y0, y0, y1, y1]) summary["roi_ilxl"] = {"il": [int(np.floor(il.min())), int(np.ceil(il.max()))], "xl": [int(np.floor(xl.min())), int(np.ceil(xl.max()))]} summary["anchor_twt_range_ms"] = [float(A.twt_ms.min()), float(A.twt_ms.max())] # cube: header so với lưới horizon; horizon pick trên peak/trough nên cực trị phải ở lag ≈ 0 cube_path = root / cfg["cube"] if cube_path.exists(): (i0, i1), (j0, j1) = summary["roi_ilxl"]["il"], summary["roi_ilxl"]["xl"] rng, lags, L = np.random.default_rng(0), np.arange(-24, 25, 1.0), [] with SeismicCube(cube_path) as c: bins = [(int(i), int(j)) for i, j in zip(rng.integers(i0, i1 + 1, 200), rng.integers(j0, j1 + 1, 200))] xy = np.array([c.coords(i, j) for i, j in bins]) gx, gy = geom.bin_to_xy(*np.array(bins).T) summary["cube"] = {"file": cube_path.name, "il": [int(c.ilines[0]), int(c.ilines[-1])], "xl": [int(c.xlines[0]), int(c.xlines[-1])], "t_ms": [c.times_ms[0], c.times_ms[-1]], "dt_ms": c.dt_ms, "max_header_vs_grid_m": float(np.hypot(xy[:, 0] - gx, xy[:, 1] - gy).max())} for s in ("Ty Fm. Top", "SHETLAND GP. Top", "Draupne Fm. Top", "Hugin Fm. VOLVE Top", "Hugin Fm. VOLVE Base"): h = hors[f"{hdir.name}/{cfg['pick_horizons'][s]}"] m = np.flatnonzero((h.il >= i0) & (h.il <= i1) & (h.xl >= j0) & (h.xl <= j1)) amp = [] for k in rng.choice(m, 1500, replace=False): try: amp.append(np.interp(h.z[k] + lags, c.times_ms, c.trace(int(h.il[k]), int(h.xl[k])))) except KeyError: pass mean = np.mean(amp, axis=0) sign = np.sign(mean[lags == 0][0]) L.append(dict(surface=s, horizon=h.name, n=len(amp), polarity=int(sign), lag_ms=float(lags[np.argmax(sign * mean)]), amp_lag0=float(mean[lags == 0][0]))) pd.DataFrame(L).to_csv(out / "horizon_lag.csv", index=False) summary["cube"]["horizon_extremum_lag_ms"] = {r["surface"]: r["lag_ms"] for r in L} (out / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False, default=float)) pd.set_option("display.width", 200) print(H[["file", "survey", "n", "il_min", "il_max", "xl_min", "xl_max", "z_min", "z_max"]].to_string(index=False)) print(json.dumps(summary, indent=1, ensure_ascii=False, default=float)) if __name__ == "__main__": main()