"""Sub-window losses on the "label bank" (plan §4.4–4.5). Each training well w has S candidate labels Y_w (S, L) and log-weights log π_w (S). For each sub-window j: ℓ_wjs = Σ_{i ∈ j} log N(y_ws,i; μ_i, σ_i²) RML: −(1/(λ n_j)) · log Σ_s π_ws exp(λ ℓ_wjs) hard-min: −(1/n_j) · max_s ℓ_wjs (λ → ∞, uniform π; B4a) S = 1 gives the mean Gaussian NLL (B3, point tie). A bank of ±K-sample shifts of a single label with uniform π gives soft-min/hard-min over bulk shifts (B4b/B4a). The same windowing mechanism is used for all methods. """ from __future__ import annotations import math import numpy as np import torch LOG_2PI = math.log(2 * math.pi) def window_starts(n_wells: int, L: int, win: int, J: int, margin: int, gen: torch.Generator, device) -> torch.Tensor: hi = L - win - margin return torch.randint(margin, hi + 1, (n_wells, J), generator=gen, device="cpu").to(device) def gather_windows(x: torch.Tensor, starts: torch.Tensor, win: int) -> torch.Tensor: """x (B, ..., L), starts (B, J) → (B, J, ..., win).""" idx = starts[..., None] + torch.arange(win, device=x.device) # (B, J, win) B = x.shape[0] mid = x.shape[1:-1] xe = x.unsqueeze(1).expand(B, idx.shape[1], *mid, x.shape[-1]) ie = idx.view(B, idx.shape[1], *([1] * len(mid)), win).expand(B, idx.shape[1], *mid, win) return torch.gather(xe, -1, ie) def window_loglik(mu, sigma, Y, starts, win): """mu, sigma (B, L); Y (B, S, L) → ℓ (B, J, S).""" m = gather_windows(mu, starts, win)[:, :, None, :] s = gather_windows(sigma, starts, win)[:, :, None, :] y = gather_windows(Y, starts, win) return (-torch.log(s) - 0.5 * ((y - m) / s) ** 2 - 0.5 * LOG_2PI).sum(-1) def bank_loss(mu, sigma, Y, logpi, starts, win: int, lam: float | None): """lam = None → hard-min (max ℓ); otherwise RML with power λ.""" ll = window_loglik(mu, sigma, Y, starts, win) if lam is None: return -(ll.max(-1).values / win).mean() v = torch.logsumexp(logpi[:, None, :] + lam * ll, dim=-1) return -(v / (lam * win)).mean() def mse_bank_loss(mu, Y, starts, win: int): """Mean MSE over the labels of the bank (H1: the optimum is the label blurred by p_δ).""" m = gather_windows(mu, starts, win)[:, :, None, :] y = gather_windows(Y, starts, win) return ((y - m) ** 2).mean() def shift_bank(y: np.ndarray, max_shift: int) -> np.ndarray: """(2K+1, L): y shifted by k samples (label y_{i+k}), NaN outside the boundaries.""" L = len(y) out = np.full((2 * max_shift + 1, L), np.nan) for n, k in enumerate(range(-max_shift, max_shift + 1)): lo, hi = max(0, -k), min(L, L - k) out[n, lo:hi] = y[lo + k: hi + k] return out def effective_lambda(labels: list[np.ndarray], f_c_hz: float = 6.0, dt_ms: float = 4.0, max_lag: int = 32) -> tuple[float, float]: """λ = 1/τ_c with τ_c = 1 + 2 Σ_k ρ(k)², where ρ is the pooled ACF of the training labels high-pass filtered above f_c (a proxy for the residual in the seismic band). Σ runs up to the first lag with ρ ≤ 0 (at most max_lag). Returns (λ, τ_c).""" from ml_porosity.eval.metrics import split_bands acc = np.zeros(max_lag + 1) for y in labels: hi = split_bands(np.asarray(y, dtype=float), f_c_hz, dt_ms)[1] hi = hi - hi.mean() a = np.correlate(hi, hi, "full")[len(hi) - 1: len(hi) + max_lag] acc += a rho = acc / acc[0] k = np.argmax(rho[1:] <= 0) + 1 if np.any(rho[1:] <= 0) else max_lag + 1 tau_c = 1.0 + 2.0 * float(np.sum(rho[1:k] ** 2)) return 1.0 / tau_c, tau_c