Complete P4 Volve; pivot the manuscript to theory + benchmark

P4 (Volve field case). Add the deviated-well and Volve well builders
(ml_porosity/data/deviated.py, volve_wells.py), the ml_porosity/volve/
pipeline, scripts 23-25, the run_p4 drivers and tests. The protocol
configs/protocol_volve.yaml was locked at 2026-10-29T01:17:42Z before the
run (.sha256, .lock.json) and is committed here after the run. Gate G-D
failed: M2-Sa beats the selected B3 at 2/6 wells (lowo) and 3/6 (slot),
coverage90 is about 0.47, and no method has blind-well skill (R2 < 0).
A post hoc constant at the training-well mean beats every network, so
G-D had no power. The dropped P4x exploratory run is kept as a record
only (exploratory/, docs/research/p4-exploratory.md).

Applicability and Teapot Dome (exploratory, pre-declared). Scripts 26-29
and docs/research/applicability-*.md: F3 and Volve fail C1 and pass C2;
T3 power needs 5-18 blind wells with an exact reference; Teapot T0 and
pilot P-a failed, so Teapot is stopped. Raw Teapot data stay gitignored.

Manuscript (Pivot 1, level A). Reframe paper/ as a theory and synthetic
benchmark paper: Propositions 3-6, Corollaries 3-4, T4 coverage
(script 30) and the post hoc H2b bound check (script 31), with F3/Volve
moved to Appendix B. Correct two earlier claims: the Berkson and
classical bounds differ by 1.5-4.6x at the f^4-weighted band, and the
bank gain exceeds the registered classical bound (7/8 wide cells at
N = 16) but only 3/8 under the post hoc Berkson bound.

Docs. Sync plan, AGENTS.md, README, report.html, theory and technical
overview. The length pass for the venue is dropped by the user
(plan section 12 item 25); the length risk stays recorded as R9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 12:18:22 +00:00
parent 7da6b077b6
commit 0cfe202a8b
61 changed files with 7162 additions and 881 deletions

View File

@@ -0,0 +1,93 @@
"""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)]