- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
(sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.
outputs/ stays out of git; the repository folder is synced as a whole to
the new server. Main S1 runs are still training at this commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
190 lines
9.8 KiB
Python
190 lines
9.8 KiB
Python
"""protocol_bench runner: protocol consistency, cell enumeration, guards, TCN path, S8 two-mode banks, summary rules.
|
|
|
|
No GPU and no main-grid realization is touched; the generator-dependent tests skip when the D2 inputs are missing.
|
|
"""
|
|
|
|
import itertools
|
|
import json
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pytest
|
|
import torch
|
|
import yaml
|
|
|
|
from ml_porosity.benchmark import cells as C
|
|
from ml_porosity.benchmark import protocol as PR
|
|
from ml_porosity.paths import REPO_ROOT, f3_root
|
|
|
|
P = yaml.safe_load((REPO_ROOT / "configs" / "protocol_bench.yaml").read_text(encoding="utf-8"))
|
|
GEN = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text(encoding="utf-8"))
|
|
NEEDED = [f3_root() / ".survey", REPO_ROOT / GEN["horizon_cache"], REPO_ROOT / P["inputs"]["warp_prior"]["path"],
|
|
REPO_ROOT / P["inputs"]["wavelet"]["path"]]
|
|
needs_inputs = pytest.mark.skipif(not all(f.exists() for f in NEEDED), reason="missing D2 inputs")
|
|
|
|
|
|
def test_protocol_consistency():
|
|
presets = GEN["misspec_presets"]
|
|
s2 = P["studies"]["S2"]
|
|
for names in s2["presets"].values():
|
|
assert all(n in presets for n in names), names
|
|
assert all(n in presets for n in s2["controls"]["presets"])
|
|
for s in P["studies"].values():
|
|
for m in s["methods"]:
|
|
assert m in P["training"]["budgets"], m
|
|
assert set(P["grid"]["regimes"]) == set(GEN["regimes"])
|
|
assert not set(P["grid"]["realizations"]) & set(P["grid"]["dev_realizations"])
|
|
p2 = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text(encoding="utf-8"))
|
|
assert not set(P["grid"]["realizations"]) & set(p2["grid"]["realizations"])
|
|
p2r = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2r.yaml").read_text(encoding="utf-8"))
|
|
assert P["grid"]["realizations"] == p2r["grid"]["realizations"]
|
|
for m in ("Oracle", "B3b", "B3c", "B3c-R", "B3d", "B3d-Sa", "M2-Sa"):
|
|
assert P["training"]["budgets"][m] == p2r["training"]["budgets"][m], m
|
|
for m in ("B4a", "B4b", "B4c", "B4d"):
|
|
assert P["training"]["budgets"][m] == p2["training"]["budgets"][m], m
|
|
for k, h in P["hypotheses"].items():
|
|
assert h["kind"] in ("claim", "descriptive", "disclosed"), k
|
|
assert h.get("statement") or h.get("items"), k
|
|
|
|
|
|
def test_cell_counts_and_uniqueness():
|
|
counts = {"S1": 560, "S2": 224, "S3": 240, "S4": 48, "S8": 96}
|
|
for s, n in counts.items():
|
|
cs = C.study_cells(P, s)
|
|
assert len(cs) == n, (s, len(cs))
|
|
assert len(set((c.setting, c.tag, c.backbone) for c in cs)) == n
|
|
s1 = C.study_cells(P, "S1")
|
|
assert not any(c.c in (0, 1, 2) and c.n_train in (4, 16) for c in s1) # P2r cells are read, not recomputed
|
|
assert sum(C.needs_posterior(c) for c in C.study_cells(P, "S3")) == 0 and all(c.posterior == "p2r" for c in C.study_cells(P, "S3"))
|
|
assert all(c.posterior == "p2r" and c.backbone == "tcn" for c in C.study_cells(P, "S4"))
|
|
assert sorted(set(c.delta_ms for c in C.study_cells(P, "S8"))) == [8.0, 16.0, 32.0]
|
|
assert len(C.study_cells(P, "S2", controls=True)) == 224 + 32
|
|
dev = C.study_cells(P, "S1", rids=[902], regimes=["R10"], grid={"drift_factors": [1.0], "n_train": [4]})
|
|
assert len(dev) == 1 and dev[0].tag == "r902_c1_n4"
|
|
|
|
|
|
def test_paths_shared_posterior_and_flat_names(tmp_path):
|
|
a = C.Cell("S1", "R10", None, 1.0, 4, 902, ("Oracle",))
|
|
b = C.Cell("S4", "R10", None, 1.0, 4, 902, ("Oracle",), backbone="tcn", posterior="bench")
|
|
assert C.posterior_paths(a, tmp_path, 0)["particles"] == C.posterior_paths(b, tmp_path, 0)["particles"]
|
|
assert C.posterior_paths(a, tmp_path, 0)["particles"].name == "r902_c1_n4_s0_particles.npz"
|
|
assert C.train_paths(b, tmp_path)["csv"].name == "r902_c1_n4__tcn.csv"
|
|
s8 = C.Cell("S8", "Rm5", None, 1.0, 16, 8, ("PM2",), posterior="none", delta_ms=32.0)
|
|
assert C.posterior_dir(s8, tmp_path) is None and s8.tag == "r8_c1_n16_d32"
|
|
s2 = C.Cell("S2", "R10", "wv_L1", 1.0, 16, 8, ("Oracle",))
|
|
assert s2.setting == "R10__wv_L1"
|
|
|
|
|
|
def test_guards():
|
|
for rids, dev in (([0], True), ([3], False), ([8, 902], True), ([902], False), ([8], True), ([77], True)):
|
|
with pytest.raises(SystemExit):
|
|
PR.check_rids(rids, P, dev=dev)
|
|
PR.check_rids([902, 905], P, dev=True)
|
|
PR.check_rids([P["reproduction"]["rid"]], P, dev=False, repro=True)
|
|
with pytest.raises(SystemExit):
|
|
PR.check_rids([9], P, dev=False, repro=True)
|
|
if not PR.LOCK.exists():
|
|
with pytest.raises(RuntimeError):
|
|
PR.check_rids([8], P, dev=False)
|
|
|
|
|
|
def test_fingerprint_depends_on_settings():
|
|
st = {"protocol_sha256": "x", "dev": True}
|
|
assert PR.fingerprint(st, stage="train", rid=8) != PR.fingerprint(st, stage="train", rid=9)
|
|
assert PR.fingerprint(st, a=1, b=2) == PR.fingerprint(st, b=2, a=1)
|
|
|
|
|
|
def test_tcn_training_path_runs_on_cpu():
|
|
from ml_porosity.benchmark.training import train_predict_tcn
|
|
|
|
rng = np.random.default_rng(0)
|
|
X, Xte = rng.normal(size=(3, 9, 126)).astype(np.float32), rng.normal(size=(2, 9, 126)).astype(np.float32)
|
|
Y = rng.normal(size=(3, 2, 126)).astype(np.float32)
|
|
spec = {"kind": "bank", "Y": Y, "logpi": np.full((3, 2), -np.log(2), np.float32), "lam": 0.5}
|
|
cfg = {"d_channels": 8, "p_dropout": 0.0, "lr": 1e-3, "grad_clip": 5.0}
|
|
out = train_predict_tcn(X, Xte, spec, cfg, 0, [2, 3], "cpu")
|
|
assert set(out) == {2, 3} and out[3][0].shape == (2, 126) and np.all(out[3][1] > 0)
|
|
out2 = train_predict_tcn(X, Xte, spec, cfg, 0, [3], "cpu")
|
|
assert np.allclose(out[3][0], out2[3][0]) # same seed, same trajectory
|
|
spec_h = spec | {"lam": None}
|
|
assert train_predict_tcn(X, Xte, spec_h, cfg, 0, [2], "cpu")[2][0].shape == (2, 126)
|
|
|
|
|
|
@needs_inputs
|
|
def test_two_mode_banks_match_corollary_setup():
|
|
from ml_porosity.benchmark.data import load_inputs
|
|
from ml_porosity.benchmark.training import two_mode_banks
|
|
from ml_porosity.registration.labels import antialias, labels_for_warps
|
|
|
|
inp = load_inputs(PR.load_protocol())
|
|
R = inp.realization(902, None)
|
|
obs, _ = inp.observe(R, 1.0, "R10", 4)
|
|
diag = [{} for _ in obs]
|
|
banks = two_mode_banks(R, obs, 32.0, diag)
|
|
assert np.stack(banks["BK2"]).shape == (4, 2, len(R.t_main)) and np.stack(banks["PM2"]).shape == (4, 1, len(R.t_main))
|
|
sides = [d["side"] for d in diag]
|
|
assert set(sides) <= {-1, 1}
|
|
for i, o in enumerate(obs):
|
|
y_aa = antialias(o["phi_log"], R.cfg["fine_dt_ms"], R.dt)
|
|
oracle = labels_for_warps(R.tau_fine, y_aa, o["t_of_tau_true"][None], R.t_main)[0]
|
|
assert np.allclose(banks["BK2"][i][0], oracle) # the truth is a member of the bank
|
|
assert 11.0 < diag[i]["PM2_warp_rmse_ms"] < 19.0 # mean warp off by Δ/2 in t, i.e. Δ/(2 e^g) in τ
|
|
again = two_mode_banks(R, obs, 32.0, [{} for _ in obs])
|
|
assert all(np.array_equal(a, b) for a, b in zip(banks["BK2"], again["BK2"])) # declared stream → deterministic
|
|
|
|
|
|
@needs_inputs
|
|
def test_dev_grid_override_and_nominal_fingerprint_helper():
|
|
from ml_porosity.benchmark.data import fingerprint_realization, load_inputs
|
|
|
|
inp = load_inputs(PR.load_protocol())
|
|
fp = fingerprint_realization(inp.realization(902, None))
|
|
stored = json.loads((REPO_ROOT / P["inputs"]["fingerprints"]["path"]).read_text())["realizations"]["902"]
|
|
assert fp["wells"]["z_g"] == stored["wells"]["z_g"]
|
|
assert fp["obs"]["seis"] == stored["obs"]["seis"]
|
|
|
|
|
|
def test_summary_rules_on_synthetic_runs():
|
|
from ml_porosity.benchmark.summary import h2a_cells, pair
|
|
|
|
rng = np.random.default_rng(1)
|
|
rows = []
|
|
for rid, seed, N, m in itertools.product(range(8), range(5), (4, 16), ("B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa")):
|
|
base = {"B3b": 1.0, "B3c": 0.8, "B3c-R": 0.82, "B3d-Sa": 0.6, "M2-Sa": 0.58}[m]
|
|
rows.append({"rid": rid, "seed": seed, "c": 1.0, "n_train": N, "method": m, "band_rmse": base + 0.01 * rng.standard_normal(),
|
|
"band_pcc": 0.9 - base / 10, "rmse": base, "pcc": 0.9})
|
|
run = pd.DataFrame(rows)
|
|
cells = h2a_cells(run, "B3d-Sa", ["B3b", "B3c", "B3c-R"], np.random.default_rng(0), 200)
|
|
assert len(cells) == 2 and cells.cell_pass.all() and (cells.best == "B3c").all()
|
|
pr = pair(run[run.n_train == 16], "M2-Sa", "B3d-Sa", np.random.default_rng(0), 200)
|
|
assert pr["better"] and pr["ratio"] < 1 and pr["ratio_lo"] <= pr["ratio"] <= pr["ratio_hi"]
|
|
|
|
|
|
@needs_inputs
|
|
def test_control_gp_bank_matches_t2_construction():
|
|
from ml_porosity.benchmark.data import load_inputs
|
|
from ml_porosity.benchmark.training import control_gp_bank
|
|
|
|
inp = load_inputs(PR.load_protocol())
|
|
R = inp.realization(902, None)
|
|
obs, _ = inp.observe(R, 1.0, "R10", 2)
|
|
rng = np.random.default_rng(3)
|
|
smc = {}
|
|
for o in obs: # synthetic "particles": smooth g, b ~ N(0, 3 ms); 256 of them
|
|
g = 0.02 + 0.03 * np.cumsum(rng.standard_normal((256, R.grid.n)), 1) / np.sqrt(np.arange(1, R.grid.n + 1))
|
|
smc[f"{o['name']}/estR/g_acf"] = np.column_stack([3 * rng.standard_normal(256), g]).astype(np.float32)
|
|
diag = [{} for _ in obs]
|
|
banks, logpi = control_gp_bank(R, obs, smc, inp.reg, 0, diag)
|
|
assert np.stack(banks).shape == (2, inp.reg["S"], len(R.t_main)) and np.stack(logpi).shape == (2, inp.reg["S"])
|
|
assert all(0.8 < d["Ctl-GP_sd_ratio"] < 1.2 for d in diag) and all(d["Ctl-GP_n_valid"] == inp.reg["S"] for d in diag)
|
|
again, _ = control_gp_bank(R, obs, smc, inp.reg, 0, [{} for _ in obs])
|
|
assert all(np.array_equal(a, b) for a, b in zip(banks, again))
|
|
|
|
|
|
def test_budget_list_includes_equal_budget_arm():
|
|
from ml_porosity.benchmark.training import budget_list, budget_of
|
|
|
|
assert budget_of(P, "B3d-Sa", "cnngru") == 250 and budget_list(P, "B3d-Sa", "cnngru") == sorted({250, P["training"]["equal_budget_arm"]})
|
|
assert budget_list(P, "Oracle", "cnngru") == [500]
|
|
assert budget_list(P, "B3b-TCN", "tcn")[0] == (P["training"].get("budgets_tcn") or {}).get("B3b", 125)
|