- 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>
209 lines
12 KiB
Python
209 lines
12 KiB
Python
"""Placing F3 on the σ_post axis (preparation of protocol_p3, descriptive only): SMC warp posterior on the 4 real F3 wells.
|
||
|
||
python scripts/16_f3_posterior.py --device cuda:1
|
||
|
||
τ is sonic time (DT integrated from the first TD marker, as in scripts/09). Anchors are the TD markers within the
|
||
extended window 400–1300 ms; TD markers are not independent checkshots (plan §10). AI in τ is taken from the LAS AI log,
|
||
anti-alias filtered onto a 0.5 ms grid. The seismic is the central trace of the 3×3 patch at each well
|
||
(outputs/f3_wells.npz).
|
||
|
||
Registration as for D2 under protocol_p2:
|
||
- MAP-II hyperparameters on the anchors of the 4 wells (σ_a = 7 ms, σ_b = 50 ms fixed, hyperprior as in the protocol);
|
||
- 128 ms statistical wavelet from the 4 traces;
|
||
- initial phase from the old fit_phase, then re-estimated by SMC (log Z);
|
||
- SMC up to γ = 1/κ (g_acf) and γ = 1.
|
||
The "f3ml" variant uses the type-II ML hyperparameters of scripts/09 (σ_a ≈ 0.4 ms), i.e. treats the TD markers as
|
||
nearly exact relative to the seismic.
|
||
|
||
There is no true warp, hence no warp error. The script reports:
|
||
- σ_post: mean over the main window of (q95 − q05)/3.29 of τ(t);
|
||
- the particle standard deviation and κ;
|
||
- r between the synthetic at the posterior-mean warp and the seismic over the main window (same definition as the
|
||
r_post column of script 14);
|
||
- r of B3c and the RMS shift of the posterior-mean warp relative to B3b.
|
||
K independent SMC runs (--smc-seeds) measure the Monte Carlo error. The results only describe where F3 lies on the
|
||
σ_post and r axes of D2; they are not used to select γ, P or λ.
|
||
|
||
Outputs: outputs/p2/diag/f3_posterior/{wells.csv, phase.json, particles.npz}.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import importlib.util
|
||
import json
|
||
import os
|
||
import time
|
||
from pathlib import Path
|
||
from types import SimpleNamespace
|
||
|
||
import numpy as np
|
||
import pandas as pd
|
||
import yaml
|
||
|
||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||
|
||
_spec = importlib.util.spec_from_file_location("run_d2", REPO_ROOT / "scripts" / "11_run_d2.py")
|
||
run_d2 = importlib.util.module_from_spec(_spec)
|
||
_spec.loader.exec_module(run_d2)
|
||
|
||
TAU_RANGE = (200.0, 1500.0) # wider than scripts/09 so that τ(t) covers the seismic window ± half a wavelet at every well
|
||
PHASES = np.arange(-180, 180, 15)
|
||
|
||
|
||
def f3_wells(cfg: dict, tau_fine: np.ndarray) -> list[dict]:
|
||
from ml_porosity.data.las_io import load_well
|
||
from ml_porosity.data.resample import log_to_time
|
||
from ml_porosity.data.tdr import sonic_tdr
|
||
|
||
D = np.load(outputs_dir() / "f3_wells.npz")
|
||
e0, e1 = cfg["ext_window_ms"]
|
||
out = []
|
||
for name in cfg["wells"]:
|
||
w = load_well(name)
|
||
cs = w.checkshot
|
||
base = sonic_tdr(w.md, w.curve("DT"), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
|
||
tk = cs.twt_ms.to_numpy()
|
||
tau_k = base.time_at(cs.md.to_numpy())
|
||
m = (tk >= e0) & (tk <= e1)
|
||
ai = log_to_time(w.md, w.curve("AI"), base, tau_fine, **cfg["resample"])
|
||
ok = np.isfinite(ai)
|
||
out.append({"name": name, "tau_k": tau_k[m], "t_k": tk[m],
|
||
"ai_log": np.interp(tau_fine, tau_fine[ok], ai[ok]), # outside the logged interval: constant (zero reflectivity)
|
||
"seis": D[f"{name}/seismic_patch"][4].astype(float), "t": D[f"{name}/times_ms"].astype(float),
|
||
"main": D[f"{name}/main_mask"].astype(bool)})
|
||
return out
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--particles", type=int, default=256)
|
||
ap.add_argument("--smc-seeds", type=int, nargs="+", default=[0, 1, 2, 3])
|
||
ap.add_argument("--settings", nargs="+", default=["proto", "f3ml"], choices=["proto", "f3ml"])
|
||
ap.add_argument("--device", default="cuda:1", help="cpu: smc.py; cuda:k: smc_torch.py")
|
||
ap.add_argument("--gpu-mem-gb", type=float, default=2.0)
|
||
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/f3_posterior")
|
||
args = ap.parse_args()
|
||
for k, v in {"OMP_NUM_THREADS": "4", "MKL_NUM_THREADS": "4", "OPENBLAS_NUM_THREADS": "4"}.items():
|
||
os.environ.setdefault(k, v)
|
||
|
||
from ml_porosity.data.wavelet import statistical_wavelet
|
||
from ml_porosity.registration.labels import invert_warps
|
||
from ml_porosity.registration.pipeline import fit_cell_hyper
|
||
from ml_porosity.registration.sampler import sample_warps
|
||
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet, residual_kappa
|
||
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, phase_loglik, synth_for_warps
|
||
from ml_porosity.registration.ties import tie_b3b, tie_b3c
|
||
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper
|
||
|
||
if args.device == "cpu":
|
||
from ml_porosity.registration.smc import smc_fit_phase, smc_tie_posterior
|
||
wrap = lambda T: T
|
||
else:
|
||
import torch
|
||
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
|
||
dev = torch.device(args.device)
|
||
if dev.type == "cuda":
|
||
total = torch.cuda.get_device_properties(dev).total_memory
|
||
torch.cuda.set_per_process_memory_fraction(min(1.0, args.gpu_mem_gb * 2**30 / total), dev)
|
||
wrap = lambda T: TiePosteriorTorch(T, args.device)
|
||
|
||
P = run_d2.load_protocol(check=True)
|
||
reg = run_d2.reg_settings(P)
|
||
cfg_d2 = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
|
||
cfg = yaml.safe_load((REPO_ROOT / "configs" / "d1_f3.yaml").read_text())
|
||
f, dt = cfg_d2["fine_dt_ms"], cfg_d2["dt_ms"]
|
||
fac = int(round(dt / f))
|
||
grid = WarpGrid(*TAU_RANGE, cfg_d2["warp_dtau_ms"])
|
||
tau_fine = np.arange(TAU_RANGE[0], TAU_RANGE[1] + f / 2, f)
|
||
wells = f3_wells(cfg, tau_fine)
|
||
t_out, mm = wells[0]["t"], wells[0]["main"]
|
||
if not all(np.array_equal(w["t"], t_out) and np.array_equal(w["main"], mm) for w in wells):
|
||
raise SystemExit("seismic time axes differ between wells")
|
||
t_main = t_out[mm]
|
||
t_fine = np.arange(t_out[0] - 300.0, t_out[-1] + 300.0 + f / 2, f)
|
||
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
|
||
w0 = statistical_wavelet(np.stack([w["seis"] for w in wells]), dt, reg["wavelet_ms"])
|
||
B = phase_basis(w0, fac)
|
||
qc = pd.read_csv(outputs_dir() / "tie_qc.csv").set_index(["well", "tdr"])["r_best_tie"]
|
||
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "f3_posterior"
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
rows, phases, saved = [], {}, {}
|
||
for setting in args.settings:
|
||
if setting == "proto":
|
||
h, hinfo = fit_cell_hyper(SimpleNamespace(grid=grid), wells, reg, seed=0)
|
||
hinfo = {k: hinfo[k] for k in ("log_marginal", "at_bound")}
|
||
else:
|
||
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())
|
||
h, hinfo = WarpHyper(**prior["fits"][P["inputs"]["warp_prior"]["fit"]]["hyper"]), {}
|
||
# initial phase as in pipeline.register: old fit_phase on S anchor-posterior samples at γ = 1
|
||
LL = []
|
||
for i, w in enumerate(wells):
|
||
smp = sample_warps(grid, h, w["tau_k"], w["t_k"], reg["S"], reg["g_max"], np.random.default_rng([0, i, 11]))
|
||
T = grid.t_of_tau(smp["b"], smp["g"], tau=tau_fine)
|
||
LL.append(phase_loglik(synth_for_warps(tau_fine, w["ai_log"], T, t_fine, t_out, fine_wavelet(w0, fac)),
|
||
w["seis"], PHASES))
|
||
phase0 = float(PHASES[fit_phase(LL, [np.ones(L.shape[1], bool) for L in LL], PHASES)])
|
||
for k in args.smc_seeds:
|
||
t0 = time.time()
|
||
Ts, Z0s = [], []
|
||
for i, w in enumerate(wells):
|
||
smp = sample_warps(grid, h, w["tau_k"], w["t_k"], args.particles, reg["g_max"],
|
||
np.random.default_rng([k, i, 13]))
|
||
Ts.append(wrap(TiePosterior(grid, h, w["tau_k"], w["t_k"], reg["g_max"], tau_fine, w["ai_log"], t_fine,
|
||
t_out, phase_wavelet(B, phase0), w["seis"], (t_main[0], t_main[-1]))))
|
||
Z0s.append(Ts[-1].z(smp["u"]))
|
||
phase_r, ph = smc_fit_phase(Ts, Z0s, B, phase0, [k, 19])
|
||
phases[f"{setting}/k{k}"] = {"phase0": phase0, "phase_R": phase_r} | ph
|
||
wf = phase_wavelet(B, phase_r)
|
||
key = {"setting": setting, "smc_seed": k, "particles": args.particles, "phase0": phase0, "phase_R": phase_r,
|
||
"phase_edge": ph["edge"]} | {f"hyper_{a}": b for a, b in h.as_dict().items() if a != "kernel"} | hinfo
|
||
for i, w in enumerate(wells):
|
||
T = Ts[i].with_wavelet(wf)
|
||
_, l0 = T.parts(Z0s[i])
|
||
cks = {"g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
|
||
t1 = time.time()
|
||
res = smc_tie_posterior(T, Z0s[i], cks.values(), np.random.default_rng([k, i, 17]))
|
||
t_b3b = tie_b3b(w["tau_k"], w["t_k"], tau_fine)
|
||
syn_b = synth_for_warps(tau_fine, w["ai_log"], t_b3b, t_fine, t_out, wf)[0]
|
||
t_b3c = tie_b3c(t_b3b, tau_fine, syn_b, w["seis"], t_out, dt)
|
||
syn_c = synth_for_warps(tau_fine, w["ai_log"], t_b3c[None], t_fine, t_out, wf)[0]
|
||
tau_b3b = invert_warps(t_b3b[None], tau_fine, t_main)[0]
|
||
info = {"well": w["name"], "n_anchor": len(w["tau_k"]), "kappa0": 1.0 / cks["g_acf"],
|
||
"n_stages": len(res["stages"]), "time_s": time.time() - t1, "r_b3b": ncc(syn_b, w["seis"]),
|
||
"r_b3c": ncc(syn_c, w["seis"]),
|
||
"b3c_vs_b3b_rms_ms": float(np.sqrt(np.nanmean((invert_warps(t_b3c[None], tau_fine, t_main)[0]
|
||
- tau_b3b) ** 2))),
|
||
"r_best_tie_calibrated": float(qc.get((w["name"], "calibrated"), np.nan))}
|
||
post = [("anchor", np.nan, Z0s[i])] + [(nm, g, res["Z"][float(g)]) for nm, g in cks.items()]
|
||
for nm, g, Z in post:
|
||
U = T.u(Z)
|
||
tau_t = invert_warps(grid.t_of_tau(U[:, 0], U[:, 1:], tau=tau_fine), tau_fine, t_main)
|
||
q05, q95 = np.nanquantile(tau_t, [0.05, 0.95], axis=0)
|
||
mean_tau = np.nanmean(tau_t, 0)
|
||
syn_m = T.synth(U.mean(0)[None])[0]
|
||
rows.append(key | info | {"posterior": nm, "gamma": g,
|
||
"logZ": res["logZ"].get(float(g), np.nan) if nm != "anchor" else np.nan,
|
||
"sigma_post_ms": float(np.mean(q95 - q05)) / 3.29,
|
||
"sd_post_ms": float(np.mean(np.nanstd(tau_t, 0))),
|
||
"shift_vs_b3b_rms_ms": float(np.sqrt(np.nanmean((mean_tau - tau_b3b) ** 2))),
|
||
"r_post": ncc(syn_m, w["seis"]), "kappa_post": residual_kappa(syn_m, w["seis"])})
|
||
saved[f"{setting}/k{k}/{w['name']}/{nm}/mean_tau"] = mean_tau.astype(np.float32)
|
||
if nm == "g_acf":
|
||
saved[f"{setting}/k{k}/{w['name']}/{nm}/U"] = U.astype(np.float32)
|
||
print(f"{setting} k={k}: φ0 {phase0:+.0f}°, φ_R {phase_r:+.1f}° ({time.time() - t0:.0f} s)", flush=True)
|
||
saved["t_main"] = t_main
|
||
np.savez_compressed(out_dir / "particles.npz", **saved)
|
||
(out_dir / "phase.json").write_text(json.dumps(phases, indent=1, default=float))
|
||
df = pd.DataFrame(rows)
|
||
df.to_csv(out_dir / "wells.csv", index=False)
|
||
cols = ["sigma_post_ms", "sd_post_ms", "r_post", "kappa_post", "kappa0", "shift_vs_b3b_rms_ms", "r_b3c",
|
||
"r_best_tie_calibrated"]
|
||
print(df.groupby(["setting", "posterior", "well"])[cols].mean().round(3).to_string())
|
||
|
||
|
||
if __name__ == "__main__":
|
||
os.environ.setdefault("PYTHONHASHSEED", "0")
|
||
main()
|