Add P6 benchmark code, locked protocol_bench, T2 study and lock inputs
- 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.
- The eight protocol_bench inputs force-added from outputs/ (warp prior,
wavelets, horizon cache, budgets) so load_protocol() and summarize work
after a fresh clone. The 102 P2r reference artifacts (1.4 GB of particle
npz) are not in git; they are only checked by posterior/train stages.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.
Main S1 runs are still training at this commit; results follow.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
127
tests/data/d2_fingerprints.json
Normal file
127
tests/data/d2_fingerprints.json
Normal file
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"meta": {
|
||||
"created": "2026-10-29",
|
||||
"purpose": "SHA-256 fingerprints of the D2 default path before misspecification parameters were added (phase P6, item p6-gen); recomputed by tests/test_d2_misspec.py",
|
||||
"generator": "ml_porosity/data/synth_d2.py at commit 0cfe202",
|
||||
"inputs": {
|
||||
"d2_config": "57b676f0fc569ebe44f6253426fe42a218fb06272323b949932e9f8d597ff0d3",
|
||||
"warp_prior": "55cda573c06b3a7275bdb4ac5f169fb4e5af329e1d199acc3d4daffe15624d27",
|
||||
"wavelet": "b689ea12578e580d8c2305c8f7219be05ff6e339884fa30b694111e968c0fc64"
|
||||
},
|
||||
"input_paths": {
|
||||
"d2_config": "configs/d2_synth_p2r.yaml",
|
||||
"warp_prior": "outputs/p2/warp_prior_f3.json",
|
||||
"wavelet": "outputs/wavelets.npz"
|
||||
},
|
||||
"warp_prior_fit": "matern32",
|
||||
"wavelet_key": "statistical",
|
||||
"rids": [
|
||||
900,
|
||||
8,
|
||||
902
|
||||
],
|
||||
"drift_factors": [
|
||||
0.0,
|
||||
1.0,
|
||||
2.0
|
||||
],
|
||||
"snr_db": 10,
|
||||
"sigma_a_ms": 7.0,
|
||||
"anchor_density": "full",
|
||||
"obs_wells": "8 test wells + first 4 pool wells, concatenated over drift factors then wells",
|
||||
"well_fields": [
|
||||
"seis_clean",
|
||||
"noise_unit",
|
||||
"phi_t",
|
||||
"z_g",
|
||||
"z_b",
|
||||
"boundaries_t",
|
||||
"eps_a"
|
||||
],
|
||||
"obs_keys": [
|
||||
"seis",
|
||||
"phi_log",
|
||||
"ai_log",
|
||||
"tau_k",
|
||||
"t_k",
|
||||
"b",
|
||||
"g",
|
||||
"t_of_tau_true",
|
||||
"y_true"
|
||||
],
|
||||
"env": {
|
||||
"numpy": "2.5.4",
|
||||
"scipy": "1.18.1",
|
||||
"python": "3.13.15",
|
||||
"platform": "Linux-6.8.0-136-generic-x86_64-with-glibc2.39"
|
||||
}
|
||||
},
|
||||
"realizations": {
|
||||
"900": {
|
||||
"wells": {
|
||||
"seis_clean": "e460372264253280218c769a4b2f65f4b531f3142fee5d5b595e90b5ee04914f",
|
||||
"noise_unit": "259ccc2614faeab0d496f0e17605105990ecfe4d26a512148e1aa3829ea64a54",
|
||||
"phi_t": "b07358ee2077dc844c995588966e7d539d007dd5315e24b7e0702dbdf59639ab",
|
||||
"z_g": "d42a6e15f2f13715b0adb65dadc4a26b1e15bf8cb82053c9148ae7abd6f1e61d",
|
||||
"z_b": "dcebebc51a5356182578dfe37f3957e8f84cf5b8bd1c0c419faa3d221eceb52e",
|
||||
"boundaries_t": "093d53cd27316aa07fb1e3c93b3fd080a228dd18071abaf380e23bf8b0622108",
|
||||
"eps_a": "5a3d87cdbace9cbeb6ca7884c6f55511c80506964099e2a2e28deac0e36503b3"
|
||||
},
|
||||
"obs": {
|
||||
"seis": "b096fac64e04ce61bcc8cf22bfe7d65538ba2a060b42e53fb236a52dbc5a7c78",
|
||||
"phi_log": "734bc3e4926415b40c3fd4127ba3e064be9ff139ebe3e08e7181bd90bc573956",
|
||||
"ai_log": "3204dbd982535fc9a5668156b57c44065dbc9cae20cc8027c8a448f5b62fa0e0",
|
||||
"tau_k": "35e971e2cd0a052ea99758c5409b9368c0e152f0eb7143f4a225945bdc0c8ffd",
|
||||
"t_k": "1cbb0f63cbebe841f393f03a4b44f0a736f3c442729e140ca82c1c0d2263ed61",
|
||||
"b": "288fdad9c7bb60b647c2d32f0db339e1158c53c6cfa6b9de9c114dbd4aa73e4d",
|
||||
"g": "50e489f199452348585a232b688037c76a3176fa311f1315d23d0ff1aec45075",
|
||||
"t_of_tau_true": "8615f79f1c306ce46ace0dbaf5e3d449d3ac25eadf97645492742ea422f90deb",
|
||||
"y_true": "9a96e7ff339bd6eff9cc113217679dc365e5d8116901972a6ad940ae92b10471"
|
||||
}
|
||||
},
|
||||
"8": {
|
||||
"wells": {
|
||||
"seis_clean": "cfca2356612b93197b614b4e3d5154fa4bae1586375fbc25280591edb5384ad0",
|
||||
"noise_unit": "a3aa075dc0eb79991380748b0ebff93d44f3821f6f42405b6f898299e07eab60",
|
||||
"phi_t": "802a7cd4da3ab63031ea7c1979d9b6e84a0d9c7ac7cd31940435fcbd62a250cc",
|
||||
"z_g": "65024e6ca2ae9dff122e16bc4f957e17d0844ebfbc260d5c0fde49c7cd619ada",
|
||||
"z_b": "e1653c27d05bdc055912e9bda3488b6cc735c30cd04e4d85a5efbc9f4f917d6c",
|
||||
"boundaries_t": "f407b1a729abda7a6acb7c22ece5e834c56afd72d87ece179482833d69b172f8",
|
||||
"eps_a": "da3cdea0869cbfd9f2c7a2d3d2f5ed789118df8ec87dfcda37661dc27a40b32e"
|
||||
},
|
||||
"obs": {
|
||||
"seis": "205947a1e5443da066c8e292255724def0d62d81bb22e2197a538461c5d2e3d4",
|
||||
"phi_log": "fa9bf941a520d2b8f213e27f0fcec14bef81fc64112dbbe969c9a29b7d4654b4",
|
||||
"ai_log": "9fd476bb875b5482c2f38f38c9cb5232d6cf503d16d7e37daec1c110880b8009",
|
||||
"tau_k": "00e51672611fc3b6672d0c6acdf484a025a999114fd5fc785c3d2ba2af8c745b",
|
||||
"t_k": "96e9393d77ec22f68c6d02bf8f9faf2405ed747b1f2318c0ce7f776b65fec057",
|
||||
"b": "0755adab47cbc6a08adaddecc3de50b2829dae738d63659040b86138fd1e17c8",
|
||||
"g": "7b1de59ada788bc7815b2c43e39b41d37475dd85c10f5dae5b0ac97f1437267c",
|
||||
"t_of_tau_true": "17264af616441713e0dba664b09ba03739fc7a06608a19ea0fd1787f63f5476d",
|
||||
"y_true": "44a8b5d80d0f5e5ebd2fa554ce032c174535a31677834bbd7763c7fbb3bd4417"
|
||||
}
|
||||
},
|
||||
"902": {
|
||||
"wells": {
|
||||
"seis_clean": "5f3534d09866d3703ae30e7d08d6debf359d0cec1ac0bd03badf0e1002db148c",
|
||||
"noise_unit": "7fc3986dee0a0b613879bf2074702429e266ad0cce0d819ac742b4704f1ba009",
|
||||
"phi_t": "e880ed13dcdf17c783acfd03bcf70403e15ac2ddc3c081bcb804f49df42ce724",
|
||||
"z_g": "d2b4e0551a08eb304f034c3289b68b85429c0b1518d98cd2c6d98cdee6f4714f",
|
||||
"z_b": "228ca890c469b1adfd0c2ceb26dfcc966fa08da2aaf7d60916419bf33b4e5d1d",
|
||||
"boundaries_t": "0c5e18d68c4d4d1f1c71e170edc7f2e80c6ab425ccc2b5e98e42207a8cb3d6e2",
|
||||
"eps_a": "7d640af84c68b56a6ce3446fcdd07ae6847b0aeedf80c18e73f7b7117a667451"
|
||||
},
|
||||
"obs": {
|
||||
"seis": "68203f9a4ff5c6a21f30227c997f6d7cf496058dfffe6fa257a57235c70c8013",
|
||||
"phi_log": "b2ba9800e47bc362bdbb1ea2d6afee208289d8972edefae7ff5f0f2a6615e039",
|
||||
"ai_log": "3467e34f9d9f4d649b6ae472dd91a8f505df2dc4a4b3e4ff6b71d3d0d6a8c641",
|
||||
"tau_k": "11d9bb79da9ae6ee0ccac5abde6508bd4c41ea180cfa9e304f8ad33274373e34",
|
||||
"t_k": "2eeebb99fb6725ef91bcbab55d5bedc9cac8c75339c7468a7bedcf8d1cc2efbe",
|
||||
"b": "edaf277378cd1bceb33e7eff98ad4f8738592af7522161b9f40c889b09b9ba91",
|
||||
"g": "65cb230013ccbf845128af85e871c126f1b9a3035ef13cecce37b0116c8170d1",
|
||||
"t_of_tau_true": "870ee33b8ccfdce32beb7117bfa4da65396987d775ecaa5e8a3b10aab58e0dc4",
|
||||
"y_true": "33bcedc3461259c7ab62e24e180d2eac78884c16cd7ad2e707104cbbd8981682"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
189
tests/test_bench.py
Normal file
189
tests/test_bench.py
Normal file
@@ -0,0 +1,189 @@
|
||||
"""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)
|
||||
294
tests/test_d2_misspec.py
Normal file
294
tests/test_d2_misspec.py
Normal file
@@ -0,0 +1,294 @@
|
||||
"""Misspecification parameters of the D2 generator (phase P6, item p6-gen; plan §12 item 22, decision 2).
|
||||
|
||||
The nominal path of ml_porosity/data/synth_d2.py must stay bit-identical to the generator used by protocol_p2 and
|
||||
protocol_p2r: tests/data/d2_fingerprints.json records SHA-256 fingerprints of the realization fields and of the
|
||||
observe() outputs, taken before the misspecification parameters were added. The other tests check that each axis
|
||||
changes only what it claims to change (common random numbers) and that the anchors stay consistent with the true warp.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import scipy
|
||||
import yaml
|
||||
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
|
||||
from ml_porosity.paths import REPO_ROOT, f3_root
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
P = yaml.safe_load(open(REPO_ROOT / "configs" / "protocol_p2r.yaml"))
|
||||
INP = P["inputs"]
|
||||
CFG = yaml.safe_load(open(REPO_ROOT / INP["d2_config"]["path"]))
|
||||
FP_PATH = REPO_ROOT / "tests" / "data" / "d2_fingerprints.json"
|
||||
NEEDED = [f3_root() / ".survey", REPO_ROOT / CFG["horizon_cache"], REPO_ROOT / INP["warp_prior"]["path"],
|
||||
REPO_ROOT / INP["wavelet"]["path"]]
|
||||
pytestmark = pytest.mark.skipif(not all(p.exists() for p in NEEDED), reason="missing D2 inputs (run scripts/09, 10)")
|
||||
|
||||
WELL_FIELDS = ("seis_clean", "noise_unit", "phi_t", "z_g", "z_b", "boundaries_t", "eps_a")
|
||||
OBS_KEYS = ("seis", "phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true")
|
||||
FP_RIDS = (900, 8, 902) # P2/P2r dev, first P2r main realization, first bench dev realization
|
||||
FP_DRIFT = (0.0, 1.0, 2.0)
|
||||
FP_SNR_DB, FP_SIGMA_A, FP_DENSITY = 10, 7.0, "full"
|
||||
|
||||
|
||||
def _sha(chunks) -> str:
|
||||
h = hashlib.sha256()
|
||||
for a in chunks:
|
||||
h.update(np.ascontiguousarray(np.asarray(a)).tobytes())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def fingerprint_wells(R) -> dict:
|
||||
return {k: _sha(getattr(w, k) for w in R.wells) for k in WELL_FIELDS}
|
||||
|
||||
|
||||
def fingerprint_obs(R, **kw) -> dict:
|
||||
wells = R.test + R.pool[:4]
|
||||
obs = [R.observe(w, c, FP_SNR_DB, FP_SIGMA_A, FP_DENSITY, **kw) for c in FP_DRIFT for w in wells]
|
||||
return {k: _sha(o[k] for o in obs) for k in OBS_KEYS}
|
||||
|
||||
|
||||
def fingerprint(R, **kw) -> dict:
|
||||
return {"wells": fingerprint_wells(R), "obs": fingerprint_obs(R, **kw)}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def make():
|
||||
hg = load_horizon_grid(CFG["horizons"], REPO_ROOT / CFG["horizon_cache"])
|
||||
prior = json.loads((REPO_ROOT / INP["warp_prior"]["path"]).read_text())["fits"][INP["warp_prior"]["fit"]]
|
||||
wav = np.load(REPO_ROOT / INP["wavelet"]["path"])[INP["wavelet"]["key"]]
|
||||
return lambda rid, **kw: D2Realization(CFG, rid, hg, WarpHyper(**prior["hyper"]), wav, **kw)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def recorded() -> dict:
|
||||
fp = json.loads(FP_PATH.read_text())
|
||||
env = fp["meta"]["env"]
|
||||
if (env["numpy"], env["scipy"]) != (np.__version__, scipy.__version__):
|
||||
pytest.skip(f"fingerprints recorded with numpy {env['numpy']} / scipy {env['scipy']}; "
|
||||
f"this environment has {np.__version__} / {scipy.__version__}")
|
||||
return fp
|
||||
|
||||
|
||||
def test_inputs_match_fingerprint_record(recorded):
|
||||
for key in ("d2_config", "warp_prior", "wavelet"):
|
||||
f = REPO_ROOT / INP[key]["path"]
|
||||
assert hashlib.sha256(f.read_bytes()).hexdigest() == recorded["meta"]["inputs"][key], key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rid", FP_RIDS)
|
||||
def test_default_path_matches_fingerprints(make, recorded, rid):
|
||||
"""Realizations and observations are bit-identical to the record taken before the misspec parameters existed."""
|
||||
fp = fingerprint(make(rid))
|
||||
for part in ("wells", "obs"):
|
||||
for k, v in recorded["realizations"][str(rid)][part].items():
|
||||
assert fp[part][k] == v, f"rid {rid}: {part}.{k} changed"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- bench config and preset validation
|
||||
|
||||
BENCH = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_bench.yaml").read_text())
|
||||
|
||||
|
||||
def test_d2_bench_generator_matches_p2r():
|
||||
"""configs/d2_synth_bench.yaml uses the protocol_p2r generator and regimes: only misspec_presets may be added."""
|
||||
from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec
|
||||
|
||||
p2r = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_p2r.yaml").read_text())
|
||||
bench = dict(BENCH)
|
||||
presets = bench.pop("misspec_presets")
|
||||
assert bench == p2r
|
||||
assert preset_misspec(BENCH, None) is None and preset_misspec(BENCH, "nominal") is None
|
||||
for name in presets:
|
||||
ms = normalize_misspec(preset_misspec(BENCH, name))
|
||||
assert ms["rock_physics"]["region"] == "all"
|
||||
with pytest.raises(KeyError):
|
||||
preset_misspec(BENCH, "no_such_preset")
|
||||
|
||||
|
||||
def test_normalize_misspec_rejects_unknown_keys():
|
||||
from ml_porosity.data.synth_d2 import MISSPEC_DEFAULTS, active_axes, normalize_misspec
|
||||
|
||||
assert normalize_misspec(None) == normalize_misspec({}) == MISSPEC_DEFAULTS
|
||||
assert active_axes(normalize_misspec({"wavelet": {"Q": None, "Q_t_ref_ms": 500.0}})) == {}
|
||||
assert active_axes(normalize_misspec({"drift": {"step_ms": 4.0}})) == {"drift": {"step_ms": 4.0}}
|
||||
for bad in ({"rockphysics": {}}, {"wavelet": {"Q_factor": 2.0}}, {"drift": {"ell_factor": 0.0}},
|
||||
{"rock_physics": {"region": "train"}}, {"wavelet": {"minphase_frac": 1.5}}):
|
||||
with pytest.raises(ValueError):
|
||||
normalize_misspec(bad)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- common random numbers and axis semantics
|
||||
|
||||
RID = 902
|
||||
C, SNR, SIGMA_A = 1.0, 10, 7.0
|
||||
CRN_FIELDS = ("phi_t", "noise_unit", "z_g", "z_b", "boundaries_t", "eps_a")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def R0(make):
|
||||
return make(RID)
|
||||
|
||||
|
||||
def _assert_crn(R, R0):
|
||||
"""Earth model, noise and standard-normal draws identical to the nominal realization."""
|
||||
for a, b in zip(R.wells, R0.wells):
|
||||
assert (a.name, a.il, a.xl) == (b.name, b.il, b.xl)
|
||||
for k in CRN_FIELDS:
|
||||
np.testing.assert_array_equal(getattr(a, k), getattr(b, k))
|
||||
|
||||
|
||||
def test_all_nominal_misspec_is_bit_identical(make, R0):
|
||||
explicit = {"rock_physics": {"dt_slope_factor": 1.0, "region": "all"}, "wavelet": {"Q": None},
|
||||
"drift": {"sigma_b_factor": 1.0, "step_ms": 0.0, "jitter_sd_ms": 0.0}}
|
||||
R = make(RID, misspec=explicit)
|
||||
assert R.misspec_active == {} and R.w_fine is R.w_fine_nominal and R.drift_true is R.drift
|
||||
assert fingerprint(R) == fingerprint(R0)
|
||||
|
||||
|
||||
def test_rock_physics_changes_seismic_only(make, R0):
|
||||
R = make(RID, misspec={"rock_physics": {"dt_slope_factor": 1.15, "unit_dt_intercept_sd": 0.05}})
|
||||
_assert_crn(R, R0)
|
||||
for w, w0 in zip(R.wells, R0.wells):
|
||||
assert not np.allclose(w.seis_clean, w0.seis_clean)
|
||||
o, o0 = (r.observe(x, C, SNR, SIGMA_A) for r, x in ((R, w), (R0, w0)))
|
||||
for k in ("phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true"):
|
||||
np.testing.assert_array_equal(o[k], o0[k]) # labels, anchors, warp: unchanged
|
||||
ai_true = R.ai_log_true(w, o)
|
||||
assert ai_true.shape == o["ai_log"].shape and not np.allclose(ai_true, o["ai_log"])
|
||||
np.testing.assert_array_equal(R0.ai_log_true(w0, o0), o0["ai_log"])
|
||||
# region: the perturbation acts on the named wells only
|
||||
Rt = make(RID, misspec={"rock_physics": {"unit_dt_intercept_sd": 0.05, "region": "test"}})
|
||||
for w, w0 in zip(Rt.pool, R0.pool):
|
||||
np.testing.assert_array_equal(w.seis_clean, w0.seis_clean)
|
||||
assert not np.allclose(Rt.test[0].seis_clean, R0.test[0].seis_clean)
|
||||
assert Rt.rp_applies("T00") and not Rt.rp_applies("P00")
|
||||
|
||||
|
||||
def test_rock_physics_uniform_error_is_near_affine(make):
|
||||
"""Uniform coefficient errors change ln AI almost affinely in φ over the D2 porosity range (15–20 % coefficient
|
||||
errors: 4 % of ln AI, of which < 1 % of the ln AI range is non-affine), so the profiled amplitude of the tie
|
||||
likelihood absorbs them; this is why the rp_* presets add per-unit scatter."""
|
||||
from ml_porosity.data.synth_d2 import phi_to_ai
|
||||
|
||||
phi = np.linspace(0.2, 0.43, 200)
|
||||
R = make(RID, misspec={"rock_physics": {"dt_slope_factor": 1.15, "dt_intercept_factor": 1.15,
|
||||
"rho_slope_factor": 1.2}})
|
||||
d = np.log(R.phi_to_ai_true(phi)) - np.log(phi_to_ai(phi))
|
||||
resid = d - np.polyval(np.polyfit(phi, d, 1), phi)
|
||||
assert np.abs(d).max() > 0.02 and np.abs(resid).max() < 0.01 * np.ptp(np.log(phi_to_ai(phi)))
|
||||
|
||||
|
||||
def test_wavelet_axis_changes_seismic_only(make, R0):
|
||||
from ml_porosity.data.wavelet import rotate_phase
|
||||
|
||||
cases = {"phase": {"phase_deg": 45.0}, "minphase": {"minphase_frac": 1.0}, "peak": {"peak_freq_factor": 1.2},
|
||||
"delay": {"delay_ms": 4.0}, "Q": {"Q": 80.0}}
|
||||
phases = np.arange(-180.0, 180.0, 1.0)
|
||||
for name, wv in cases.items():
|
||||
R = make(RID, misspec={"wavelet": wv})
|
||||
_assert_crn(R, R0)
|
||||
w, w0 = R.pool[0], R0.pool[0]
|
||||
assert not np.allclose(w.seis_clean, w0.seis_clean), name
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
for k in ("phi_log", "ai_log", "tau_k", "t_k", "t_of_tau_true", "y_true"):
|
||||
np.testing.assert_array_equal(o[k], o0[k])
|
||||
if name == "Q":
|
||||
assert R.w_fine is R.w_fine_nominal # stationary part nominal; Q acts in the forward
|
||||
k600, k1100 = R.true_wavelet_at(600.0), R.true_wavelet_at(1100.0)
|
||||
spec = lambda k: np.abs(np.fft.rfft(k, 4096))
|
||||
f = np.fft.rfftfreq(4096, 0.0005)
|
||||
hi = f > 50
|
||||
assert (spec(k1100)[hi] / spec(k1100).max()).sum() < (spec(k600)[hi] / spec(k600).max()).sum()
|
||||
else:
|
||||
cc = [np.corrcoef(rotate_phase(R.w_fine_nominal, p), R.w_fine)[0, 1] for p in phases]
|
||||
best = phases[int(np.argmax(cc))]
|
||||
if name == "phase":
|
||||
assert abs(best - 45.0) <= 1.0 and max(cc) > 0.999 # inside the constant-phase family
|
||||
if name == "minphase":
|
||||
assert max(cc) < 0.9 # not representable by a constant phase
|
||||
assert len(R.wavelet) == len(R0.wavelet) and len(R.w_fine) == len(R0.w_fine)
|
||||
|
||||
|
||||
def test_minimum_phase_keeps_amplitude_spectrum(R0):
|
||||
from ml_porosity.data.synth_d2 import fractional_minimum_phase
|
||||
|
||||
w = R0.w_fine_nominal
|
||||
for frac in (0.0, 0.5, 1.0):
|
||||
y = fractional_minimum_phase(w, frac)
|
||||
a, b = np.abs(np.fft.rfft(w, 4096)), np.abs(np.fft.rfft(y, 4096))
|
||||
band = a > 0.1 * a.max() # truncation to 128 ms only touches the band edges
|
||||
assert np.abs(b[band] / a[band] - 1.0).max() < 0.05, frac
|
||||
assert abs(np.sum(y**2) / np.sum(w**2) - 1.0) < 0.01, frac
|
||||
np.testing.assert_allclose(fractional_minimum_phase(w, 0.0), w, atol=1e-9)
|
||||
|
||||
|
||||
def test_drift_hyper_factors_use_common_random_numbers(make, R0):
|
||||
R = make(RID, misspec={"drift": {"sigma_b_factor": 3.0, "sigma_g_factor": 1.5}})
|
||||
_assert_crn(R, R0)
|
||||
for w, w0 in zip(R.pool[:3], R0.pool[:3]):
|
||||
np.testing.assert_array_equal(w.seis_clean, w0.seis_clean) # the seismic is untouched
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
assert o["b"] == pytest.approx(3.0 * o0["b"])
|
||||
m = C * R.drift.m_g
|
||||
np.testing.assert_allclose(o["g"] - m, 1.5 * (o0["g"] - m), atol=1e-12)
|
||||
np.testing.assert_array_equal(o["t_k"], o0["t_k"]) # picks keep their noise draws
|
||||
np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9)
|
||||
Rl = make(RID, misspec={"drift": {"ell_factor": 0.5}})
|
||||
assert Rl.drift_true.ell_ms == pytest.approx(0.5 * R0.drift.ell_ms) and Rl.Lg_true is not Rl.Lg
|
||||
|
||||
|
||||
def test_drift_step_is_exact_jump_below_horizon(make, R0):
|
||||
J, width = 8.0, 12.0
|
||||
R = make(RID, misspec={"drift": {"step_ms": J, "step_width_ms": width}})
|
||||
_assert_crn(R, R0)
|
||||
k = CFG["horizons"].index("Truncation")
|
||||
for w, w0 in zip(R.wells, R0.wells):
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
d = o["t_of_tau_true"] - o0["t_of_tau_true"]
|
||||
t_h = R.hg.at(w.il, w.xl)[k]
|
||||
tau_h = np.interp(t_h, o0["t_of_tau_true"], R.tau_fine)
|
||||
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
np.testing.assert_allclose(d[R.tau_fine < tau_h - R.grid.dtau], 0.0, atol=1e-9)
|
||||
np.testing.assert_allclose(d[R.tau_fine > tau_h + width + 2 * R.grid.dtau], J, atol=1e-9)
|
||||
np.testing.assert_allclose(R.grid.t_of_tau(o["b"], o["g"])[0], R.true_warp_grid(w, C), atol=1e-9)
|
||||
np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9)
|
||||
assert o["b"] == o0["b"] and np.count_nonzero(o["g"] != o0["g"]) == int(round(width / R.grid.dtau))
|
||||
Rn = make(RID, misspec={"drift": {"step_ms": -6.0}})
|
||||
o = Rn.observe(Rn.pool[0], C, SNR, SIGMA_A)
|
||||
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
|
||||
|
||||
def test_drift_jitter_is_high_frequency_and_monotone(make, R0):
|
||||
sd, ell = 1.0, 8.0
|
||||
R = make(RID, misspec={"drift": {"jitter_sd_ms": sd, "jitter_ell_ms": ell}})
|
||||
_assert_crn(R, R0)
|
||||
rms = []
|
||||
for w, w0 in zip(R.wells, R0.wells):
|
||||
o, o0 = R.observe(w, C, SNR, SIGMA_A), R0.observe(w0, C, SNR, SIGMA_A)
|
||||
d = o["t_of_tau_true"] - o0["t_of_tau_true"]
|
||||
assert np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
np.testing.assert_array_equal(o["g"], o0["g"]) # jitter is not folded into g
|
||||
np.testing.assert_allclose(np.interp(o["tau_k"], R.tau_fine, o["t_of_tau_true"]), w.boundaries_t, atol=1e-9)
|
||||
rms.append(np.sqrt(np.mean(d**2)))
|
||||
# decorrelates within a few ℓ: lag-40 ms autocorrelation small, lag-4 ms large
|
||||
g = np.interp(R.grid.tau, R.tau_fine, d)
|
||||
acf = lambda lag: np.corrcoef(g[:-lag], g[lag:])[0, 1]
|
||||
assert acf(1) > 0.5 and abs(acf(10)) < 0.4
|
||||
assert 0.5 * sd < np.mean(rms) < 1.5 * sd
|
||||
assert R.misspec_info["monotone_repairs"] == 0
|
||||
assert "z_jitter" in R.wells[0].extra and "z_jitter" not in R0.wells[0].extra
|
||||
|
||||
|
||||
def test_presets_build_and_report_active_axes(make, R0):
|
||||
from ml_porosity.data.synth_d2 import preset_misspec
|
||||
|
||||
for name in BENCH["misspec_presets"]:
|
||||
R = make(RID, misspec=preset_misspec(BENCH, name))
|
||||
_assert_crn(R, R0)
|
||||
axis = next(p for p in name.split("_") if p in ("rp", "wv", "dr")) # names: rp_L1, wv_Q, cand_dr_s, ...
|
||||
assert list(R.misspec_active) == [{"rp": "rock_physics", "wv": "wavelet", "dr": "drift"}[axis]]
|
||||
o = R.observe(R.pool[0], C, SNR, SIGMA_A)
|
||||
assert np.isfinite(o["seis"]).all() and np.all(np.diff(o["t_of_tau_true"]) > 0)
|
||||
Reference in New Issue
Block a user