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>
This commit is contained in:
202
scripts/14_diag_posterior.py
Normal file
202
scripts/14_diag_posterior.py
Normal file
@@ -0,0 +1,202 @@
|
||||
"""Post-G-B diagnostics, steps 1–2 (plan §9): seismic-conditioned warp posterior via SMC tempering.
|
||||
|
||||
python scripts/14_diag_posterior.py --rids 900 901 --c 0 1 2 --n 4 16 --seeds 0 --workers 4 --device cuda:1
|
||||
|
||||
Dev realizations only (realizations of the protocol_p2 main grid are refused). Each job (rid, c, N, seed): register
|
||||
as in protocol_p2 (pipeline.register: MAP-II hyperparameters, statistical wavelet + constant phase, old M1/M2, B3b–d),
|
||||
re-estimate the constant phase by SMC over the training wells (smc.smc_fit_phase), then run SMC per well from P
|
||||
anchor-posterior samples through the γ milestones: γ of the old M2 (g_old), γ = 1/κ at the best anchor sample (g_acf)
|
||||
and γ = 1 (g_one). Four wavelets: "est" (statistical spectrum, protocol_p2 phase), "estR" (statistical spectrum,
|
||||
re-estimated phase — the proposed method), "est0" (statistical spectrum, zero phase = true D2 phase) and "true" (true
|
||||
D2 wavelet); est0 and true serve only as upper bounds, not as methods. B3c is recomputed for each wavelet. Writes warp
|
||||
errors (RMSE of τ(t) over the main window — for SMC, the error of the posterior-mean warp, i.e. B3d on the new
|
||||
posterior — 90% coverage and width), the log-likelihood at the true warp, log Z_w over phase (smc_fit_phase) and the
|
||||
SMC samples (est, estR) to outputs/p2/diag/posterior/. --device cpu runs smc.py (numpy); any other device runs
|
||||
smc_torch.py (same algorithm and random streams; matches the numpy version up to rounding error).
|
||||
|
||||
Stress tests (dev only; defaults = protocol_p2): --snr and --anchor-density change the observed data; --sigma-a-reg
|
||||
changes the σ_a used for registration (data are still generated with the σ_a of d2_synth.yaml); --smc-seeds k reruns
|
||||
the anchor sampling, phase and SMC with random stream k (registration seed kept) to measure run-to-run stability;
|
||||
--wavelets drops some of the upper-bound wavelets. Each setting should write to its own --out-dir.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
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)
|
||||
|
||||
OLD = ["B3b", "B3c", "B3d", "M1", "M2"]
|
||||
SAVE = {("est", "g_acf"), ("estR", "g_acf"), ("estR", "g_one")}
|
||||
WAVELETS = ("est", "estR", "est0", "true")
|
||||
|
||||
|
||||
def job_tag(rid, c, N, seed, smc_seed=None) -> str:
|
||||
return f"r{rid}_c{c:g}_n{N}_s{seed}" + ("" if smc_seed is None else f"_k{smc_seed}")
|
||||
|
||||
|
||||
def run_job(job) -> pd.DataFrame:
|
||||
rid, c, N, seed, n_part, P, out_dir, device, mem_gb, st = job
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.registration.pipeline import register
|
||||
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 synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
|
||||
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
|
||||
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
|
||||
obs = [R.observe(w, c, st["snr_db"], cfg["anchors"]["sigma_a_ms"], st["anchor_density"]) for w in R.pool[:N]]
|
||||
reg = run_d2.reg_settings(P)
|
||||
if st["sigma_a_reg"] is not None:
|
||||
reg["sigma_a_ms"] = st["sigma_a_reg"]
|
||||
k = seed if st["smc_seed"] is None else st["smc_seed"] # random stream for anchor samples, phase and SMC
|
||||
mm = (R.t_ext >= R.t_main[0]) & (R.t_ext <= R.t_main[-1])
|
||||
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
|
||||
if 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(device)
|
||||
if dev.type == "cuda": # shared GPU: exceeding the cap makes this job OOM rather than encroach on other processes
|
||||
total = torch.cuda.get_device_properties(dev).total_memory
|
||||
torch.cuda.set_per_process_memory_fraction(min(1.0, mem_gb * 2**30 / total), dev)
|
||||
wrap = lambda T: TiePosteriorTorch(T, device)
|
||||
|
||||
out = register(R, obs, reg, seed)
|
||||
h = WarpHyper(**out["hyper"])
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
B = phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), int(round(R.dt / cfg["fine_dt_ms"])))
|
||||
Ts, Z0s = [], []
|
||||
for i, o in enumerate(obs):
|
||||
smp = sample_warps(R.grid, h, o["tau_k"], o["t_k"], n_part, reg["g_max"], np.random.default_rng([k, i, 13]))
|
||||
Ts.append(wrap(TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine,
|
||||
R.t_ext, phase_wavelet(B, out["phase"]), seis[i], (R.t_main[0], R.t_main[-1]))))
|
||||
Z0s.append(Ts[-1].z(smp["u"]))
|
||||
t0 = time.time()
|
||||
phase_r, ph = smc_fit_phase(Ts, Z0s, B, out["phase"], [k, 19])
|
||||
key = dict(rid=rid, c=c, n_train=N, seed=seed, smc_seed=k, particles=n_part, snr_db=st["snr_db"],
|
||||
anchor_density=st["anchor_density"], sigma_a_reg=reg["sigma_a_ms"], phase=out["phase"], phase_R=phase_r,
|
||||
phase_n=len(ph["phases"]), phase_edge=ph["edge"], phase_time_s=time.time() - t0)
|
||||
wavelets = {"est": phase_wavelet(B, out["phase"]), "estR": phase_wavelet(B, phase_r),
|
||||
"est0": phase_wavelet(B, 0.0), "true": R.w_fine}
|
||||
wavelets = {wn: wf for wn, wf in wavelets.items() if wn in st["wavelets"]}
|
||||
rows, saved = [], {}
|
||||
for i, o in enumerate(obs):
|
||||
d = out["diag"][i]
|
||||
for m in OLD:
|
||||
e = {k.removeprefix(f"{m}_"): v for k, v in d.items() if k.startswith(f"{m}_warp")}
|
||||
rows.append(key | {"well": o["name"], "method": m, "wavelet": "est",
|
||||
"gamma": d["gamma"] if m == "M2" else np.nan} | e)
|
||||
ut = np.concatenate([[o["b"]], o["g"]])[None]
|
||||
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
|
||||
for wn, wf in wavelets.items():
|
||||
if wn != "est":
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wf)[0]
|
||||
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
rows.append(key | {"well": o["name"], "method": "B3c", "wavelet": wn}
|
||||
| warp_errors(t3c[None], R.tau_fine, o["t_of_tau_true"], R.t_main))
|
||||
T = Ts[i].with_wavelet(wf)
|
||||
_, l0 = T.parts(Z0s[i])
|
||||
cks = {"g_old": d["gamma"], "g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
|
||||
t0, T.n_eval = time.time(), 0
|
||||
res = smc_tie_posterior(T, Z0s[i], cks.values(), np.random.default_rng([k, i, 17]))
|
||||
sg = pd.DataFrame(res["stages"])
|
||||
info = {"well": o["name"], "wavelet": wn, "kappa0": 1.0 / cks["g_acf"], "ll_true": float(T.loglik(ut)[0]),
|
||||
"ll_anchor_max": float(l0.max()), "n_stages": len(sg), "n_eval": T.n_eval,
|
||||
"time_s": time.time() - t0, "shrink_mean": float(sg["shrink"].mean()),
|
||||
"jump_z_min": float(sg["jump_z"].min()), "r_true": ncc(T.synth(ut)[0], seis[i])}
|
||||
for name, gk in cks.items():
|
||||
U = T.u(res["Z"][float(gk)])
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
|
||||
e = warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)
|
||||
syn_m = T.synth(U.mean(0)[None])[0]
|
||||
rows.append(key | info | {"method": f"SMC_{name}", "gamma": gk, "logZ": res["logZ"][float(gk)],
|
||||
"ll_max": float(res["ll"][float(gk)].max()),
|
||||
"ll_mean": float(res["ll"][float(gk)].mean()),
|
||||
"kappa_post": residual_kappa(syn_m, seis[i]), "r_post": ncc(syn_m, seis[i])} | e)
|
||||
if (wn, name) in SAVE:
|
||||
saved[f"{o['name']}/{wn}/{name}"] = U.astype(np.float32)
|
||||
tag = job_tag(rid, c, N, seed, st["smc_seed"])
|
||||
(out_dir / f"{tag}_phase.json").write_text(json.dumps({"phase0": out["phase"], "phase_R": phase_r} | ph))
|
||||
np.savez_compressed(out_dir / f"{tag}_particles.npz", **saved)
|
||||
df = pd.DataFrame(rows)
|
||||
df.to_csv(out_dir / f"{tag}.csv", index=False)
|
||||
return df
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=[900, 901])
|
||||
ap.add_argument("--c", type=float, nargs="+", default=[1.0])
|
||||
ap.add_argument("--n", type=int, nargs="+", default=[16])
|
||||
ap.add_argument("--seeds", type=int, nargs="+", default=[0])
|
||||
ap.add_argument("--particles", type=int, default=256)
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
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, help="per-worker GPU memory allocation cap (GiB)")
|
||||
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/p2/diag/posterior")
|
||||
ap.add_argument("--snr", type=float, default=None, help="seismic SNR (dB); default: grid.snr_db of protocol_p2")
|
||||
ap.add_argument("--anchor-density", default=None, choices=["full", "half", "topbottom"])
|
||||
ap.add_argument("--sigma-a-reg", type=float, default=None, help="σ_a (ms) used for registration; default as in protocol_p2")
|
||||
ap.add_argument("--smc-seeds", type=int, nargs="+", default=None,
|
||||
help="each k: an independent SMC run (random stream k); files get the suffix _k<k>")
|
||||
ap.add_argument("--wavelets", nargs="+", default=list(WAVELETS), choices=WAVELETS)
|
||||
args = ap.parse_args()
|
||||
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "2"}.items():
|
||||
os.environ.setdefault(k, v)
|
||||
|
||||
P = run_d2.load_protocol(check=True)
|
||||
bad = sorted(set(args.rids) & set(P["grid"]["realizations"]))
|
||||
if bad:
|
||||
raise SystemExit(f"realizations {bad} belong to the protocol_p2 main grid: diagnostics use dev realizations only")
|
||||
out_dir = args.out_dir or outputs_dir() / "p2" / "diag" / "posterior"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
G = P["grid"]
|
||||
st = {"snr_db": G["snr_db"] if args.snr is None else args.snr,
|
||||
"anchor_density": args.anchor_density or G["anchor_density"], "sigma_a_reg": args.sigma_a_reg,
|
||||
"wavelets": args.wavelets}
|
||||
jobs = [(r, c, n, s, args.particles, P, out_dir, args.device, args.gpu_mem_gb, st | {"smc_seed": k})
|
||||
for r in args.rids for c in args.c for n in args.n for s in args.seeds for k in (args.smc_seeds or [None])
|
||||
if not (out_dir / f"{job_tag(r, c, n, s, k)}.csv").exists()]
|
||||
jobs.sort(key=lambda j: -j[2])
|
||||
print(f"{len(jobs)} jobs, {args.workers} workers, device {args.device}", flush=True)
|
||||
t0 = time.time()
|
||||
if jobs:
|
||||
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
|
||||
futs = {ex.submit(run_job, j): j[:4] + (j[-1]["smc_seed"],) for j in jobs}
|
||||
for i, f in enumerate(as_completed(futs), 1):
|
||||
f.result()
|
||||
print(f"[{i}/{len(jobs)}] {futs[f]} done ({time.time() - t0:.0f} s)", flush=True)
|
||||
df = pd.concat([pd.read_csv(f) for f in sorted(out_dir.glob("r*_s*.csv"))], ignore_index=True)
|
||||
df.to_csv(out_dir / "warp.csv", index=False)
|
||||
print(df.groupby(["rid", "c", "n_train"])[["phase", "phase_R", "phase_n", "phase_edge"]].first().to_string())
|
||||
cols = ["warp_rmse_ms", "warp_cov90", "warp_width90_ms", "gamma"]
|
||||
print(df.groupby(["c", "n_train", "wavelet", "method"])[cols].mean().round(3).to_string())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("PYTHONHASHSEED", "0")
|
||||
main()
|
||||
Reference in New Issue
Block a user