"""Bank losses with label masks (P4: Volve labels cover 16–37 of the 126 main-window samples). Member s of the bank of training well b places the same label run at its own times, so it has its own support mask M_bs (L); a (B, L) mask is shared by all members. For window j, n_bjs = Σ_{i ∈ j} M_bsi and n̄_bj = mean_s n_bjs: ℓ_bjs = (n̄_bj / n_bjs) Σ_{i ∈ j} M_bsi log N(y_bs,i; μ_i, σ_i²) (members compared at a common count) RML: L_b = −Σ_j (1/λ) log Σ_s π_bs exp(λ ℓ_bjs) / Σ_j n̄_bj hard-min: L_b = −Σ_j max_s ℓ_bjs / Σ_j n̄_bj and the loss is the mean of L_b over wells. A window where some member has no valid sample contributes nothing. With a shared mask the count factor is 1; with every sample valid the loss equals losses.rml.bank_loss. """ from __future__ import annotations import numpy as np import torch from scipy import signal from ml_porosity.losses.rml import LOG_2PI, gather_windows def masked_window_loglik(mu, sigma, Y, mask, starts, win: int) -> tuple[torch.Tensor, torch.Tensor]: """mu, sigma (B, L); Y (B, S, L), any value where the mask is False; mask (B, L) or (B, S, L) → summed ℓ (B, J, S) and valid counts n (B, J, S).""" if mask.dim() == 2: mask = mask[:, None, :].expand(Y.shape) if mask.shape != Y.shape: raise ValueError("mask must be (B, L) or match the bank (B, S, L)") y = torch.where(mask, Y, torch.zeros((), dtype=Y.dtype, device=Y.device)) m = gather_windows(mu, starts, win)[:, :, None, :] s = gather_windows(sigma, starts, win)[:, :, None, :] w = gather_windows(mask.to(mu.dtype), starts, win) term = -torch.log(s) - 0.5 * ((gather_windows(y, starts, win) - m) / s) ** 2 - 0.5 * LOG_2PI return (term * w).sum(-1), w.sum(-1) def masked_bank_loss(mu, sigma, Y, logpi, mask, starts, win: int, lam: float | None) -> torch.Tensor: """lam = None → hard-min (max ℓ); otherwise RML with power λ. Every well needs a window in which every member has a valid sample.""" ll, n = masked_window_loglik(mu, sigma, Y, mask, starts, win) use = (n > 0).all(-1) nbar = n.mean(-1) ll = torch.where(use[..., None], ll * nbar[..., None] / n.clamp(min=1), torch.zeros((), dtype=ll.dtype, device=ll.device)) total = (nbar * use).sum(1) if not bool((total > 0).all()): raise ValueError("a training well has no labelled sample in any window") v = ll.max(-1).values if lam is None else torch.logsumexp(logpi[:, None, :] + lam * ll, dim=-1) / lam v = torch.where(use, v, torch.zeros((), dtype=v.dtype, device=v.device)) return -(v.sum(1) / total).mean() def highpass_segment(y: np.ndarray, f_c_hz: float, dt_ms: float = 4.0, order: int = 4) -> np.ndarray: """y minus its zero-phase Butterworth low band below f_c, as eval.metrics.split_bands (identical for ≥ 16 samples at order 4); shorter segments use the longest even padding scipy accepts.""" y = np.asarray(y, dtype=float) sos = signal.butter(order, f_c_hz, fs=1000.0 / dt_ms, output="sos") pad = min(3 * (2 * len(sos) + 1), y.size - 1) return y - signal.sosfiltfilt(sos, y, padtype="even", padlen=pad) def segment_lambda(segments: list[np.ndarray], f_c_hz: float = 6.0, dt_ms: float = 4.0, max_lag: int = 32) -> tuple[float, float]: """losses.rml.effective_lambda for label segments of any length ≥ 2: λ = 1/τ_c, τ_c = 1 + 2 Σ_k ρ(k)², with ρ the ACF of the high-passed segments pooled as lagged products (a lag longer than a segment adds nothing). Σ runs up to the first lag with ρ ≤ 0. Equals effective_lambda when every segment has more than max_lag samples.""" acc = np.zeros(max_lag + 1) for y in segments: y = np.asarray(y, dtype=float) if y.size < 2 or not np.isfinite(y).all(): raise ValueError("segments must be finite with at least two samples") hi = highpass_segment(y, f_c_hz, dt_ms) hi = hi - hi.mean() a = np.correlate(hi, hi, "full")[hi.size - 1: hi.size + max_lag] acc[: a.size] += 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 def finite_runs(y: np.ndarray) -> list[tuple[int, int]]: """[start, stop) of the maximal runs of finite samples of a series (NaN separates runs).""" ok = np.isfinite(np.asarray(y, dtype=float)) edges = np.flatnonzero(np.diff(np.r_[0, ok.astype(int), 0])) return [(int(a), int(b)) for a, b in zip(edges[::2], edges[1::2])] def label_segments(y: np.ndarray) -> list[np.ndarray]: """Maximal runs of finite samples of a series.""" y = np.asarray(y, dtype=float) return [y[a:b] for a, b in finite_runs(y)]