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>
479 lines
22 KiB
Python
479 lines
22 KiB
Python
"""P4 Volve pipeline: masked losses, public/private data views, nested blind folds, selection without test labels.
|
|
|
|
Everything here is synthetic (no Volve data, no PHIF metric of a real well).
|
|
"""
|
|
|
|
import copy
|
|
import itertools
|
|
import json
|
|
import zlib
|
|
|
|
import numpy as np
|
|
import pytest
|
|
import torch
|
|
|
|
from ml_porosity.data.volve_wells import blind_key, blind_training_wells
|
|
from ml_porosity.eval.metrics import split_bands
|
|
from ml_porosity.f3.protocol import digest, fingerprint
|
|
from ml_porosity.losses.rml import bank_loss, effective_lambda
|
|
from ml_porosity.volve.data import VolveData, visible
|
|
from ml_porosity.volve.folds import (inner_folds, nested_folds, outer_folds, prediction_targets, target_name,
|
|
training_sets)
|
|
from ml_porosity.volve.losses import (finite_runs, highpass_segment, label_segments, masked_bank_loss,
|
|
segment_lambda)
|
|
from ml_porosity.volve.protocol import load_protocol, source_config
|
|
from ml_porosity.volve.runner import check_arrays, job_path, nan_allowed, reg_path, reusable, save_npz
|
|
from ml_porosity.volve.training import method_spec, train_trajectory
|
|
|
|
P = load_protocol()
|
|
P4 = source_config(P)["p4"]
|
|
WELLS = list(P["data"]["wells"])
|
|
SCHEMES = list(P["split"]["schemes"])
|
|
T = np.arange(2000.0, 3201.0, 4.0)
|
|
MAIN = (T >= 2400) & (T <= 2900)
|
|
L = int(MAIN.sum())
|
|
|
|
|
|
def synthetic_arrays(seed: int = 0) -> dict[str, np.ndarray]:
|
|
"""Flat "<well>/<item>" arrays shaped like outputs/volve/volve_wells.npz (no real values)."""
|
|
rng = np.random.default_rng(seed)
|
|
a = {}
|
|
for n, w in enumerate(WELLS):
|
|
a |= {f"{w}/times_ms": T, f"{w}/main_mask": MAIN, f"{w}/kb_msl": np.array(54.9),
|
|
f"{w}/survey/md": np.linspace(0, 4000, 50), f"{w}/il": np.array(10230.0 + n),
|
|
f"{w}/xl": np.array(2300.0 + n), f"{w}/x": np.array(4.3e5), f"{w}/y": np.array(6.47e6),
|
|
f"{w}/log/md": np.linspace(3000, 3500, 200), f"{w}/log/DT": rng.normal(90, 5, 200),
|
|
f"{w}/anchors_md": np.array([3100.0, 3300.0]), f"{w}/anchors_twt_ms": np.array([2500.0, 2700.0]),
|
|
f"{w}/tdr/sonic/md": np.linspace(0, 4000, 40), f"{w}/support/md": np.array([3000.0, 3500.0]),
|
|
f"{w}/reference/seismic_patch": rng.normal(size=(9, T.size))}
|
|
for ref, start, length in (("calibrated", 130 + 4 * n, 16 + 3 * n), ("anchors", 132 + 4 * n, 12),
|
|
("sonic", 129 + 4 * n, 16 + 3 * n)):
|
|
y = np.full(T.size, np.nan)
|
|
y[start: start + length] = 0.2 + 0.03 * rng.standard_normal(length)
|
|
a[f"{w}/{ref}/PHIF"] = y
|
|
a[f"{w}/calibrated/AI"] = np.where(np.isfinite(a[f"{w}/calibrated/PHIF"]), 6e6, np.nan)
|
|
others = [v for v in WELLS if v != w]
|
|
for k in range(1, len(others) + 1):
|
|
for K in itertools.combinations(others, k):
|
|
a[f"{w}/blind/{blind_key(K)}/seismic_patch"] = rng.normal(size=(9, T.size))
|
|
for ref in ("NIVSP", "OPTIMIZED"):
|
|
a[f"F-11 T2/{ref}/PHIF"] = a["F-11 T2/calibrated/PHIF"].copy()
|
|
return a
|
|
|
|
|
|
ARRAYS = synthetic_arrays()
|
|
|
|
|
|
# ---------- masked losses ----------
|
|
|
|
|
|
def bank(B=3, S=5, seed=0):
|
|
g = torch.Generator().manual_seed(seed)
|
|
mu = torch.randn(B, L, generator=g, dtype=torch.float64, requires_grad=True)
|
|
sigma = (0.5 + torch.rand(B, L, generator=g, dtype=torch.float64)).requires_grad_(True)
|
|
Y = torch.randn(B, S, L, generator=g, dtype=torch.float64)
|
|
logpi = torch.log_softmax(torch.randn(B, S, generator=g, dtype=torch.float64), -1)
|
|
starts = torch.tensor(np.tile(np.arange(0, L - 64 + 1, 2), (B, 1)))
|
|
return mu, sigma, Y, logpi, starts
|
|
|
|
|
|
@pytest.mark.parametrize("lam", [None, 0.3, 1.0])
|
|
def test_masked_bank_loss_equals_the_f3_bank_loss_when_every_sample_is_labelled(lam):
|
|
mu, sigma, Y, logpi, starts = bank()
|
|
mask = torch.ones(mu.shape, dtype=torch.bool)
|
|
a = masked_bank_loss(mu, sigma, Y, logpi, mask, starts, 64, lam)
|
|
b = bank_loss(mu, sigma, Y, logpi, starts, 64, lam)
|
|
assert torch.allclose(a, b, rtol=1e-12, atol=1e-12)
|
|
|
|
|
|
def brute_force(mu, sigma, Y, logpi, mask, starts, win, lam):
|
|
mu, sigma, Y, logpi, mask = (t.detach().numpy() for t in (mu, sigma, Y, logpi, mask))
|
|
if mask.ndim == 2:
|
|
mask = np.repeat(mask[:, None, :], Y.shape[1], axis=1)
|
|
per_well = []
|
|
for b in range(mu.shape[0]):
|
|
num = den = 0.0
|
|
for s0 in starts[b].numpy():
|
|
j = np.arange(s0, s0 + win)
|
|
n = mask[b][:, j].sum(-1)
|
|
if (n == 0).any():
|
|
continue
|
|
ll = np.array([(-np.log(sigma[b, i]) - 0.5 * ((Y[b, s, i] - mu[b, i]) / sigma[b, i]) ** 2
|
|
- 0.5 * np.log(2 * np.pi)).sum() for s, i in enumerate(j[m] for m in mask[b][:, j])])
|
|
ll = ll * n.mean() / n
|
|
if lam is None:
|
|
num += ll.max()
|
|
else:
|
|
z = logpi[b] + lam * ll
|
|
num += (z.max() + np.log(np.exp(z - z.max()).sum())) / lam
|
|
den += n.mean()
|
|
per_well.append(-num / den)
|
|
return np.mean(per_well)
|
|
|
|
|
|
@pytest.mark.parametrize("lam", [None, 0.25])
|
|
def test_masked_bank_loss_matches_a_brute_force_reference_and_ignores_unlabelled_samples(lam):
|
|
mu, sigma, Y, logpi, starts = bank()
|
|
mask = torch.zeros(mu.shape, dtype=torch.bool)
|
|
mask[0, 10:30] = True # one short run: most windows of well 0 are unlabelled
|
|
mask[1, 40:77] = True
|
|
mask[1, 100:110] = True # two runs
|
|
mask[2, :] = True # fully labelled: per-well normalisation, not pooled samples
|
|
Y = torch.where(mask[:, None, :], Y, torch.full_like(Y, np.nan))
|
|
loss = masked_bank_loss(mu, sigma, Y, logpi, mask, starts, 64, lam)
|
|
assert np.isclose(loss.item(), brute_force(mu, sigma, Y, logpi, mask, starts, 64, lam), rtol=1e-10)
|
|
loss.backward()
|
|
assert torch.isfinite(mu.grad).all() and torch.isfinite(sigma.grad).all()
|
|
assert (mu.grad[~mask] == 0).all() and (sigma.grad[~mask] == 0).all()
|
|
assert (mu.grad[mask] != 0).any()
|
|
|
|
|
|
@pytest.mark.parametrize("lam", [None, 0.25])
|
|
@pytest.mark.parametrize("win", [64, L])
|
|
def test_member_masks_match_brute_force_and_reduce_to_a_shared_mask(lam, win):
|
|
mu, sigma, Y, logpi, _ = bank()
|
|
starts = torch.tensor(np.tile(np.arange(0, L - win + 1, 2), (3, 1)))
|
|
mask = torch.zeros(Y.shape, dtype=torch.bool)
|
|
for s in range(Y.shape[1]): # the same 16-sample run, placed by each member at its own offset
|
|
mask[0, s, 20 + s: 36 + s] = True
|
|
mask[1, s, 60 - s: 77 - s + (s % 2)] = True # counts 17 or 18: rescaled to the mean count
|
|
mask[2] = True
|
|
Yn = torch.where(mask, Y, torch.full_like(Y, np.nan))
|
|
loss = masked_bank_loss(mu, sigma, Yn, logpi, mask, starts, win, lam)
|
|
assert np.isclose(loss.item(), brute_force(mu, sigma, Yn, logpi, mask, starts, win, lam), rtol=1e-10)
|
|
loss.backward()
|
|
union = mask.any(1)
|
|
assert torch.isfinite(mu.grad).all() and (mu.grad[~union] == 0).all() and (sigma.grad[~union] == 0).all()
|
|
shared = torch.zeros(mu.shape, dtype=torch.bool)
|
|
shared[:, 30:50] = True
|
|
a = masked_bank_loss(mu, sigma, Y, logpi, shared, starts, win, lam)
|
|
b = masked_bank_loss(mu, sigma, Y, logpi, shared[:, None, :].expand(Y.shape), starts, win, lam)
|
|
assert torch.allclose(a, b, rtol=1e-12)
|
|
with pytest.raises(ValueError, match="mask"):
|
|
masked_bank_loss(mu, sigma, Y, logpi, mask[:, :2], starts, win, lam)
|
|
|
|
|
|
def test_masked_bank_loss_does_not_depend_on_values_outside_the_mask():
|
|
mu, sigma, Y, logpi, starts = bank()
|
|
mask = torch.zeros(mu.shape, dtype=torch.bool)
|
|
mask[:, 50:80] = True
|
|
a = masked_bank_loss(mu, sigma, Y, logpi, mask, starts, 64, 0.5)
|
|
Y2 = torch.where(mask[:, None, :], Y, torch.full_like(Y, 1e6))
|
|
assert torch.equal(a, masked_bank_loss(mu, sigma, Y2, logpi, mask, starts, 64, 0.5))
|
|
|
|
|
|
def test_masked_bank_loss_rejects_a_well_without_labels():
|
|
mu, sigma, Y, logpi, starts = bank()
|
|
mask = torch.ones(mu.shape, dtype=torch.bool)
|
|
mask[1] = False
|
|
with pytest.raises(ValueError, match="no labelled sample"):
|
|
masked_bank_loss(mu, sigma, Y, logpi, mask, starts, 64, 0.5)
|
|
|
|
|
|
@pytest.mark.parametrize("n", [16, 40, 126])
|
|
def test_highpass_segment_equals_split_bands_from_16_samples(n):
|
|
y = np.random.default_rng(n).normal(size=n).cumsum()
|
|
assert np.allclose(highpass_segment(y, 6.0, 4.0), split_bands(y, 6.0, 4.0)[1], atol=1e-12)
|
|
|
|
|
|
def test_highpass_segment_accepts_short_label_runs():
|
|
y = np.random.default_rng(1).normal(size=5)
|
|
assert np.isfinite(highpass_segment(y, 6.0, 4.0)).all()
|
|
|
|
|
|
def test_segment_lambda_equals_effective_lambda_for_long_segments():
|
|
rng = np.random.default_rng(2)
|
|
segs = [rng.normal(size=n).cumsum() * 0.01 for n in (80, 126, 60)]
|
|
assert np.allclose(segment_lambda(segs, 6.0, 4.0, 32), effective_lambda(segs, 6.0, 4.0, 32), rtol=1e-12)
|
|
lam, tau = segment_lambda([s[:20] for s in segs], 6.0, 4.0, 32) # runs shorter than the maximum lag
|
|
assert 0 < lam <= 1 and np.isclose(lam * tau, 1.0)
|
|
with pytest.raises(ValueError):
|
|
segment_lambda([np.array([0.1, np.nan, 0.2])])
|
|
|
|
|
|
def test_finite_runs_and_label_segments():
|
|
y = np.array([np.nan, 1, 2, np.nan, np.nan, 3, np.nan, 4, 5, 6])
|
|
assert finite_runs(y) == [(1, 3), (5, 6), (7, 10)]
|
|
assert [s.tolist() for s in label_segments(y)] == [[1, 2], [3], [4, 5, 6]]
|
|
assert finite_runs(np.full(4, np.nan)) == []
|
|
assert finite_runs(np.ones(4)) == [(0, 4)]
|
|
|
|
|
|
# ---------- public/private views ----------
|
|
|
|
PRIVATE_ITEMS = ["il", "xl", "x", "y", "log/md", "log/DT", "anchors_md", "anchors_twt_ms", "tdr/sonic/md",
|
|
"support/md", "reference/seismic_patch", "calibrated/PHIF", "calibrated/AI", "anchors/PHIF",
|
|
"sonic/PHIF"]
|
|
|
|
|
|
def test_a_training_view_holds_only_public_items_and_admissible_blind_keys_of_held_out_wells():
|
|
train = ("F-1", "F-11 A", "F-12")
|
|
view = VolveData(P, training_wells=train, arrays=ARRAYS)
|
|
for w in WELLS:
|
|
if w in train:
|
|
assert all(f"{w}/{item}" in view.arrays for item in PRIVATE_ITEMS)
|
|
continue
|
|
for item in PRIVATE_ITEMS:
|
|
assert f"{w}/{item}" not in view.arrays, f"{w}/{item} leaked"
|
|
assert all(f"{w}/{item}" in view.arrays for item in ("times_ms", "main_mask", "kb_msl", "survey/md"))
|
|
keys = view.blind_keys(w)
|
|
assert keys, w
|
|
for k in keys:
|
|
members = set(k.split("+"))
|
|
assert w not in members and set(train) <= members
|
|
expected = {blind_key(train + extra) for r in range(3)
|
|
for extra in itertools.combinations([v for v in WELLS if v not in train and v != w], r)}
|
|
assert set(keys) == expected
|
|
assert not any(k.startswith("F-11 T2/NIVSP") for k in view.arrays)
|
|
|
|
|
|
def test_a_training_view_refuses_held_out_labels_reference_inputs_and_registration_inputs():
|
|
view = VolveData(P, training_wells=("F-1", "F-12"), arrays=ARRAYS)
|
|
assert view.y("F-1", "calibrated").shape == (L,)
|
|
with pytest.raises(RuntimeError):
|
|
view.y("F-1 A", "calibrated")
|
|
with pytest.raises(RuntimeError):
|
|
view.patch("F-1 A", "reference")
|
|
with pytest.raises(RuntimeError):
|
|
view.patch("F-1", blind_key(("F-1", "F-12")))
|
|
with pytest.raises(RuntimeError):
|
|
view.training_observations(("F-1", "F-1 A"))
|
|
with pytest.raises(KeyError, match="not in this data view"):
|
|
view.ext("F-1 A", "anchors_md")
|
|
with pytest.raises(KeyError): # a blind key without every training well is not admissible
|
|
view.patch("F-1 A", "F-1")
|
|
assert view.X("F-1 A", "F-1+F-12").shape == (9, L)
|
|
|
|
|
|
def test_visible_rules():
|
|
train = frozenset({"F-1", "F-12"})
|
|
assert visible("F-1/log/DT", train) and visible("F-1/log/DT", None)
|
|
assert visible("F-1 A/survey/md", train) and visible("F-1 A/times_ms", train)
|
|
assert not visible("F-1 A/il", train) and not visible("F-1 A/calibrated/PHIF", train)
|
|
assert visible("F-1 A/blind/F-1+F-12/seismic_patch", train)
|
|
assert visible("F-1 A/blind/F-1+F-11 A+F-12/seismic_patch", train)
|
|
assert not visible("F-1 A/blind/F-1/seismic_patch", train)
|
|
assert not visible("F-1 A/blind/F-1+F-1 A+F-12/seismic_patch", train)
|
|
|
|
|
|
def test_the_full_view_is_only_for_scoring():
|
|
full = VolveData(P, arrays=ARRAYS)
|
|
assert full.y("F-1 A", "calibrated").shape == (L,)
|
|
with pytest.raises(ValueError):
|
|
VolveData(P, training_wells=("F-99",), arrays=ARRAYS)
|
|
|
|
|
|
# ---------- folds ----------
|
|
|
|
|
|
def test_fold_counts_and_target_counts():
|
|
folds = nested_folds(WELLS, SCHEMES, P4)
|
|
sets = training_sets(WELLS, SCHEMES, P4)
|
|
assert len(folds) == 52 and sum(f["scheme"] == "lowo" for f in folds) == 30
|
|
assert [len(s) for s in sets].count(4) == 15 and [len(s) for s in sets].count(3) == 4
|
|
assert [len(s) for s in sets].count(2) == 3 and len(sets) == 22
|
|
assert {len(s): len(prediction_targets(WELLS, s)) for s in sets} == {4: 8, 3: 15, 2: 34}
|
|
|
|
|
|
def test_folds_never_train_on_a_held_out_well_and_slot_holds_out_the_whole_group():
|
|
for f in nested_folds(WELLS, SCHEMES, P4):
|
|
assert f["test"] not in f["outer_train"] and f["validation"] in f["outer_train"]
|
|
assert f["test"] not in f["inner_train"] and f["validation"] not in f["inner_train"]
|
|
assert set(f["inner_train"]) | {f["validation"]} == set(f["outer_train"])
|
|
if f["scheme"] == "slot":
|
|
group = next(g for g in P4["slot_groups"] if f["test"] in g)
|
|
assert not set(group) & set(f["outer_train"])
|
|
else:
|
|
assert set(f["outer_train"]) == set(WELLS) - {f["test"]}
|
|
assert dict(outer_folds(WELLS, "slot", P4))["F-11 T2"] == ("F-1", "F-1 A", "F-1 B", "F-12")
|
|
assert dict(outer_folds(WELLS, "slot", P4))["F-12"] == tuple(sorted(WELLS[:5]))
|
|
with pytest.raises(ValueError):
|
|
inner_folds(("F-12",))
|
|
|
|
|
|
def test_prediction_targets_cover_every_validation_and_test_input():
|
|
for f in nested_folds(WELLS, SCHEMES, P4):
|
|
names = {target_name(w, k) for w, k in prediction_targets(WELLS, f["inner_train"])}
|
|
assert target_name(f["validation"], f["validation_key"]) in names
|
|
assert target_name(f["test"], f["test_key"]) in names
|
|
assert f["test_key"] == blind_key(blind_training_wells(f["test"], f["scheme"], P4))
|
|
for s in training_sets(WELLS, SCHEMES, P4):
|
|
for w, k in prediction_targets(WELLS, s):
|
|
assert k == "reference" if w in s else (w not in k.split("+") and set(s) <= set(k.split("+")))
|
|
|
|
|
|
# ---------- training ----------
|
|
|
|
|
|
def toy_bundle(method="M2-Sa", B=2, S=4):
|
|
rng = np.random.default_rng(3)
|
|
mask = np.zeros((B, S, L), bool)
|
|
for s in range(S):
|
|
mask[0, s, 30 + s: 55 + s], mask[1, s, 60 - s: 80 - s] = True, True
|
|
Y = np.where(mask, 0.2 + 0.03 * rng.standard_normal((B, S, L)), np.nan).astype(np.float32)
|
|
bundle = {"PHIF/norm": np.array([0.2, 0.03]), f"PHIF/{method}": Y, "PHIF/lambda": np.array(0.4)}
|
|
if method == "M2-Sa":
|
|
bundle["PHIF/M2-Sa/logpi"] = np.full((B, S), -np.log(S))
|
|
return bundle
|
|
|
|
|
|
def test_method_spec_normalises_and_rejects_inconsistent_banks():
|
|
spec = method_spec(toy_bundle(), "PHIF", "M2-Sa")
|
|
assert np.allclose(np.nanmean(spec["Y"]), 0.0, atol=0.5) and spec["lam"] == pytest.approx(0.4)
|
|
single = method_spec(toy_bundle("B3b", S=1), "PHIF", "B3b")
|
|
assert single["logpi"].shape == (2, 1) and np.allclose(single["logpi"], 0.0)
|
|
bad = toy_bundle()
|
|
bad["PHIF/M2-Sa/logpi"] = np.zeros((2, 3))
|
|
with pytest.raises(ValueError, match="weights"):
|
|
method_spec(bad, "PHIF", "M2-Sa")
|
|
assert spec["mask"].shape == (2, 4, L) and spec["mask"].sum(-1).tolist() == [[25] * 4, [20] * 4]
|
|
bad = toy_bundle()
|
|
bad["PHIF/M2-Sa"][0, 1, 40] = np.inf
|
|
with pytest.raises(ValueError, match="not finite"):
|
|
method_spec(bad, "PHIF", "M2-Sa")
|
|
bad = toy_bundle()
|
|
bad["PHIF/M2-Sa"][1, 2] = np.nan
|
|
with pytest.raises(ValueError, match="no label support"):
|
|
method_spec(bad, "PHIF", "M2-Sa")
|
|
|
|
|
|
def test_train_trajectory_is_deterministic_on_member_supports():
|
|
cfg = dict(P["training"], d_channels=8)
|
|
assert cfg["window_samples"] == L # one window: the whole main window
|
|
rng = np.random.default_rng(4)
|
|
X, Xt = rng.normal(size=(2, 9, L)), rng.normal(size=(3, 9, L))
|
|
run = lambda b: train_trajectory(X, Xt, method_spec(b, "PHIF", "M2-Sa"), "M2-Sa", cfg, 0, [1, 3], "cpu",
|
|
None, 1)[0]
|
|
a, b = run(toy_bundle()), run(toy_bundle())
|
|
assert set(a) == {"1/mu", "1/sigma", "3/mu", "3/sigma"} and a["3/mu"].shape == (3, L)
|
|
for k in a:
|
|
assert np.isfinite(a[k]).all() and np.array_equal(a[k], b[k])
|
|
assert (a["3/sigma"] > 0).all()
|
|
|
|
|
|
# ---------- runner caches ----------
|
|
|
|
|
|
def test_nan_is_allowed_only_in_label_banks():
|
|
assert nan_allowed("PHIF/M2-Sa") and nan_allowed("PHIF/B3b")
|
|
assert not nan_allowed("PHIF/M2-Sa/logpi") and not nan_allowed("250/mu") and not nan_allowed("PHIF/mask")
|
|
check_arrays("x", {"PHIF/B3b": np.array([np.nan, 0.2]), "wells": np.array(["F-1"])})
|
|
for bad in ({"250/mu": np.array([np.nan, 0.2])}, {"PHIF/B3b": np.full(2, np.nan)},
|
|
{"PHIF/B3b": np.array([np.inf, 0.2])}, {}):
|
|
with pytest.raises(RuntimeError):
|
|
check_arrays("x", bad)
|
|
|
|
|
|
def test_reusable_checks_fingerprint_and_checksums(tmp_path):
|
|
path = reg_path(tmp_path, ("F-1", "F-12"))
|
|
assert not reusable(path, "k")
|
|
save_npz(path, {"PHIF/B3b": np.array([0.1, np.nan]), "phase0": np.array(0.0)})
|
|
path.with_suffix(".json").write_text(json.dumps({"fingerprint": "k", "artifact_sha256": digest(path)}))
|
|
assert reusable(path, "k")
|
|
with pytest.raises(RuntimeError, match="fingerprint"):
|
|
reusable(path, "other")
|
|
save_npz(path, {"PHIF/B3b": np.array([0.3, np.nan]), "phase0": np.array(0.0)})
|
|
with pytest.raises(RuntimeError, match="checksum"):
|
|
reusable(path, "k")
|
|
job = job_path(tmp_path, ("F-1", "F-12"), "B3b", "PHIF", 0)
|
|
save_npz(job, {"2/mu": np.ones(3)})
|
|
job.with_suffix(".json").write_text(json.dumps({"fingerprint": "k", "artifact_sha256": digest(job)}))
|
|
with pytest.raises(RuntimeError, match="checkpoint"):
|
|
reusable(job, "k")
|
|
|
|
|
|
# ---------- selection never reads outer-test labels ----------
|
|
|
|
|
|
def small_protocol():
|
|
p = copy.deepcopy(P)
|
|
p["split"]["seeds"] = [0, 1]
|
|
p["training"]["budgets"] = [2, 4]
|
|
p["registration"]["sigma_a_sensitivity_ms"] = []
|
|
return p
|
|
|
|
|
|
def fake_jobs(root, p):
|
|
"""Trajectory and registration files with deterministic pseudo-predictions (no model)."""
|
|
from ml_porosity.volve.runner import fold_sets
|
|
|
|
sa = p["registration"]["sigma_a_ms"]
|
|
for names in fold_sets(p):
|
|
targets = [target_name(w, k) for w, k in prediction_targets(WELLS, names)]
|
|
for method, seed in itertools.product(p["methods"]["main"], p["split"]["seeds"]):
|
|
rng = np.random.default_rng(zlib.crc32(f"{names}{method}{seed}".encode()))
|
|
z = {"targets": np.asarray(targets), "wells": np.asarray(names), "norm": np.array([0.2, 0.03])}
|
|
for b in p["training"]["budgets"]:
|
|
z[f"{b}/mu"] = 0.2 + 0.03 * rng.standard_normal((len(targets), L))
|
|
z[f"{b}/sigma"] = 0.02 + 0.01 * rng.random((len(targets), L))
|
|
save_npz(job_path(root, names, method, "PHIF", seed, sa), z)
|
|
meta = {"phase0": 0.0, "phase_R": 15.0, "lambda": 0.4, "tau_c": 2.5, "wall_seconds": 1.0,
|
|
"diagnostics": [{"well": w, "gamma": 1.0, "lik_ms": [2500.0, 2600.0],
|
|
"label_samples": {m: 20 for m in p["methods"]["main"]},
|
|
"label_samples_max": {m: 21 for m in p["methods"]["main"]}} for w in names]}
|
|
path = reg_path(root, names, sa).with_suffix(".json")
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(meta))
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def fake_root(tmp_path_factory):
|
|
root = tmp_path_factory.mktemp("p4")
|
|
p = small_protocol()
|
|
fake_jobs(root, p)
|
|
return root, p
|
|
|
|
|
|
def perturbed(arrays, well, seed):
|
|
rng = np.random.default_rng(seed)
|
|
out = dict(arrays)
|
|
for k, v in arrays.items():
|
|
if k.startswith(f"{well}/") and k.endswith("/PHIF"):
|
|
out[k] = v + rng.normal(0, 0.1, v.shape)
|
|
return out
|
|
|
|
|
|
@pytest.mark.parametrize("well", ["F-1", "F-11 T2", "F-12"])
|
|
def test_selection_and_predictions_of_an_outer_fold_ignore_its_test_labels(fake_root, well):
|
|
from ml_porosity.volve.evaluation import neural_predictions
|
|
|
|
root, p = fake_root
|
|
sa = [p["registration"]["sigma_a_ms"]]
|
|
pred_a, sel_a = neural_predictions(p, root, ARRAYS, sa)
|
|
pred_b, sel_b = neural_predictions(p, root, perturbed(ARRAYS, well, 7), sa)
|
|
pick = lambda rows: [r for r in rows if r["test_well"] == well]
|
|
assert pick(sel_a) == pick(sel_b) and len(pick(sel_a)) == len(SCHEMES) * 5 * 2
|
|
for a, b in zip(pick(pred_a), pick(pred_b), strict=True):
|
|
assert np.array_equal(a["mu"], b["mu"]) and np.array_equal(a["sigma"], b["sigma"])
|
|
# The perturbation is real: folds that validate on `well` do see it.
|
|
assert sel_a != sel_b or any(not np.array_equal(a["mu"], b["mu"]) for a, b in zip(pred_a, pred_b))
|
|
|
|
|
|
def test_summarize_runs_end_to_end_on_synthetic_jobs(fake_root):
|
|
import pandas as pd
|
|
|
|
from ml_porosity.volve.evaluation import summarize
|
|
|
|
root, p = fake_root
|
|
gate = summarize(p, root, [p["registration"]["sigma_a_ms"]], arrays=ARRAYS)
|
|
assert gate["evaluated"] and set(gate["schemes"]) == set(SCHEMES)
|
|
assert all(s["n_wells"] == 6 for s in gate["schemes"].values())
|
|
for s in gate["schemes"].values():
|
|
assert {r["competitor"] for r in s["per_well"]} <= set(p["gate"]["point_competitors"])
|
|
dest = root / "summary"
|
|
metrics = pd.read_csv(dest / "metrics.csv")
|
|
assert set(metrics.reference) == {"calibrated", "anchors", "NIVSP", "OPTIMIZED"}
|
|
assert set(metrics[metrics.reference == "NIVSP"].test_well) == {"F-11 T2"}
|
|
assert len(pd.read_csv(dest / "selection.csv")) == len(SCHEMES) * 6 * 5 * 2
|
|
for f in ("macro.csv", "registration.csv", "best_shift_DIAGNOSTIC_ONLY.csv", "predictions.npz",
|
|
"gate_gd.json", "summary.md", "wells_lowo.png", "wells_slot.pdf", "figure_manifest.json"):
|
|
assert (dest / f).exists(), f
|
|
|
|
|
|
def test_fingerprints_separate_jobs():
|
|
stamp = {"protocol_sha256": "a"}
|
|
a = fingerprint(stamp, stage="train", names=["F-1"], method="B3b", label="PHIF", seed=0, sa=7.0)
|
|
assert a != fingerprint(stamp, stage="train", names=["F-1"], method="B3b", label="PHIF", seed=1, sa=7.0)
|
|
assert a != fingerprint(stamp | {"smoke": True}, stage="train", names=["F-1"], method="B3b", label="PHIF",
|
|
seed=0, sa=7.0)
|