"""SMC tie posterior of one cell: the computation of scripts/14_diag_posterior.py run_job restricted to the arm protocol_p2r used (statistical wavelet with the re-estimated phase, "estR"), with the same random streams (anchor samples [k, i, 13], phase fit [k, 19], SMC [k, i, 17]) and the same γ checkpoints (g_old, g_acf, g_one), so that the default generator reproduces the protocol_p2r particles. Only the γ = 1/κ (g_acf) particles are stored. """ from __future__ import annotations import json import time from pathlib import Path import numpy as np import pandas as pd OLD = ["B3b", "B3c", "B3d", "M1", "M2"] CHECKPOINTS = ("g_old", "g_acf", "g_one") def posterior_cell(R, inp, obs: list[dict], c: float, N: int, regime: dict, reg_seed: int, smc_seed: int, particles: int, device: str, mem_gb: float, paths: dict[str, Path], save=("estR/g_acf",), checkpoints=CHECKPOINTS, extra_meta: dict | None = None, phase_kw: dict | None = None) -> pd.DataFrame: 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 reg, cfg = dict(inp.reg), inp.cfg k = smc_seed 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 others 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) t_all = time.time() out = register(R, obs, reg, 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"], particles, 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], **(phase_kw or {})) key = dict(rid=R.rid, c=c, n_train=N, seed=reg_seed, smc_seed=k, particles=particles, snr_db=regime["snr_db"], anchor_density=regime["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 = {"estR": phase_wavelet(B, phase_r)} rows, saved = [], {} for i, o in enumerate(obs): d = out["diag"][i] for m in OLD: e = {kk.removeprefix(f"{m}_"): v for kk, v in d.items() if kk.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(): 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_all = {"g_old": d["gamma"], "g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0} cks = {n: cks_all[n] for n in checkpoints} 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_all["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 f"{wn}/{name}" in save: saved[f"{o['name']}/{wn}/{name}"] = U.astype(np.float32) paths["phase"].parent.mkdir(parents=True, exist_ok=True) paths["phase"].write_text(json.dumps({"phase0": out["phase"], "phase_R": phase_r} | ph)) tmp = paths["particles"].with_suffix(".tmp.npz") np.savez_compressed(tmp, **saved) tmp.replace(paths["particles"]) df = pd.DataFrame(rows) df.to_csv(paths["csv"], index=False) meta = {"wall_seconds": time.time() - t_all, "device": device, "particles": particles, "phase0": out["phase"], "phase_R": phase_r, "misspec_active": R.misspec_active, "monotone_repairs": R.misspec_info["monotone_repairs"], "hyper": out["hyper"], "lam": out["lam"], "tau_c": out["tau_c"], "checkpoints": list(checkpoints), "saved": sorted(saved)} | (extra_meta or {}) return df, meta