Files
ML-Porosity/scripts/07_volve_interp_qc.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

144 lines
7.7 KiB
Python
Raw Permalink 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.
"""QC of the Volve interpretation data (Geophysical_Interpretations) before the cube is available.
python scripts/07_volve_interp_qc.py
Checks: horizon grids, number of TWT anchors from the well picks at the 10 D3 wells (9 PHIF wells and F-15 A), pick − horizon
offset at the pick coordinates, pick − checkshot offset (F-11 T2, F-15 A), ROI in IL/XL of the ST10010 grid; if the cube is present:
header coordinates vs the horizon grid, and the lag of the mean-amplitude extremum along each horizon (≈ 0 if the time axis is correct).
Outputs: 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 = {}
# horizon grids
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())}
# TWT anchors at the main wells
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
# shallow TWT: same MD, different well branches
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 at the pick coordinates
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 (in TVDSS, independent of the MD datum)
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 in 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 vs horizon grid; horizons are picked on peaks/troughs, so the extremum should be at 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()