- 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>
88 lines
3.6 KiB
Python
88 lines
3.6 KiB
Python
"""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
|