"""Training-set-only P4 registration and label banks. No held-out well is passed to this module. Follows ml_porosity.f3.registration.register_set with three recorded deviations (protocol_volve): - Likelihood window: AI exists only over the logged interval (45–151 of the 301 ext samples), so the tie likelihood of a well (phase grid, SMC, γ) is evaluated on `lik`, the ext samples from the first to the last finite calibrated AI sample of that well; outside it the constant AI extension gives a zero synthetic that would only fit noise. B3c/B3c-R keep the F3 full-window local shifts: windows without synthetic energy have r = NaN and are dropped by r_min. - Particle validity: labels cover 16–37 of the 126 main samples, so a particle only has to invert over the main window (F3 also required full label support there). - Member support: every member keeps the samples where its own warp places the label run (NaN elsewhere), so no label is extrapolated and the run is not trimmed to the intersection of all members (which loses both ends of a 16-sample run under the posterior spread). A member with fewer than `min_label_samples` is an error. The intersection over members and methods is recorded as a diagnostic only. """ from __future__ import annotations import gc import time from types import SimpleNamespace import numpy as np from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet from ml_porosity.registration.labels import antialias, invert_warps, labels_for_warps from ml_porosity.registration.pipeline import PHASES, fit_cell_hyper from ml_porosity.registration.sampler import sample_warps from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, profile_loglik, synth_for_warps from ml_porosity.registration.ties import tie_b3b, tie_b3c from ml_porosity.volve.data import VolveData from ml_porosity.volve.losses import label_segments, segment_lambda METHODS = ("B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa") def valid_warps(data: VolveData, warps: np.ndarray) -> np.ndarray: """Warps whose inverse τ(t) exists over the whole main window.""" return np.isfinite(invert_warps(warps, data.tau, data.t_main)).all(axis=1) def window_phase_loglik(syn0: np.ndarray, seis: np.ndarray, lik: np.ndarray, phases=PHASES) -> np.ndarray: """(P, S) as tie_likelihood.phase_loglik, with the phase rotated on the full ext synthetic and the profile likelihood taken over the samples `lik` only.""" syn0 = np.atleast_2d(syn0) return np.stack([profile_loglik(rotate_phase(syn0, p)[:, lik], seis[lik]) for p in phases]) def label_fn(data: VolveData, obs: dict, y_filtered: np.ndarray): """t(τ) warps (S, n_tau) → labels (S, L) on the main window, NaN where the label is not supported.""" valid = obs["label_valid"][data.label].astype(float) def lab(warps): warps = np.atleast_2d(warps) tau_at = invert_warps(warps, data.tau, data.t_main) support = np.interp(np.nan_to_num(tau_at, nan=data.tau[0] - 1.0), data.tau, valid, left=0, right=0) out = labels_for_warps(data.tau, y_filtered, warps, data.t_main) return np.where(np.isfinite(tau_at) & (support >= 1 - 1e-9), out, np.nan) return lab def register_set(data: VolveData, names: tuple[str, ...], p: dict, device: str, sigma_a: float = 7.0) -> tuple[dict, dict]: import torch from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior started = time.perf_counter() names = tuple(sorted(names)) r = p["registration"] | {"sigma_a_ms": sigma_a} label = data.label obs = data.training_observations(names) if tuple(o["name"] for o in obs) != names: raise RuntimeError("Unexpected training-well payload") h, hinfo = fit_cell_hyper(SimpleNamespace(grid=data.grid), obs, r, r["smc_seed"]) f = r["fine_dt_ms"] fac = int(round(data.dt / f)) w0 = statistical_wavelet(np.stack([o["seis"] for o in obs]), data.dt, r["wavelet_ms"]) B = phase_basis(w0, fac) cover = (data.t_main[0], data.t_main[-1]) samples, Ts, Zs, LL, anchor_valid = [], [], [], [], [] for i, o in enumerate(obs): smp = sample_warps(data.grid, h, o["tau_k"], o["t_k"], r["particles"], r["g_max"], np.random.default_rng([r["smc_seed"], i, 13])) samples.append(smp) tg = data.grid.t_of_tau(smp["b"][:r["S"]], smp["g"][:r["S"]], data.tau) valid = valid_warps(data, tg) if not valid.any(): raise ValueError(f"No anchor sample covers the main window: {o['name']}") anchor_valid.append(valid) syn = synth_for_warps(data.tau, o["ai_log"], tg, data.t_fine, data.t, fine_wavelet(w0, fac)) LL.append(window_phase_loglik(syn, o["seis"], o["lik"])) phase0 = float(PHASES[fit_phase(LL, anchor_valid, PHASES)]) for o, smp in zip(obs, samples): T = TiePosteriorTorch(TiePosterior(data.grid, h, o["tau_k"], o["t_k"], r["g_max"], data.tau, o["ai_log"], data.t_fine, data.t[o["lik"]], phase_wavelet(B, phase0), o["seis"][o["lik"]], cover), device) Zs.append(T.z(smp["u"])) Ts.append(T) phase_r, ph = smc_fit_phase(Ts, Zs, B, phase0, [r["smc_seed"], 19], step=r["phase_step"], half_width=r["phase_half_width"], max_extra=r["phase_max_extra"], n_moves=r["smc_moves"]) wf = phase_wavelet(B, phase_r) post, diag = [], [] for i, (o, T0, z0) in enumerate(zip(obs, Ts, Zs)): T = T0.with_wavelet(wf) gamma = gamma_acf(T, z0, T.parts(z0)[1]) res = smc_tie_posterior(T, z0, [gamma], np.random.default_rng([r["smc_seed"], i, 17]), n_moves=r["smc_moves"]) u = T.u(res["Z"][gamma]) tg = data.grid.t_of_tau(u[:, 0], u[:, 1:], data.tau) valid = valid_warps(data, tg) if valid.sum() < min(256, r["particles"]): raise ValueError(f"Insufficient posterior particles covering the main window: {o['name']}, " f"{valid.sum()} valid") post.append(tg[valid]) diag.append({"well": o["name"], "gamma": gamma, "n_stages": len(res["stages"]), "valid_particles": int(valid.sum()), "particles": len(valid), "n_anchors": len(o["tau_k"]), "lik_samples": int(o["lik"].sum()), "lik_ms": [float(data.t[o["lik"]][0]), float(data.t[o["lik"]][-1])]}) bundle = {"wells": np.asarray(names), "phase0": np.asarray(phase0), "phase_R": np.asarray(phase_r)} banks = {m: [] for m in METHODS} logpi = [] filtered = [antialias(o["labels"][label], f, data.dt) for o in obs] normsel = (data.tau >= data.t_main[0]) & (data.tau <= data.t_main[-1]) vals = np.concatenate([y[normsel & o["label_valid"][label]] for o, y in zip(obs, filtered)]) bundle[f"{label}/norm"] = np.array([vals.mean(), max(vals.std(), 1e-8)]) for i, (o, tg, y) in enumerate(zip(obs, post, filtered)): lab = label_fn(data, o, y) b3b = tie_b3b(o["tau_k"], o["t_k"], data.tau) ties = {"B3b": b3b, "B3d-Sa": tg.mean(axis=0)} for name, phase in (("B3c", phase0), ("B3c-R", phase_r)): syn = synth_for_warps(data.tau, o["ai_log"], b3b, data.t_fine, data.t, fine_wavelet(rotate_phase(w0, phase), fac))[0] ties[name] = tie_b3c(b3b, data.tau, syn, o["seis"], data.t, data.dt) per = {m: lab(t) for m, t in ties.items()} sub = np.random.default_rng([r["smc_seed"], i, 29]).choice(len(tg), r["S"], replace=False) per["M2-Sa"] = lab(tg[sub]) counts = {m: np.isfinite(a).sum(axis=1) for m, a in per.items()} short = {m: int(c.min()) for m, c in counts.items() if c.min() < p["data"]["min_label_samples"]} if short: raise ValueError(f"Label support too short: {o['name']}, fewest samples per member {short}") for m in METHODS: banks[m].append(per[m]) common = np.logical_and.reduce([np.isfinite(a).all(axis=0) for a in per.values()]) union = np.isfinite(per["M2-Sa"]).any(axis=0) logpi.append(np.full(r["S"], -np.log(r["S"]))) tau_at = invert_warps(tg, data.tau, data.t_main) q = np.diff(np.quantile(tau_at, [0.05, 0.95], axis=0), axis=0)[0] / 3.29 diag[i] |= {"sigma_post_ms": float(np.mean(q)), "sigma_post_label_ms": float(np.mean(q[union])), "common_samples": int(common.sum()), "label_samples": {m: int(c.min()) for m, c in counts.items()}, "label_samples_max": {m: int(c.max()) for m, c in counts.items()}} for m in METHODS: bundle[f"{label}/{m}"] = np.stack(banks[m]).astype(np.float32) bundle[f"{label}/M2-Sa/logpi"] = np.stack(logpi).astype(np.float32) segments = [s for y in bundle[f"{label}/B3b"][:, 0] for s in label_segments(y) if s.size >= 2] lam, tau_c = segment_lambda(segments, p["metrics"]["f_c_hz"], data.dt) bundle[f"{label}/lambda"], bundle[f"{label}/tau_c"] = np.asarray(lam), np.asarray(tau_c) for o, tg in zip(obs, post): bundle[f"posterior/{o['name']}/tau_at_main"] = invert_warps(tg, data.tau, data.t_main) meta = {"training_wells": list(names), "sigma_a_ms": sigma_a, "phase0": phase0, "phase_R": phase_r, "phase_info": ph, "hyper": h.as_dict(), "hyper_info": hinfo, "diagnostics": diag, "lambda": lam, "tau_c": tau_c, "wall_seconds": time.perf_counter() - started} del Ts, Zs, T, T0 gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() return bundle, meta