Files
ML-Porosity/scripts/01_build_wells.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

117 lines
5.0 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.
"""Build the F3 well dataset in the seismic time domain.
python scripts/01_build_wells.py [--config configs/d1_f3.yaml]
Outputs (in outputs/):
f3_wells.npz flat keys "<well>/<item>", no allow_pickle needed. All time series lie on
the extended window `ext_window_ms`; `main_mask` marks the main window:
seismic_patch (C, L), times_ms (L,), main_mask (L,), il, xl, x, y,
anchors_md, anchors_twt_ms, tdr/<name>/md, tdr/<name>/twt_ms,
<TDR name>/<curve> (L,), horizon/<name> (TWT ms at the well)
f3_wells_summary.json well locations (true and as used in the thesis), anchor counts, label coverage.
"""
from __future__ import annotations
import argparse
import json
import numpy as np
import yaml
from ml_porosity.data.geometry import SurveyGeometry
from ml_porosity.data.horizons import F3_HORIZONS, horizon_at
from ml_porosity.data.las_io import LEGACY_IL_XL, Well, load_td_source, load_well
from ml_porosity.data.resample import log_to_time
from ml_porosity.data.seismic_io import SeismicCube
from ml_porosity.data.tdr import TDR, calibrate_to_anchors, legacy_sonic_tdr, sonic_tdr
from ml_porosity.paths import REPO_ROOT, f3_root, outputs_dir
def build_tdrs(well: Well, names: list[str]) -> dict[str, TDR]:
cs = well.checkshot
dt = well.curve("DT")
out = {}
for name in names:
if name == "legacy":
out[name] = legacy_sonic_tdr(well.md, dt)
elif name == "calibrated":
base = sonic_tdr(well.md, dt, md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
out[name] = calibrate_to_anchors(base, cs.md, cs.twt_ms)
elif name == "anchors":
out[name] = TDR.from_pairs(cs.to_numpy(), "anchors")
elif name == "wlt":
out[name] = TDR.from_pairs(load_td_source(well.name, "wlt"), "wlt", drop_flat=True)
else:
raise ValueError(f"unsupported TDR: {name}")
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--config", default=str(REPO_ROOT / "configs" / "d1_f3.yaml"))
cfg = yaml.safe_load(open(ap.parse_args().config))
geom = SurveyGeometry.from_survey(f3_root())
t0, t1 = cfg["time_window_ms"]
e0, e1 = cfg["ext_window_ms"]
arrays: dict[str, np.ndarray] = {}
summary = {"config": cfg, "wells": {}}
with SeismicCube() as cube:
win = cube.window(e0, e1)
t_win = cube.times_ms[win]
main = (t_win >= t0) & (t_win <= t1)
for name in cfg["wells"]:
w = load_well(name)
# Harmonized label per plan §1.2d / D-1: PHIE_DT = −0.2018 + 0.0011·DT for all 4 wells.
w.logs["PHIE_DT"] = -0.2018 + 0.0011 * w.logs["DT"]
il, xl = geom.nearest_bin(w.x, w.y)
patch = cube.patch(il, xl, cfg["patch_radius"])[:, win]
tdrs = build_tdrs(w, cfg["tdrs"])
p = f"{name}/"
arrays.update({
p + "seismic_patch": patch,
p + "times_ms": t_win,
p + "main_mask": main,
p + "il": np.int32(il), p + "xl": np.int32(xl),
p + "x": np.float64(w.x), p + "y": np.float64(w.y),
p + "anchors_md": w.checkshot.md.to_numpy(),
p + "anchors_twt_ms": w.checkshot.twt_ms.to_numpy(),
})
coverage = {}
for tname, tdr in tdrs.items():
arrays[p + f"tdr/{tname}/md"] = tdr.md
arrays[p + f"tdr/{tname}/twt_ms"] = tdr.twt_ms
for c in cfg["curves"]:
v = log_to_time(w.md, w.curve(c), tdr, t_win, **cfg["resample"])
arrays[p + f"{tname}/{c}"] = v
coverage[f"{tname}/{c}"] = round(float(np.isfinite(v[main]).mean()), 3)
for h in F3_HORIZONS:
arrays[p + f"horizon/{h}"] = np.float64(horizon_at(h, geom, [(il, xl)])[0])
info = {"x": w.x, "y": w.y, "kb": w.kb, "il": il, "xl": xl,
"n_anchors_in_window": int(w.checkshot.twt_ms.between(t0, t1).sum()),
"label_coverage": coverage}
if name in LEGACY_IL_XL:
lil, lxl = LEGACY_IL_XL[name]
lx, ly = geom.bin_to_xy(lil, lxl)
info["legacy_il_xl"] = [lil, lxl]
info["legacy_offset_km"] = round(float(np.hypot(lx - w.x, ly - w.y)) / 1000, 2)
summary["wells"][name] = info
print(f"{name}: IL/XL {il}/{xl}"
+ (f" (thesis {info['legacy_il_xl'][0]}/{info['legacy_il_xl'][1]}, offset {info['legacy_offset_km']} km)"
if "legacy_il_xl" in info else "")
+ f", {info['n_anchors_in_window']} anchors in window, "
+ f"PHIE coverage (calibrated) {coverage.get('calibrated/PHIE', float('nan')):.0%}")
out = outputs_dir()
np.savez_compressed(out / "f3_wells.npz", **arrays)
(out / "f3_wells_summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))
print(f"-> {out / 'f3_wells.npz'}")
if __name__ == "__main__":
main()