Add P6 benchmark code, locked protocol_bench, T2 study
- 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>
This commit is contained in:
7
ml_porosity/benchmark/__init__.py
Normal file
7
ml_porosity/benchmark/__init__.py
Normal file
@@ -0,0 +1,7 @@
|
||||
"""protocol_bench (phase P6, level B): registration-aware synthetic benchmark on D2.
|
||||
|
||||
Studies (configs/protocol_bench.yaml, `studies:`): S1 grid fill, S2 misspecification axes, S3 anchor-free B4
|
||||
baselines under the P2r cells, S4 second backbone (TCN), S8 controlled cycle-skip (two-mode) regime. The modules
|
||||
mirror ml_porosity/volve (freeze/check/lock, fingerprinted resume) and scripts 14/15/18 (SMC posterior, training,
|
||||
summary) so that the default generator path reproduces protocol_p2r.
|
||||
"""
|
||||
153
ml_porosity/benchmark/cells.py
Normal file
153
ml_porosity/benchmark/cells.py
Normal file
@@ -0,0 +1,153 @@
|
||||
"""Cell enumeration and output paths of protocol_bench.
|
||||
|
||||
A cell is one (study, regime, preset, c, N, rid[, Δ]) with its method list, budgets and backbone. Paths are flat and
|
||||
deterministic. Posterior files follow the protocol_p2r layout (r{rid}_c{c}_n{N}_s{reg_seed}{.csv,_particles.npz,
|
||||
_phase.json}) so that scripts 15/18-style readers and the P2r reference share one reader.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from ml_porosity.paths import outputs_dir
|
||||
|
||||
P2R_GRID = {"drift_factors": (0.0, 1.0, 2.0), "n_train": (4, 16)}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Cell:
|
||||
study: str
|
||||
regime: str
|
||||
preset: str | None # misspecification preset of configs/d2_synth_bench.yaml (None: nominal)
|
||||
c: float
|
||||
n_train: int
|
||||
rid: int
|
||||
methods: tuple[str, ...]
|
||||
backbone: str = "cnngru" # cnngru (bank_train.train_predict, as P2r) | tcn (f3.training.TCNHetero)
|
||||
posterior: str = "bench" # bench (this protocol's SMC) | p2r (outputs/p2r/posterior) | none
|
||||
delta_ms: float | None = None # S8 two-mode separation
|
||||
tags: tuple[str, ...] = field(default_factory=tuple)
|
||||
|
||||
@property
|
||||
def setting(self) -> str:
|
||||
return self.regime if self.preset in (None, "nominal") else f"{self.regime}__{self.preset}"
|
||||
|
||||
@property
|
||||
def tag(self) -> str:
|
||||
t = f"r{self.rid}_c{self.c:g}_n{self.n_train}"
|
||||
if self.delta_ms is not None:
|
||||
t += f"_d{self.delta_ms:g}"
|
||||
return t
|
||||
|
||||
def suffix(self) -> str:
|
||||
return "" if self.backbone == "cnngru" else f"__{self.backbone}"
|
||||
|
||||
|
||||
def bench_root(dev: bool = False, repro: bool = False) -> Path:
|
||||
root = outputs_dir() / "bench"
|
||||
return root / ("repro" if repro else "dev" if dev else "")
|
||||
|
||||
|
||||
def posterior_dir(cell: Cell, root: Path) -> Path | None:
|
||||
if cell.posterior == "none":
|
||||
return None
|
||||
if cell.posterior == "p2r":
|
||||
return outputs_dir() / "p2r" / "posterior" / cell.regime
|
||||
return root / "posterior" / cell.setting # shared by every study that needs the same (regime, preset) posterior
|
||||
|
||||
|
||||
def posterior_paths(cell: Cell, root: Path, reg_seed: int) -> dict[str, Path]:
|
||||
d = posterior_dir(cell, root)
|
||||
tag = f"r{cell.rid}_c{cell.c:g}_n{cell.n_train}_s{reg_seed}"
|
||||
return {"csv": d / f"{tag}.csv", "particles": d / f"{tag}_particles.npz", "phase": d / f"{tag}_phase.json",
|
||||
"meta": d / f"{tag}.json"}
|
||||
|
||||
|
||||
def train_dir(cell: Cell, root: Path) -> Path:
|
||||
return root / cell.study.lower() / "train" / cell.setting / "cells"
|
||||
|
||||
|
||||
def train_paths(cell: Cell, root: Path) -> dict[str, Path]:
|
||||
d = train_dir(cell, root)
|
||||
stem = cell.tag + cell.suffix()
|
||||
return {"csv": d / f"{stem}.csv", "npz": d / f"{stem}.npz", "diag": d / f"{stem}_diag.csv", "meta": d / f"{stem}.json"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- study → cells
|
||||
|
||||
def _rids(p: dict, rids) -> list[int]:
|
||||
return [int(r) for r in (p["grid"]["realizations"] if rids is None else rids)]
|
||||
|
||||
|
||||
def _grid(s: dict, grid: dict | None) -> tuple[list, list]:
|
||||
g = grid or {}
|
||||
return list(g.get("drift_factors") or s.get("drift_factors", [])), list(g.get("n_train") or s["n_train"])
|
||||
|
||||
|
||||
def s1_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
"""grid: dev-only override {drift_factors, n_train}; with an override the P2r-grid exclusion is lifted."""
|
||||
s = p["studies"]["S1"]
|
||||
cs, ns = _grid(s, grid)
|
||||
cells = []
|
||||
for reg in (regimes or s["regimes"]):
|
||||
for c, N in itertools.product(cs, ns):
|
||||
if grid is None and float(c) in P2R_GRID["drift_factors"] and int(N) in P2R_GRID["n_train"]:
|
||||
continue # existing protocol_p2r cell: read, not recomputed
|
||||
for rid in _rids(p, rids):
|
||||
cells.append(Cell("S1", reg, None, float(c), int(N), rid, tuple(s["methods"])))
|
||||
return cells
|
||||
|
||||
|
||||
def s2_cells(p: dict, rids=None, regimes=None, presets=None, controls: bool = False, grid: dict | None = None) -> list[Cell]:
|
||||
s = p["studies"]["S2"]
|
||||
names = presets or [name for axis in s["presets"].values() for name in axis]
|
||||
if controls:
|
||||
names = list(names) + list(s.get("controls", {}).get("presets", []))
|
||||
cs, ns0 = _grid(s, grid)
|
||||
cells = []
|
||||
for reg in (regimes or s["regimes"]):
|
||||
for name in names:
|
||||
ns = ns0 if (grid or name not in s.get("controls", {}).get("presets", [])) else s["controls"]["n_train"]
|
||||
for c, N in itertools.product(cs, ns):
|
||||
for rid in _rids(p, rids):
|
||||
cells.append(Cell("S2", reg, name, float(c), int(N), rid, tuple(s["methods"])))
|
||||
return cells
|
||||
|
||||
|
||||
def s3_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
s = p["studies"]["S3"]
|
||||
cs, ns = _grid(s, grid)
|
||||
post = "bench" if grid is not None else s.get("posterior", "none") # dev override: dev posteriors of the setting
|
||||
return [Cell("S3", reg, None, float(c), int(N), rid, tuple(s["methods"]), posterior=post)
|
||||
for reg in (regimes or s["regimes"]) for c, N in itertools.product(cs, ns) for rid in _rids(p, rids)]
|
||||
|
||||
|
||||
def s4_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
"""Dev override: posterior 'bench' (dev posteriors of the same setting) instead of the P2r particles."""
|
||||
s = p["studies"]["S4"]
|
||||
ns = _grid(s, grid)[1]
|
||||
return [Cell("S4", cell["regime"], None, float(cell["c"]), int(N), rid, tuple(s["methods"]), backbone=s["backbone"],
|
||||
posterior="bench" if grid is not None else s["posterior"])
|
||||
for cell in s["cells"] if regimes is None or cell["regime"] in regimes
|
||||
for N in ns for rid in _rids(p, rids)]
|
||||
|
||||
|
||||
def s8_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
|
||||
s = p["studies"]["S8"]
|
||||
cs, ns = _grid(s, grid)
|
||||
return [Cell("S8", reg, None, float(c), int(N), rid, tuple(s["methods"]), posterior="none", delta_ms=float(d))
|
||||
for reg in (regimes or s["regimes"]) for d in s["delta_ms"]
|
||||
for c, N in itertools.product(cs, ns) for rid in _rids(p, rids)]
|
||||
|
||||
|
||||
STUDIES = {"S1": s1_cells, "S2": s2_cells, "S3": s3_cells, "S4": s4_cells, "S8": s8_cells}
|
||||
|
||||
|
||||
def study_cells(p: dict, study: str, rids=None, regimes=None, **kw) -> list[Cell]:
|
||||
return STUDIES[study](p, rids=rids, regimes=regimes, **kw)
|
||||
|
||||
|
||||
def needs_posterior(cell: Cell) -> bool:
|
||||
return cell.posterior == "bench"
|
||||
90
ml_porosity/benchmark/data.py
Normal file
90
ml_porosity/benchmark/data.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""Inputs of protocol_bench: generator configuration, horizon grid, warp prior, wavelet, and the registration /
|
||||
training / metric blocks of protocol_p2 (the same objects scripts 11/14/15 build), plus the realization builder with
|
||||
misspecification presets and the nominal-fingerprint helper of tests/test_d2_misspec.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.benchmark.protocol import generator_config, protocol_p2
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid, preset_misspec
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
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_DRIFT, FP_SNR_DB, FP_SIGMA_A, FP_DENSITY = (0.0, 1.0, 2.0), 10, 7.0, "full"
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def load_script(name: str):
|
||||
"""scripts/<name> as a module (scripts 11's reg_settings / method_specs / evaluate are the P2r semantics)."""
|
||||
spec = importlib.util.spec_from_file_location("bench_" + name[:2], REPO_ROOT / "scripts" / name)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
@dataclass
|
||||
class Inputs:
|
||||
p: dict
|
||||
cfg: dict
|
||||
hg: object
|
||||
prior_hyper: dict
|
||||
wav: np.ndarray
|
||||
P2: dict
|
||||
reg: dict
|
||||
tcfg: dict
|
||||
f_c: float
|
||||
|
||||
def realization(self, rid: int, preset: str | None) -> D2Realization:
|
||||
return D2Realization(self.cfg, int(rid), self.hg, WarpHyper(**self.prior_hyper), self.wav,
|
||||
misspec=preset_misspec(self.cfg, preset))
|
||||
|
||||
def regime(self, name: str) -> dict:
|
||||
return dict(self.cfg["regimes"][name])
|
||||
|
||||
@property
|
||||
def sigma_a(self) -> float:
|
||||
return float(self.cfg["anchors"]["sigma_a_ms"])
|
||||
|
||||
def observe(self, R: D2Realization, c: float, regime: str, N: int) -> tuple[list[dict], list[dict]]:
|
||||
"""Training observations (first N pool wells, regime anchors) and the 8 test wells (full anchors, same SNR),
|
||||
exactly as scripts 14/15."""
|
||||
st = self.regime(regime)
|
||||
obs = [R.observe(w, c, st["snr_db"], self.sigma_a, st["anchor_density"]) for w in R.pool[:N]]
|
||||
test = [R.observe(w, c, st["snr_db"], self.sigma_a) for w in R.test]
|
||||
return obs, test
|
||||
|
||||
|
||||
def load_inputs(p: dict) -> Inputs:
|
||||
cfg = generator_config(p)
|
||||
P2 = protocol_p2(p)
|
||||
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
|
||||
wp = p["inputs"]["warp_prior"]
|
||||
prior = json.loads((REPO_ROOT / wp["path"]).read_text())["fits"][wp["fit"]]
|
||||
wav = np.load(REPO_ROOT / p["inputs"]["wavelet"]["path"])[p["inputs"]["wavelet"]["key"]]
|
||||
run_d2 = load_script("11_run_d2.py")
|
||||
return Inputs(p, cfg, hg, prior["hyper"], wav, P2, run_d2.reg_settings(P2),
|
||||
P2["training"]["model"] | P2["training"]["optimizer"], float(P2["metrics"]["bands"]["f_c_hz"]))
|
||||
|
||||
|
||||
def _sha(chunks) -> str:
|
||||
h = hashlib.sha256()
|
||||
for a in chunks:
|
||||
h.update(np.ascontiguousarray(np.asarray(a)).tobytes())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def fingerprint_realization(R: D2Realization) -> dict:
|
||||
"""{"wells": {field: sha}, "obs": {key: sha}} as tests/test_d2_misspec.py records them."""
|
||||
wells = R.test + R.pool[:4]
|
||||
obs = [R.observe(w, c, FP_SNR_DB, FP_SIGMA_A, FP_DENSITY) for c in FP_DRIFT for w in wells]
|
||||
return {"wells": {k: _sha(getattr(w, k) for w in R.wells) for k in WELL_FIELDS},
|
||||
"obs": {k: _sha(o[k] for o in obs) for k in OBS_KEYS}}
|
||||
73
ml_porosity/benchmark/devbudgets.py
Normal file
73
ml_porosity/benchmark/devbudgets.py
Normal file
@@ -0,0 +1,73 @@
|
||||
"""S4 TCN budgets on dev realizations (protocol_p2 budget_selection rule applied to the TCN backbone).
|
||||
|
||||
Every S4 method is trained with the TCN at every candidate budget (one trajectory per seed) on dev realizations
|
||||
902–905 at R10, c = 1, N ∈ {4, 16}, seeds 0–1; per method the budget with the smallest mean total RMSE (macro over
|
||||
test wells → mean over rid × N × seed) is selected. The dev SMC posteriors of those cells are produced by the
|
||||
ordinary posterior stage (outputs/bench/dev/posterior/R10). Output: outputs/bench/dev/budgets_tcn.json; the chosen
|
||||
values are copied into protocol_bench.yaml training.budgets_tcn before the lock.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell, bench_root, posterior_paths, train_paths
|
||||
from ml_porosity.benchmark.protocol import check_rids, dev_stamp, fingerprint
|
||||
from ml_porosity.benchmark.runner import cell_from, make_jobs, posterior_worker, run_jobs
|
||||
from ml_porosity.f3.progress import write_json
|
||||
|
||||
DEV_RIDS = (902, 903, 904, 905)
|
||||
DEV_SEEDS = (0, 1)
|
||||
|
||||
|
||||
def dev_budget_worker(job: dict) -> dict:
|
||||
import torch
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.training import train_cell
|
||||
|
||||
torch.set_num_threads(job["threads"])
|
||||
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
|
||||
paths = train_paths(cell, root)
|
||||
if paths["meta"].exists() and json.loads(paths["meta"].read_text()).get("fingerprint") == job["key"]:
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
cand = [int(b) for b in p["training"]["budget_candidates"]]
|
||||
post = posterior_paths(cell, root, int(p["registration"]["reg_seed"]))
|
||||
rows, diag, _, meta = train_cell(cell, p, load_inputs(p), job["device"], post, save_preds=False, seeds=job["seeds"],
|
||||
budget_lists={m.removesuffix("-TCN"): cand for m in cell.methods})
|
||||
paths["csv"].parent.mkdir(parents=True, exist_ok=True)
|
||||
pd.DataFrame(diag).to_csv(paths["diag"], index=False)
|
||||
pd.DataFrame(rows).to_csv(paths["csv"], index=False)
|
||||
write_json(paths["meta"], meta | {"fingerprint": job["key"], "candidates": cand, "cell": dataclasses.asdict(cell)})
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
def dev_budgets(p: dict, device: str, workers: int, mem_gb: float, threads: int, rids=None) -> dict:
|
||||
rids = [int(r) for r in (rids or DEV_RIDS)]
|
||||
check_rids(rids, p, dev=True)
|
||||
s4, root, stamp = p["studies"]["S4"], bench_root(dev=True), dev_stamp(p)
|
||||
cells = [Cell("S4", "R10", None, 1.0, int(N), rid, tuple(s4["methods"]), backbone=s4["backbone"], posterior="bench")
|
||||
for N in s4["n_train"] for rid in rids]
|
||||
run_jobs(make_jobs(p, cells, "posterior", stamp, root, device, mem_gb, threads), posterior_worker, workers, root,
|
||||
"posterior:dev-budgets")
|
||||
jobs = []
|
||||
for c in cells:
|
||||
settings = dict(stage="dev-budgets", setting=c.setting, misspec=None, rid=c.rid, c=c.c, n_train=c.n_train, methods=list(c.methods),
|
||||
backbone=c.backbone, candidates=list(p["training"]["budget_candidates"]), seeds=list(DEV_SEEDS))
|
||||
jobs.append(dict(p=p, cell=dataclasses.asdict(c), root=str(root), device=device, mem_gb=mem_gb, threads=threads,
|
||||
seeds=list(DEV_SEEDS), key=fingerprint(stamp, **settings)))
|
||||
jobs.sort(key=lambda j: -j["cell"]["n_train"])
|
||||
run_jobs(jobs, dev_budget_worker, workers, root, "train:dev-budgets")
|
||||
df = pd.concat([pd.read_csv(train_paths(cell_from(j["cell"]), root)["csv"]) for j in jobs], ignore_index=True)
|
||||
run = df.groupby(["method", "budget", "rid", "n_train", "seed"])["rmse"].mean().groupby(["method", "budget"]).mean()
|
||||
chosen = {m.removesuffix("-TCN"): int(run.loc[m].idxmin()) for m in run.index.get_level_values(0).unique()}
|
||||
table = run.unstack("budget")
|
||||
out = {"rule": "protocol_p2 budget_selection (lowest mean total RMSE at c = 1 over dev rid × N × seed) applied to the TCN backbone",
|
||||
"rids": rids, "seeds": list(DEV_SEEDS), "candidates": list(p["training"]["budget_candidates"]), "budgets_tcn": chosen,
|
||||
"mean_total_rmse": {m: {int(b): float(v) for b, v in r.items()} for m, r in table.iterrows()}}
|
||||
(root / "budgets_tcn.json").write_text(json.dumps(out, indent=1))
|
||||
print(table.round(4).to_string())
|
||||
return out
|
||||
196
ml_porosity/benchmark/protocol.py
Normal file
196
ml_porosity/benchmark/protocol.py
Normal file
@@ -0,0 +1,196 @@
|
||||
"""Protocol loading, locking and realization guards for protocol_bench.
|
||||
|
||||
The lock (configs/protocol_bench.lock.json + .sha256) records the protocol text, the code (ml_porosity/**/*.py, the
|
||||
bench scripts, pyproject.toml), the environment, every hash-listed input, the protocol_p2r artifacts that S2/S4 read,
|
||||
and the nominal generator fingerprints of two realizations. Main realizations 8–15 are refused unless the lock exists
|
||||
and matches; dev realizations 900–905 never need the lock; the protocol_p2 realizations 0–7 are always refused.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from ml_porosity.f3.protocol import digest, environment
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
__all__ = ["CONFIG", "LOCK", "check_rids", "current_stamp", "dev_stamp", "fingerprint", "freeze", "load_protocol",
|
||||
"protocol_p2", "protocol_p2r", "generator_config"]
|
||||
|
||||
CONFIG = REPO_ROOT / "configs/protocol_bench.yaml"
|
||||
LOCK = REPO_ROOT / "configs/protocol_bench.lock.json"
|
||||
SCRIPTS = ("scripts/34_run_bench.py", "scripts/run_bench.sh")
|
||||
RESULT_DIRS = ("s1", "s2", "s3", "s4", "s8", "summary")
|
||||
|
||||
|
||||
def load_protocol(check_inputs: bool = True) -> dict:
|
||||
p = yaml.safe_load(CONFIG.read_text(encoding="utf-8"))
|
||||
if check_inputs:
|
||||
for k, v in p["inputs"].items():
|
||||
f = REPO_ROOT / v["path"]
|
||||
if not f.exists():
|
||||
raise FileNotFoundError(f"protocol_bench input {k} missing: {v['path']} (sync outputs/ first)")
|
||||
h = digest(f, text=f.suffix in (".yaml", ".json"))
|
||||
if v.get("sha256") not in (None, "TBD") and h != v["sha256"]:
|
||||
raise RuntimeError(f"{v['path']} differs from the hash recorded in protocol_bench ({h[:12]} ≠ {v['sha256'][:12]})")
|
||||
from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec
|
||||
cfg = generator_config(p)
|
||||
for name, spec in (p.get("calibration", {}).get("chosen") or {}).items():
|
||||
if normalize_misspec(spec) != normalize_misspec(preset_misspec(cfg, name)):
|
||||
raise RuntimeError(f"preset {name} in {p['inputs']['d2_config']['path']} differs from calibration.chosen of protocol_bench")
|
||||
return p
|
||||
|
||||
|
||||
def generator_config(p: dict) -> dict:
|
||||
return yaml.safe_load((REPO_ROOT / p["inputs"]["d2_config"]["path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def protocol_p2(p: dict) -> dict:
|
||||
"""protocol_p2: source of the registration, training and metric blocks (as scripts 14/15 use it)."""
|
||||
return yaml.safe_load((REPO_ROOT / p["inputs"]["protocol_p2"]["path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def protocol_p2r(p: dict) -> dict:
|
||||
return yaml.safe_load((REPO_ROOT / p["inputs"]["protocol_p2r"]["path"]).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def code_files() -> list[Path]:
|
||||
paths = sorted((REPO_ROOT / "ml_porosity").rglob("*.py"))
|
||||
paths += [REPO_ROOT / s for s in SCRIPTS if (REPO_ROOT / s).exists()]
|
||||
return paths + [REPO_ROOT / "pyproject.toml"]
|
||||
|
||||
|
||||
def source_hash() -> str:
|
||||
h = hashlib.sha256()
|
||||
for f in code_files():
|
||||
h.update(f.relative_to(REPO_ROOT).as_posix().encode() + b"\0")
|
||||
h.update(f.read_bytes().replace(b"\r\n", b"\n") + b"\0")
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def p2r_reference_files(p: dict) -> list[Path]:
|
||||
"""protocol_p2r artifacts the benchmark reads: SMC particles and phase of the S4 cells, the per-regime runs.csv
|
||||
(S1 grid, S2 nominal reference, S3 join) and sigma_post.csv."""
|
||||
root = outputs_dir() / "p2r"
|
||||
ref = p["reference"]["p2r"]
|
||||
files = [root / "summary" / "sigma_post.csv"]
|
||||
files += [root / "train" / reg / "runs.csv" for reg in ref["regimes"]]
|
||||
for cell in p["studies"]["S4"]["cells"]:
|
||||
for N in p["studies"]["S4"]["n_train"]:
|
||||
for rid in p["grid"]["realizations"]:
|
||||
tag = f"r{rid}_c{cell['c']:g}_n{N}_s{p['registration']['reg_seed']}"
|
||||
files += [root / "posterior" / cell["regime"] / f"{tag}_particles.npz",
|
||||
root / "posterior" / cell["regime"] / f"{tag}_phase.json"]
|
||||
return files
|
||||
|
||||
|
||||
def portable(path: Path) -> str:
|
||||
path = path.resolve()
|
||||
for prefix, base in (("outputs", outputs_dir()), ("repo", REPO_ROOT)):
|
||||
try:
|
||||
return f"{prefix}:{path.relative_to(base.resolve()).as_posix()}"
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError(f"input outside the repository and outputs roots: {path}")
|
||||
|
||||
|
||||
def nominal_fingerprints(p: dict) -> dict:
|
||||
"""Recompute the nominal generator fingerprints of the realizations listed in the protocol and compare them with
|
||||
tests/data/d2_fingerprints.json (recorded before the misspecification parameters were added)."""
|
||||
from ml_porosity.benchmark.data import fingerprint_realization, load_inputs
|
||||
|
||||
inp = load_inputs(p)
|
||||
stored = json.loads((REPO_ROOT / p["inputs"]["fingerprints"]["path"]).read_text(encoding="utf-8"))
|
||||
out = {}
|
||||
for rid in p["reference"]["fingerprint_rids"]:
|
||||
fp = fingerprint_realization(inp.realization(rid, None))
|
||||
ref = stored["realizations"][str(rid)]
|
||||
ok = all(ref[block].get(k) == v for block, d in fp.items() for k, v in d.items() if k in ref[block])
|
||||
out[str(rid)] = {"match": bool(ok), "sha256_of_fingerprint": hashlib.sha256(json.dumps(fp, sort_keys=True).encode()).hexdigest()}
|
||||
if not ok:
|
||||
raise RuntimeError(f"nominal generator fingerprint of realization {rid} differs from tests/data/d2_fingerprints.json")
|
||||
return out
|
||||
|
||||
|
||||
def current_stamp(p: dict | None = None, with_fingerprints: bool = True) -> dict:
|
||||
p = load_protocol() if p is None else p
|
||||
inputs = {k: REPO_ROOT / v["path"] for k, v in p["inputs"].items()}
|
||||
refs = p2r_reference_files(p)
|
||||
missing = [f for f in list(inputs.values()) + refs if not f.exists()]
|
||||
if missing:
|
||||
raise FileNotFoundError(f"protocol_bench inputs missing (sync outputs/ first): {[str(f) for f in missing[:5]]}"
|
||||
f"{' ...' if len(missing) > 5 else ''}")
|
||||
stamp = {"protocol_sha256": digest(CONFIG, True), "code_sha256": source_hash(), "environment": environment(),
|
||||
"inputs": {portable(f): digest(f, f.suffix in (".yaml", ".json")) for f in inputs.values()},
|
||||
"p2r_reference": {portable(f): digest(f, f.suffix == ".json") for f in refs}}
|
||||
if with_fingerprints:
|
||||
stamp["nominal_fingerprints"] = nominal_fingerprints(p)
|
||||
return stamp
|
||||
|
||||
|
||||
def freeze(check: bool = False) -> dict:
|
||||
"""Return the lock; create it if absent and check is False. Any difference from an existing lock is an error."""
|
||||
p = load_protocol()
|
||||
stamp = current_stamp(p)
|
||||
if LOCK.exists():
|
||||
old = json.loads(LOCK.read_text(encoding="utf-8"))
|
||||
for k, v in stamp.items():
|
||||
if old[k] != v:
|
||||
raise RuntimeError(f"protocol_bench lock mismatch: {k}. Preserve results and create a new protocol version.")
|
||||
return old
|
||||
if check:
|
||||
raise RuntimeError("protocol_bench is not locked. Run the lock stage before any main-grid run.")
|
||||
if any((outputs_dir() / "bench" / d).exists() for d in RESULT_DIRS):
|
||||
raise RuntimeError("Refusing a first lock after protocol_bench results already exist.")
|
||||
if any(v.get("sha256") in (None, "TBD") for v in p["inputs"].values()):
|
||||
raise RuntimeError("protocol_bench.yaml has an input without a recorded sha256 (TBD): fill it before locking.")
|
||||
if p.get("status", "").upper().startswith("DRAFT"):
|
||||
raise RuntimeError("protocol_bench.yaml still says DRAFT: set status to LOCKED (with the date) before locking.")
|
||||
stamp |= {"locked_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"canonical_text": "UTF-8, CRLF normalized to LF for code, protocol and text inputs; binary inputs exact",
|
||||
"studies": sorted(p["studies"]), "realizations": p["grid"]["realizations"]}
|
||||
LOCK.write_text(json.dumps(stamp, indent=2), encoding="utf-8")
|
||||
CONFIG.with_suffix(".sha256").write_text(stamp["protocol_sha256"] + " configs/protocol_bench.yaml\n", encoding="utf-8")
|
||||
return stamp
|
||||
|
||||
|
||||
def dev_stamp(p: dict) -> dict:
|
||||
"""Resume key for dev and repro runs: the nominal generator (configuration without the preset block) and the
|
||||
registration block only; the misspecification preset enters the job settings as its normalised dict. Code and
|
||||
protocol edits during dev therefore do not invalidate the cache (dev outputs are never results)."""
|
||||
cfg = {k: v for k, v in generator_config(p).items() if k != "misspec_presets"}
|
||||
return {"dev": True, "generator_nominal_sha256": hashlib.sha256(json.dumps(cfg, sort_keys=True, default=str).encode()).hexdigest(),
|
||||
"registration": p["registration"]}
|
||||
|
||||
|
||||
def fingerprint(stamp: dict, **settings) -> str:
|
||||
return hashlib.sha256(json.dumps({"lock": stamp, **settings}, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def check_rids(rids, p: dict, dev: bool, repro: bool = False) -> None:
|
||||
"""Main realizations only under the lock; dev realizations only with dev=True; protocol_p2 realizations never;
|
||||
no mixing. repro: the single reproduction cell (reproduction.rid) is allowed without the lock."""
|
||||
rids = sorted(set(int(r) for r in rids))
|
||||
p2 = protocol_p2(p)["grid"]
|
||||
if bad := sorted(set(rids) & set(p2["realizations"])):
|
||||
raise SystemExit(f"realizations {bad} belong to the protocol_p2 main grid and are never used by protocol_bench")
|
||||
main, devs = set(p["grid"]["realizations"]), set(p["grid"]["dev_realizations"])
|
||||
if set(rids) & main and set(rids) & devs:
|
||||
raise SystemExit("do not mix main-grid and dev realizations in one run")
|
||||
if unknown := sorted(set(rids) - main - devs):
|
||||
raise SystemExit(f"realizations {unknown} are neither main-grid nor dev realizations of protocol_bench")
|
||||
if dev:
|
||||
if set(rids) & main:
|
||||
raise SystemExit("--dev runs use dev realizations 900–905 only")
|
||||
return
|
||||
if repro:
|
||||
if rids != [int(p["reproduction"]["rid"])]:
|
||||
raise SystemExit("the reproduction stage runs the single cell of protocol_bench reproduction:")
|
||||
return
|
||||
if set(rids) & devs:
|
||||
raise SystemExit("dev realizations require --dev (outputs go to outputs/bench/dev)")
|
||||
freeze(check=True)
|
||||
111
ml_porosity/benchmark/registration.py
Normal file
111
ml_porosity/benchmark/registration.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""SMC tie posterior of one cell: the computation of scripts/14_diag_posterior.py run_job restricted to the arm
|
||||
protocol_p2r used (statistical wavelet with the re-estimated phase, "estR"), with the same random streams
|
||||
(anchor samples [k, i, 13], phase fit [k, 19], SMC [k, i, 17]) and the same γ checkpoints (g_old, g_acf, g_one), so
|
||||
that the default generator reproduces the protocol_p2r particles. Only the γ = 1/κ (g_acf) particles are stored.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
OLD = ["B3b", "B3c", "B3d", "M1", "M2"]
|
||||
CHECKPOINTS = ("g_old", "g_acf", "g_one")
|
||||
|
||||
|
||||
def posterior_cell(R, inp, obs: list[dict], c: float, N: int, regime: dict, reg_seed: int, smc_seed: int,
|
||||
particles: int, device: str, mem_gb: float, paths: dict[str, Path], save=("estR/g_acf",),
|
||||
checkpoints=CHECKPOINTS, extra_meta: dict | None = None, phase_kw: dict | None = None) -> pd.DataFrame:
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.registration.pipeline import register
|
||||
from ml_porosity.registration.sampler import sample_warps
|
||||
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet, residual_kappa
|
||||
from ml_porosity.registration.tie_likelihood import synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors
|
||||
from ml_porosity.registration.warp_prior import WarpHyper
|
||||
|
||||
reg, cfg = dict(inp.reg), inp.cfg
|
||||
k = smc_seed
|
||||
mm = (R.t_ext >= R.t_main[0]) & (R.t_ext <= R.t_main[-1])
|
||||
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
|
||||
if device == "cpu":
|
||||
from ml_porosity.registration.smc import smc_fit_phase, smc_tie_posterior
|
||||
wrap = lambda T: T
|
||||
else:
|
||||
import torch
|
||||
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
|
||||
dev = torch.device(device)
|
||||
if dev.type == "cuda": # shared GPU: exceeding the cap makes this job OOM rather than encroach on others
|
||||
total = torch.cuda.get_device_properties(dev).total_memory
|
||||
torch.cuda.set_per_process_memory_fraction(min(1.0, mem_gb * 2**30 / total), dev)
|
||||
wrap = lambda T: TiePosteriorTorch(T, device)
|
||||
|
||||
t_all = time.time()
|
||||
out = register(R, obs, reg, reg_seed)
|
||||
h = WarpHyper(**out["hyper"])
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
B = phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), int(round(R.dt / cfg["fine_dt_ms"])))
|
||||
Ts, Z0s = [], []
|
||||
for i, o in enumerate(obs):
|
||||
smp = sample_warps(R.grid, h, o["tau_k"], o["t_k"], particles, reg["g_max"], np.random.default_rng([k, i, 13]))
|
||||
Ts.append(wrap(TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine,
|
||||
R.t_ext, phase_wavelet(B, out["phase"]), seis[i], (R.t_main[0], R.t_main[-1]))))
|
||||
Z0s.append(Ts[-1].z(smp["u"]))
|
||||
t0 = time.time()
|
||||
phase_r, ph = smc_fit_phase(Ts, Z0s, B, out["phase"], [k, 19], **(phase_kw or {}))
|
||||
key = dict(rid=R.rid, c=c, n_train=N, seed=reg_seed, smc_seed=k, particles=particles, snr_db=regime["snr_db"],
|
||||
anchor_density=regime["anchor_density"], sigma_a_reg=reg["sigma_a_ms"], phase=out["phase"],
|
||||
phase_R=phase_r, phase_n=len(ph["phases"]), phase_edge=ph["edge"], phase_time_s=time.time() - t0)
|
||||
wavelets = {"estR": phase_wavelet(B, phase_r)}
|
||||
rows, saved = [], {}
|
||||
for i, o in enumerate(obs):
|
||||
d = out["diag"][i]
|
||||
for m in OLD:
|
||||
e = {kk.removeprefix(f"{m}_"): v for kk, v in d.items() if kk.startswith(f"{m}_warp")}
|
||||
rows.append(key | {"well": o["name"], "method": m, "wavelet": "est",
|
||||
"gamma": d["gamma"] if m == "M2" else np.nan} | e)
|
||||
ut = np.concatenate([[o["b"]], o["g"]])[None]
|
||||
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
|
||||
for wn, wf in wavelets.items():
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wf)[0]
|
||||
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
rows.append(key | {"well": o["name"], "method": "B3c", "wavelet": wn}
|
||||
| warp_errors(t3c[None], R.tau_fine, o["t_of_tau_true"], R.t_main))
|
||||
T = Ts[i].with_wavelet(wf)
|
||||
_, l0 = T.parts(Z0s[i])
|
||||
cks_all = {"g_old": d["gamma"], "g_acf": gamma_acf(T, Z0s[i], l0), "g_one": 1.0}
|
||||
cks = {n: cks_all[n] for n in checkpoints}
|
||||
t0, T.n_eval = time.time(), 0
|
||||
res = smc_tie_posterior(T, Z0s[i], cks.values(), np.random.default_rng([k, i, 17]))
|
||||
sg = pd.DataFrame(res["stages"])
|
||||
info = {"well": o["name"], "wavelet": wn, "kappa0": 1.0 / cks_all["g_acf"], "ll_true": float(T.loglik(ut)[0]),
|
||||
"ll_anchor_max": float(l0.max()), "n_stages": len(sg), "n_eval": T.n_eval,
|
||||
"time_s": time.time() - t0, "shrink_mean": float(sg["shrink"].mean()),
|
||||
"jump_z_min": float(sg["jump_z"].min()), "r_true": ncc(T.synth(ut)[0], seis[i])}
|
||||
for name, gk in cks.items():
|
||||
U = T.u(res["Z"][float(gk)])
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
|
||||
e = warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)
|
||||
syn_m = T.synth(U.mean(0)[None])[0]
|
||||
rows.append(key | info | {"method": f"SMC_{name}", "gamma": gk, "logZ": res["logZ"][float(gk)],
|
||||
"ll_max": float(res["ll"][float(gk)].max()),
|
||||
"ll_mean": float(res["ll"][float(gk)].mean()),
|
||||
"kappa_post": residual_kappa(syn_m, seis[i]), "r_post": ncc(syn_m, seis[i])} | e)
|
||||
if f"{wn}/{name}" in save:
|
||||
saved[f"{o['name']}/{wn}/{name}"] = U.astype(np.float32)
|
||||
paths["phase"].parent.mkdir(parents=True, exist_ok=True)
|
||||
paths["phase"].write_text(json.dumps({"phase0": out["phase"], "phase_R": phase_r} | ph))
|
||||
tmp = paths["particles"].with_suffix(".tmp.npz")
|
||||
np.savez_compressed(tmp, **saved)
|
||||
tmp.replace(paths["particles"])
|
||||
df = pd.DataFrame(rows)
|
||||
df.to_csv(paths["csv"], index=False)
|
||||
meta = {"wall_seconds": time.time() - t_all, "device": device, "particles": particles, "phase0": out["phase"],
|
||||
"phase_R": phase_r, "misspec_active": R.misspec_active, "monotone_repairs": R.misspec_info["monotone_repairs"],
|
||||
"hyper": out["hyper"], "lam": out["lam"], "tau_c": out["tau_c"], "checkpoints": list(checkpoints),
|
||||
"saved": sorted(saved)} | (extra_meta or {})
|
||||
return df, meta
|
||||
74
ml_porosity/benchmark/repro.py
Normal file
74
ml_porosity/benchmark/repro.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""P2r reproduction check: compare the reproduction cell of protocol_bench (outputs/bench/repro) with the stored
|
||||
protocol_p2r artifacts. The P2r guard hashes no code, so this comparison is the evidence that the runner's default
|
||||
path (generator, registration, SMC, label banks, training) is the one that produced outputs/p2r."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell, bench_root, posterior_paths, train_paths
|
||||
from ml_porosity.f3.progress import write_json
|
||||
from ml_porosity.paths import outputs_dir
|
||||
|
||||
|
||||
def _max_abs(a, b) -> float:
|
||||
a, b = np.asarray(a, float), np.asarray(b, float)
|
||||
return float(np.nanmax(np.abs(a - b))) if a.shape == b.shape else float("inf")
|
||||
|
||||
|
||||
def compare(p: dict) -> dict:
|
||||
rp = p["reproduction"]
|
||||
cell = Cell("S1", rp["regime"], None, float(rp["c"]), int(rp["n_train"]), int(rp["rid"]), tuple(rp["methods"]))
|
||||
root = bench_root(repro=True)
|
||||
reg_seed = int(p["registration"]["reg_seed"])
|
||||
new, ref = posterior_paths(cell, root, reg_seed), {}
|
||||
tag = f"r{cell.rid}_c{cell.c:g}_n{cell.n_train}_s{reg_seed}"
|
||||
p2r = outputs_dir() / "p2r"
|
||||
ref = {"csv": p2r / "posterior" / cell.regime / f"{tag}.csv", "particles": p2r / "posterior" / cell.regime / f"{tag}_particles.npz",
|
||||
"phase": p2r / "posterior" / cell.regime / f"{tag}_phase.json",
|
||||
"train_csv": p2r / "train" / cell.regime / "cells" / f"{cell.tag}.csv", "train_npz": p2r / "train" / cell.regime / "cells" / f"{cell.tag}.npz",
|
||||
"train_diag": p2r / "train" / cell.regime / "cells" / f"{cell.tag}_diag.csv"}
|
||||
out = {"cell": {"regime": cell.regime, "rid": cell.rid, "c": cell.c, "n_train": cell.n_train}, "posterior": {}, "train": {}}
|
||||
# posterior: phase, particles, warp diagnostics
|
||||
pn, pr = json.loads(new["phase"].read_text()), json.loads(ref["phase"].read_text())
|
||||
out["posterior"]["phase0"] = {"new": pn["phase0"], "p2r": pr["phase0"], "equal": pn["phase0"] == pr["phase0"]}
|
||||
out["posterior"]["phase_R"] = {"new": pn["phase_R"], "p2r": pr["phase_R"], "abs_diff_deg": abs(pn["phase_R"] - pr["phase_R"])}
|
||||
out["posterior"]["logZ_max_abs_diff"] = _max_abs(pn["logZ"], pr["logZ"]) if np.shape(pn["logZ"]) == np.shape(pr["logZ"]) else "shape differs"
|
||||
with np.load(new["particles"]) as zn, np.load(ref["particles"]) as zr:
|
||||
keys = sorted(k for k in zn.files if k in zr.files)
|
||||
out["posterior"]["particle_keys_compared"] = keys
|
||||
diffs = {k: _max_abs(zn[k], zr[k]) for k in keys}
|
||||
out["posterior"]["particles_max_abs_diff"] = diffs
|
||||
out["posterior"]["particles_bitwise"] = all(np.array_equal(zn[k], zr[k]) for k in keys)
|
||||
out["posterior"]["warp_mean_max_abs_diff_ms"] = {k: _max_abs(zn[k].mean(0), zr[k].mean(0)) for k in keys}
|
||||
dn, dr = pd.read_csv(new["csv"]), pd.read_csv(ref["csv"])
|
||||
m = dn.merge(dr, on=["well", "method", "wavelet"], suffixes=("_new", "_p2r"))
|
||||
cols = ["warp_rmse_ms", "warp_cov90", "warp_width90_ms", "logZ", "kappa_post", "r_post"]
|
||||
out["posterior"]["csv_max_abs_diff"] = {c: _max_abs(m[f"{c}_new"], m[f"{c}_p2r"]) for c in cols if f"{c}_new" in m}
|
||||
out["posterior"]["n_stages"] = {"new": dn[dn.method == "SMC_g_acf"].n_stages.tolist(), "p2r": dr[dr.method == "SMC_g_acf"].n_stages.tolist()}
|
||||
# training: per (method, seed, test well) metrics and predictions
|
||||
tn, tr = pd.read_csv(train_paths(cell, root)["csv"]), pd.read_csv(ref["train_csv"])
|
||||
keys = ["method", "seed", "budget", "test_well"]
|
||||
mt = tn.merge(tr, on=keys, suffixes=("_new", "_p2r"))
|
||||
out["train"]["rows_compared"] = int(len(mt))
|
||||
for c in ("band_rmse", "rmse", "band_pcc", "nll", "coverage_90"):
|
||||
out["train"][f"{c}_max_abs_diff"] = _max_abs(mt[f"{c}_new"], mt[f"{c}_p2r"])
|
||||
per_m = {m_: _max_abs(g[f"band_rmse_new"], g[f"band_rmse_p2r"]) for m_, g in mt.groupby("method")}
|
||||
out["train"]["band_rmse_max_abs_diff_per_method"] = per_m
|
||||
cm = mt.groupby("method")[["band_rmse_new", "band_rmse_p2r"]].mean()
|
||||
out["train"]["cell_mean_band_rmse"] = {m_: {"new": float(r.band_rmse_new), "p2r": float(r.band_rmse_p2r)} for m_, r in cm.iterrows()}
|
||||
with np.load(train_paths(cell, root)["npz"]) as zn, np.load(ref["train_npz"]) as zr:
|
||||
ks = sorted(k for k in zn.files if k in zr.files and k.endswith("/mu"))
|
||||
out["train"]["pred_mu_max_abs_diff_pu"] = {k: _max_abs(zn[k], zr[k]) for k in ks}
|
||||
out["train"]["pred_bitwise"] = all(np.array_equal(zn[k], zr[k]) for k in ks)
|
||||
out["train"]["y_true_bitwise"] = bool(np.array_equal(zn["y_true"], zr["y_true"]))
|
||||
gn, gr = pd.read_csv(train_paths(cell, root)["diag"]), pd.read_csv(ref["train_diag"])
|
||||
g = gn.merge(gr, on="well", suffixes=("_new", "_p2r"))
|
||||
out["train"]["diag_max_abs_diff"] = {c: _max_abs(g[f"{c}_new"], g[f"{c}_p2r"]) for c in ("B3c-R_warp_rmse_ms", "B3d-Sa_warp_rmse_ms", "lam", "phase_R")}
|
||||
out["train"]["M2-Sa_n_valid_equal"] = bool((g["M2-Sa_n_valid_new"] == g["M2-Sa_n_valid_p2r"]).all())
|
||||
write_json(root / "comparison.json", out)
|
||||
return out
|
||||
233
ml_porosity/benchmark/runner.py
Normal file
233
ml_porosity/benchmark/runner.py
Normal file
@@ -0,0 +1,233 @@
|
||||
"""Resumable stages of protocol_bench: posterior (SMC), train, with fingerprinted completion markers.
|
||||
|
||||
Completion marker of a job: its `.json` sidecar carrying the resume fingerprint (lock stamp + cell settings) and the
|
||||
SHA-256 of every artifact. A job whose sidecar matches is skipped; a sidecar with a different fingerprint or a
|
||||
mismatched artifact raises (use a new output root), as in ml_porosity/volve/runner.py. Dev runs (realizations
|
||||
900–905) write under outputs/bench/dev with a protocol-and-generator-only fingerprint; the reproduction cell writes
|
||||
under outputs/bench/repro. Neither is a result.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
|
||||
from datetime import datetime
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import (Cell, bench_root, needs_posterior, posterior_dir, posterior_paths,
|
||||
study_cells, train_paths)
|
||||
from ml_porosity.benchmark.protocol import check_rids, dev_stamp, digest, fingerprint, freeze, generator_config
|
||||
from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec
|
||||
from ml_porosity.f3.progress import write_json
|
||||
|
||||
|
||||
def _threads(n: int) -> None:
|
||||
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS", "NUMBA_NUM_THREADS"):
|
||||
os.environ.setdefault(k, str(n))
|
||||
|
||||
|
||||
def cell_from(d: dict) -> Cell:
|
||||
d = dict(d)
|
||||
d["methods"], d["tags"] = tuple(d["methods"]), tuple(d.get("tags", ()))
|
||||
return Cell(**d)
|
||||
|
||||
|
||||
def reusable(meta: Path, key: str, artifacts: list[Path]) -> bool:
|
||||
if not meta.exists():
|
||||
return False
|
||||
stored = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if stored.get("fingerprint") != key:
|
||||
raise RuntimeError(f"resume fingerprint mismatch: {meta}. Use a new output root (or a new protocol version).")
|
||||
for a in artifacts:
|
||||
if not a.exists() or digest(a) != stored.get("artifact_sha256", {}).get(a.name):
|
||||
raise RuntimeError(f"missing or mismatched completed artifact: {a}")
|
||||
return True
|
||||
|
||||
|
||||
def sidecar(meta_path: Path, key: str, artifacts: list[Path], extra: dict) -> None:
|
||||
write_json(meta_path, extra | {"fingerprint": key, "artifact_sha256": {a.name: digest(a) for a in artifacts},
|
||||
"finished": datetime.now().astimezone().isoformat(timespec="seconds")})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- workers (importable, spawn context)
|
||||
|
||||
def posterior_worker(job: dict) -> dict:
|
||||
import torch
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.registration import posterior_cell
|
||||
|
||||
torch.set_num_threads(job["threads"])
|
||||
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
|
||||
reg_seed = int(p["registration"]["reg_seed"])
|
||||
paths = posterior_paths(cell, root, reg_seed)
|
||||
arts = [paths["csv"], paths["particles"], paths["phase"]]
|
||||
if reusable(paths["meta"], job["key"], arts):
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
inp = load_inputs(p)
|
||||
R = inp.realization(cell.rid, cell.preset)
|
||||
obs, _ = inp.observe(R, cell.c, cell.regime, cell.n_train)
|
||||
smc = p["registration"]["smc"]
|
||||
_, meta = posterior_cell(R, inp, obs, cell.c, cell.n_train, inp.regime(cell.regime), reg_seed,
|
||||
int(smc["smc_seed"]), int(smc["particles"]), job["device"], job["mem_gb"], paths,
|
||||
checkpoints=tuple(smc["checkpoints"]), extra_meta={"cell": dataclasses.asdict(cell)},
|
||||
phase_kw={k: smc[f"phase_{k}"] for k in ("step", "half_width", "max_extra") if f"phase_{k}" in smc})
|
||||
sidecar(paths["meta"], job["key"], arts, meta)
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
def training_worker(job: dict) -> dict:
|
||||
import torch
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.training import train_cell
|
||||
|
||||
torch.set_num_threads(job["threads"])
|
||||
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
|
||||
paths = train_paths(cell, root)
|
||||
arts = [paths["csv"], paths["npz"], paths["diag"]]
|
||||
if reusable(paths["meta"], job["key"], arts):
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
post = posterior_paths(cell, root, int(p["registration"]["reg_seed"])) if cell.posterior != "none" else None
|
||||
if post is not None and not post["particles"].exists():
|
||||
raise FileNotFoundError(f"{cell.tag}: posterior not available at {post['particles']}")
|
||||
inp = load_inputs(p)
|
||||
rows, diag, preds, meta = train_cell(cell, p, inp, job["device"], post, save_preds=True, seeds=job.get("seeds"))
|
||||
paths["csv"].parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = paths["npz"].with_suffix(".tmp.npz")
|
||||
np.savez_compressed(tmp, **preds)
|
||||
tmp.replace(paths["npz"])
|
||||
pd.DataFrame(diag).to_csv(paths["diag"], index=False)
|
||||
pd.DataFrame(rows).to_csv(paths["csv"], index=False)
|
||||
sidecar(paths["meta"], job["key"], arts, meta | {"cell": dataclasses.asdict(cell)})
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- pools
|
||||
|
||||
def progress(root: Path, name: str, **values) -> None:
|
||||
path = root / "progress.json"
|
||||
for attempt in range(10):
|
||||
try:
|
||||
old = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||
old[name] = old.get(name, {}) | values | {"updated": datetime.now().astimezone().isoformat(timespec="seconds")}
|
||||
write_json(path, old)
|
||||
return
|
||||
except (PermissionError, json.JSONDecodeError):
|
||||
time.sleep(0.25 * (attempt + 1))
|
||||
|
||||
|
||||
def run_jobs(jobs: list[dict], fn, workers: int, root: Path, name: str) -> list[dict]:
|
||||
if not jobs:
|
||||
print(f"{name}: nothing to do", flush=True)
|
||||
return []
|
||||
started, results = time.perf_counter(), []
|
||||
progress(root, name, status="running", completed=0, total=len(jobs), error=None)
|
||||
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context("spawn")) as pool:
|
||||
futures = {pool.submit(fn, job): job for job in jobs}
|
||||
pending = set(futures)
|
||||
while pending:
|
||||
done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED)
|
||||
for fut in done:
|
||||
try:
|
||||
result = fut.result()
|
||||
except Exception as exc:
|
||||
for other in pending:
|
||||
other.cancel()
|
||||
progress(root, name, status="failed; pending jobs cancelled", error=f"{futures[fut]['cell']['study']} "
|
||||
f"{futures[fut]['cell']['regime']} {futures[fut]['cell']['rid']}: {exc}")
|
||||
raise
|
||||
results.append(result)
|
||||
fresh = sum(not r.get("cached") for r in results)
|
||||
elapsed = time.perf_counter() - started
|
||||
eta = elapsed / fresh * (len(jobs) - len(results)) if fresh else None
|
||||
progress(root, name, completed=len(results), cached=len(results) - fresh, elapsed_seconds=elapsed, eta_seconds=eta)
|
||||
print(f"[{name} {len(results)}/{len(jobs)}] {'cached ' if result.get('cached') else ''}{result['path']}"
|
||||
f"{'' if result.get('cached') else f' ({result.get('wall_seconds', 0):.0f} s)'} "
|
||||
f"elapsed {elapsed:.0f} s{'' if eta is None else f', eta {eta:.0f} s'}", flush=True)
|
||||
progress(root, name, status="done", eta_seconds=0)
|
||||
return results
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- planning
|
||||
|
||||
def plan(p: dict, studies: list[str], rids=None, regimes=None, presets=None, controls: bool = False,
|
||||
grid: dict | None = None) -> list[Cell]:
|
||||
cells = []
|
||||
for s in studies:
|
||||
kw = {"presets": presets, "controls": controls} if s == "S2" else {}
|
||||
cells += study_cells(p, s, rids=rids, regimes=regimes, grid=grid, **kw)
|
||||
return cells
|
||||
|
||||
|
||||
def stamp_for(p: dict, mode: str) -> dict:
|
||||
if mode == "dev":
|
||||
return dev_stamp(p)
|
||||
if mode == "repro":
|
||||
return dev_stamp(p) | {"repro": True}
|
||||
return freeze(check=True)
|
||||
|
||||
|
||||
def make_jobs(p: dict, cells: list[Cell], stage: str, stamp: dict, root: Path, device: str, workers_mem_gb: float,
|
||||
threads: int, seeds=None) -> list[dict]:
|
||||
jobs, seen = [], set()
|
||||
cfg = generator_config(p)
|
||||
for cell in cells:
|
||||
misspec = normalize_misspec(preset_misspec(cfg, cell.preset))
|
||||
if stage == "posterior":
|
||||
if not needs_posterior(cell):
|
||||
continue
|
||||
ident = (cell.study, cell.setting, cell.rid, cell.c, cell.n_train)
|
||||
settings = dict(stage="posterior", setting=cell.setting, regime=cell.regime, preset=cell.preset, misspec=misspec,
|
||||
rid=cell.rid, c=cell.c, n_train=cell.n_train, reg_seed=p["registration"]["reg_seed"],
|
||||
smc=p["registration"]["smc"])
|
||||
else:
|
||||
ident = (cell.study, cell.setting, cell.tag, cell.backbone)
|
||||
settings = dict(stage="train", study=cell.study, setting=cell.setting, regime=cell.regime, preset=cell.preset,
|
||||
misspec=misspec, rid=cell.rid, c=cell.c, n_train=cell.n_train, methods=list(cell.methods), backbone=cell.backbone,
|
||||
delta_ms=cell.delta_ms, posterior=cell.posterior, seeds=list(p["grid"]["seeds"] if seeds is None else seeds),
|
||||
budgets={m: p["training"]["budgets"].get(m.removesuffix("-TCN")) for m in cell.methods},
|
||||
equal_budget_arm=p["training"].get("equal_budget_arm"))
|
||||
if ident in seen:
|
||||
continue
|
||||
seen.add(ident)
|
||||
jobs.append(dict(p=p, cell=dataclasses.asdict(cell), root=str(root), device=device, mem_gb=workers_mem_gb,
|
||||
threads=threads, seeds=seeds, key=fingerprint(stamp, **settings)))
|
||||
# largest N first keeps the wall-clock tail short (as scripts 14/15)
|
||||
jobs.sort(key=lambda j: (-j["cell"]["n_train"], j["cell"]["rid"]))
|
||||
return jobs
|
||||
|
||||
|
||||
def run(stage: str, p: dict, studies: list[str], device: str, workers: int, mem_gb: float, threads: int = 2,
|
||||
mode: str = "main", rids=None, regimes=None, presets=None, controls: bool = False, seeds=None,
|
||||
root: Path | None = None, grid: dict | None = None) -> list[dict]:
|
||||
"""stage: posterior | train. mode: main (locked), dev (outputs/bench/dev), repro (outputs/bench/repro).
|
||||
grid / seeds: dev-only overrides of the (c, N) lists and the network seeds."""
|
||||
_threads(threads)
|
||||
if (grid or seeds) and mode != "dev":
|
||||
raise SystemExit("--drift / --n-train / --seeds are dev-only overrides")
|
||||
if mode == "repro":
|
||||
rp = p["reproduction"]
|
||||
rids, regimes = [rp["rid"]], [rp["regime"]]
|
||||
cells = [Cell("S1", rp["regime"], None, float(rp["c"]), int(rp["n_train"]), int(rp["rid"]), tuple(rp["methods"]))]
|
||||
else:
|
||||
cells = plan(p, studies, rids=rids, regimes=regimes, presets=presets, controls=controls, grid=grid)
|
||||
check_rids([c.rid for c in cells] or (rids or []), p, dev=(mode == "dev"), repro=(mode == "repro"))
|
||||
stamp = stamp_for(p, mode)
|
||||
root = root or bench_root(dev=(mode == "dev"), repro=(mode == "repro"))
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
jobs = make_jobs(p, cells, stage, stamp, root, device, mem_gb, threads, seeds)
|
||||
name = f"{stage}:{'+'.join(studies) if mode != 'repro' else 'repro'}:{mode}"
|
||||
print(f"{name}: {len(jobs)} jobs, {workers} workers, device {device}, root {root}", flush=True)
|
||||
fn = posterior_worker if stage == "posterior" else training_worker
|
||||
return run_jobs(jobs, fn, workers, root, name)
|
||||
|
||||
|
||||
def status(root: Path) -> str:
|
||||
path = root / "progress.json"
|
||||
return path.read_text(encoding="utf-8") if path.exists() else "protocol_bench has not started."
|
||||
539
ml_porosity/benchmark/summary.py
Normal file
539
ml_porosity/benchmark/summary.py
Normal file
@@ -0,0 +1,539 @@
|
||||
"""Pre-declared analyses of protocol_bench (hypotheses block of configs/protocol_bench.yaml), applied as written.
|
||||
|
||||
Rules are those of protocol_p2 / protocol_p2r through scripts/13 (gate_gb, boot) and scripts/18 (pair_cell). Runs of
|
||||
the P2r cells come from outputs/p2r (reference, read-only). Everything is reported regardless of direction; a
|
||||
hypothesis of kind `claim` gets a pass/fail, `descriptive` items get tables only.
|
||||
→ <root>/summary/: s1_cells.csv, s1_h2a.csv, s1_families.csv, s1_additivity.csv, s2_cells.csv, s2_smc.csv, s2_h2a.csv,
|
||||
s2_degradation.csv, s3_h2a.csv, s3_table.csv, s4_cells.csv, s4_h2a.csv, s8_cells.csv, s8_transfer.csv, verdict.json,
|
||||
summary.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell, bench_root, study_cells, train_paths
|
||||
from ml_porosity.benchmark.data import load_script
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
sp13 = load_script("13_summarize_p2.py")
|
||||
METRICS = sp13.METRICS
|
||||
Z90 = 3.29
|
||||
NFFT = 256
|
||||
POINT_TIES = ["B3b", "B3c", "B3c-R"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- loading
|
||||
|
||||
def _runs_from_cells(files: list[Path], budgets: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
if not files:
|
||||
return pd.DataFrame(), pd.DataFrame()
|
||||
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
df = df[df["budget"] == df["method"].map(lambda m: budgets.get(m, np.nan))]
|
||||
by = ["study", "regime", "preset", "delta_ms", "rid", "c", "n_train", "method", "seed"]
|
||||
by = [b for b in by if b in df.columns]
|
||||
run = df.groupby(by, as_index=False, dropna=False)[METRICS].mean()
|
||||
return df, run
|
||||
|
||||
|
||||
def study_budgets(p: dict, study: str, arm: int | None = None) -> dict:
|
||||
"""Registered budgets per method (TCN names for S4); arm: the equal-budget arm instead (every method at `arm`)."""
|
||||
b = dict(p["training"]["budgets"])
|
||||
if p["studies"][study].get("backbone", "cnngru") != "cnngru":
|
||||
alt = p["training"].get("budgets_tcn") or {}
|
||||
b = {f"{m}-TCN": int(alt.get(m, v)) for m, v in b.items()}
|
||||
if arm:
|
||||
b = {m: int(arm) for m in b}
|
||||
return b
|
||||
|
||||
|
||||
def load_study(p: dict, root: Path, study: str, arm: int | None = None) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
|
||||
"""(rows, runs, diag) of every completed cell of a study under root at the registered budgets (arm=None) or at
|
||||
the equal-budget arm."""
|
||||
d = root / study.lower() / "train"
|
||||
files = sorted(f for f in d.glob("*/cells/*.csv") if not f.name.endswith("_diag.csv")) if d.exists() else []
|
||||
rows, run = _runs_from_cells(files, study_budgets(p, study, arm))
|
||||
diag = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True) if files else pd.DataFrame()
|
||||
return rows, run, diag
|
||||
|
||||
|
||||
USE_P2R = True # set to False by summarize(dev=True): a dev summary must never read main-grid results
|
||||
|
||||
|
||||
def p2r_runs(p: dict) -> pd.DataFrame:
|
||||
root = REPO_ROOT / p["reference"]["p2r"]["root"]
|
||||
parts = []
|
||||
if not USE_P2R:
|
||||
return pd.DataFrame()
|
||||
for reg in p["reference"]["p2r"]["regimes"]:
|
||||
f = root / "train" / reg / "runs.csv"
|
||||
if f.exists():
|
||||
parts.append(pd.read_csv(f).assign(regime=reg, preset="nominal", study="P2r"))
|
||||
return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame()
|
||||
|
||||
|
||||
def sigma_post_table(dirs: dict[str, Path]) -> pd.DataFrame:
|
||||
"""σ_post and SMC diagnostics per (setting, c, N) from posterior CSVs (SMC_g_acf, estR), mean over wells then rids."""
|
||||
rows = []
|
||||
for setting, d in dirs.items():
|
||||
files = sorted(d.glob("r*_s*.csv")) if d.exists() else []
|
||||
if not files:
|
||||
continue
|
||||
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||||
s = df[(df.method == "SMC_g_acf") & (df.wavelet == "estR")]
|
||||
per = s.groupby(["c", "n_train", "rid"]).agg(width90=("warp_width90_ms", "mean"), warp_rmse_ms=("warp_rmse_ms", "mean"),
|
||||
warp_cov90=("warp_cov90", "mean"), kappa_post=("kappa_post", "mean"),
|
||||
r_post=("r_post", "mean"), phase_R=("phase_R", "first"), phase0=("phase", "first"))
|
||||
per["sigma_post_ms"] = per.width90 / Z90
|
||||
per["overconfidence"] = per.warp_rmse_ms / per.sigma_post_ms
|
||||
g = per.groupby(["c", "n_train"]).agg(sigma_post_ms=("sigma_post_ms", "mean"), warp_rmse_ms=("warp_rmse_ms", "mean"),
|
||||
warp_cov90=("warp_cov90", "mean"), overconfidence=("overconfidence", "mean"),
|
||||
kappa_post=("kappa_post", "mean"), r_post=("r_post", "mean"),
|
||||
phase_R_mean=("phase_R", "mean"), phase_R_abs_mean=("phase_R", lambda x: float(np.mean(np.abs(x)))),
|
||||
n_rid=("sigma_post_ms", "size")).reset_index()
|
||||
rows.append(g.assign(setting=setting))
|
||||
return pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- rules
|
||||
|
||||
def h2a_cells(run: pd.DataFrame, cand: str, comp: list[str], rng, n_boot: int) -> pd.DataFrame:
|
||||
"""protocol_p2 cell rule with `cand` in the role of M2 against the best of `comp` (scripts/13 gate_gb)."""
|
||||
r = run[run.method.isin(comp) | (run.method == cand)].replace({"method": {cand: "M2"}})
|
||||
if r.empty or "M2" not in set(r.method) or not (set(r.method) & set(comp)):
|
||||
return pd.DataFrame()
|
||||
if any(m.endswith("-TCN") for m in comp): # gate_gb reads 'B3b' by name: drop the backbone suffix locally
|
||||
r = r.assign(method=r.method.str.replace("-TCN", "", regex=False))
|
||||
comp = [m.removesuffix("-TCN") for m in comp]
|
||||
grid = {"n_train": sorted(r.n_train.unique().tolist()), "drift_factors": sorted(r.c.unique().tolist()),
|
||||
"realistic_drift": 1, "realizations": sorted(r.rid.unique().tolist()), "seeds": sorted(r.seed.unique().tolist())}
|
||||
cells, _ = sp13.gate_gb(r, {"grid": grid, "gates": {"G-B": {"competitors": comp}}}, n_boot, rng)
|
||||
return cells
|
||||
|
||||
|
||||
def pair(run: pd.DataFrame, a: str, b: str, rng, n_boot: int) -> dict:
|
||||
"""Ratio mean(a)/mean(b) of band RMSE with CI over realizations and the 'better' rule (scripts/18 pair_cell)."""
|
||||
x = run[run.method == a].set_index(["rid", "seed"])["band_rmse"]
|
||||
y = run[run.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index)
|
||||
ok = y.notna()
|
||||
x, y = x[ok], y[ok]
|
||||
if len(x) == 0:
|
||||
return {}
|
||||
d = x - y
|
||||
ds, dr = d.groupby("seed").mean(), d.groupby("rid").mean()
|
||||
lo, hi = sp13.boot(x.groupby("rid").mean().to_numpy(), y.groupby("rid").mean().to_numpy(), n_boot, rng)
|
||||
return {"ratio": float(x.mean() / y.mean()), "ratio_lo": lo, "ratio_hi": hi, "seeds_better": int((ds < 0).sum()),
|
||||
"rids_better": int((dr < 0).sum()), "n_seed": len(ds), "n_rid": len(dr),
|
||||
"better": bool((ds < 0).sum() >= math.ceil(sp13.SEED_FRAC * len(ds) - 1e-9) and (dr < 0).sum() > len(dr) / 2)}
|
||||
|
||||
|
||||
def perm_spearman(x, y, groups, rng, n_perm: int) -> tuple[float, float]:
|
||||
"""Spearman ρ(x, y) and one-sided permutation p (ρ ≤ observed) permuting y within groups."""
|
||||
from scipy.stats import spearmanr
|
||||
|
||||
x, y, groups = np.asarray(x, float), np.asarray(y, float), np.asarray(groups)
|
||||
if len(x) < 3:
|
||||
return float("nan"), float("nan")
|
||||
rho = spearmanr(x, y).statistic
|
||||
idx = {g: np.flatnonzero(groups == g) for g in np.unique(groups)}
|
||||
cnt = 0
|
||||
for _ in range(n_perm):
|
||||
yp = y.copy()
|
||||
for ii in idx.values():
|
||||
yp[ii] = y[rng.permutation(ii)]
|
||||
cnt += spearmanr(x, yp).statistic <= rho
|
||||
return float(rho), float(cnt / n_perm)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S1
|
||||
|
||||
def s1(p: dict, root: Path, rng, n_boot: int, n_perm: int) -> tuple[dict, dict]:
|
||||
_, run_new, _ = load_study(p, root, "S1")
|
||||
run = pd.concat([p2r_runs(p), run_new], ignore_index=True) if len(run_new) else p2r_runs(p)
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
sp = sigma_post_table({reg: root / "posterior" / reg for reg in p["studies"]["S1"]["regimes"]})
|
||||
sp_ref = REPO_ROOT / p["reference"]["p2r"]["root"] / "summary" / "sigma_post.csv"
|
||||
if sp_ref.exists() and USE_P2R:
|
||||
ref = pd.read_csv(sp_ref).rename(columns={"setting": "regime"})
|
||||
ref = ref[ref.regime.isin(p["studies"]["S1"]["regimes"])][["regime", "c", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]]
|
||||
sp = pd.concat([sp.rename(columns={"setting": "regime"}), ref.assign(source="p2r")], ignore_index=True) if len(sp) else ref.assign(source="p2r")
|
||||
else:
|
||||
sp = sp.rename(columns={"setting": "regime"})
|
||||
tables, verdict = {}, {}
|
||||
# phase-diagram cells: per (regime, c, N) band RMSE per method, ratios with CI
|
||||
cells = []
|
||||
for (reg, c, N), g in run.groupby(["regime", "c", "n_train"]):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "c": c, "n_train": N, "n_rid": g.rid.nunique(), "n_seed": g.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
if "M2-Sa" in mean and "B3d-Sa" in mean:
|
||||
row |= {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa", "B3d-Sa", rng, n_boot).items()}
|
||||
pt = [m for m in POINT_TIES if m in mean.index]
|
||||
if pt and "B3d-Sa" in mean:
|
||||
best = mean.loc[pt].idxmin()
|
||||
row |= {"best_point_tie": best} | {f"pm_best_{k}": v for k, v in pair(g, "B3d-Sa", best, rng, n_boot).items()}
|
||||
cells.append(row)
|
||||
cells = pd.DataFrame(cells).merge(sp[["regime", "c", "n_train", "sigma_post_ms"]].drop_duplicates(["regime", "c", "n_train"]),
|
||||
on=["regime", "c", "n_train"], how="left")
|
||||
tables["s1_cells"] = cells
|
||||
# H2a rule at every (regime, c, N) (S1-H1: R10, c = 1.5, both N)
|
||||
h2a = []
|
||||
for reg, g in run.groupby("regime"):
|
||||
t = h2a_cells(g, "B3d-Sa", POINT_TIES, rng, n_boot)
|
||||
if len(t):
|
||||
h2a.append(t.assign(regime=reg))
|
||||
h2a = pd.concat(h2a, ignore_index=True) if h2a else pd.DataFrame()
|
||||
tables["s1_h2a"] = h2a
|
||||
if len(h2a):
|
||||
t = h2a[(h2a.regime == "R10") & (h2a.c == 1.5)]
|
||||
verdict["S1-H1"] = {"cells": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()},
|
||||
"ratios": {int(r.n_train): [r.ratio, r.ratio_lo, r.ratio_hi] for r in t.itertuples()},
|
||||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None,
|
||||
"complete": bool(len(t) == 2 and (t.n_rid == len(p["grid"]["realizations"])).all())}
|
||||
# S1-H2: families with σ_post(N = 16) ≥ 1.5 ms; r(N) decreasing in N
|
||||
wide16 = cells[(cells.n_train == 16) & (cells.sigma_post_ms >= 1.5)][["regime", "c"]]
|
||||
fam = cells.merge(wide16, on=["regime", "c"]).dropna(subset=["m2_pm_ratio"])
|
||||
fam["family"] = fam.regime + "_c" + fam.c.map(lambda v: f"{v:g}")
|
||||
tables["s1_families"] = fam[["family", "regime", "c", "n_train", "sigma_post_ms", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better"]]
|
||||
if len(fam):
|
||||
r16 = fam[fam.n_train == 16].set_index("family").m2_pm_ratio
|
||||
r2 = fam[fam.n_train == 2].set_index("family").m2_pm_ratio
|
||||
both = r16.index.intersection(r2.index)
|
||||
sign = int((r16[both] < r2[both]).sum())
|
||||
rho, pval = perm_spearman(np.log2(fam.n_train), fam.m2_pm_ratio, fam.family, rng, n_perm)
|
||||
a = bool(len(both) > 0 and sign >= math.ceil(2 / 3 * len(both) - 1e-9))
|
||||
b = bool(rho < 0 and pval < 0.05)
|
||||
verdict["S1-H2"] = {"families": sorted(fam.family.unique()), "families_with_N2_and_N16": int(len(both)), "r16_below_r2": sign,
|
||||
"a_sign": a, "spearman_rho": rho, "perm_p_one_sided": pval, "b_dose": b,
|
||||
"pass": (a and b) if len(both) > 0 and fam.n_train.nunique() >= 3 else None}
|
||||
# S1-D additivity: band_rmse²(B3d-Sa) = band_rmse²(Oracle) + β σ_post² per regime
|
||||
add = []
|
||||
for reg, g in cells.dropna(subset=["sigma_post_ms"]).groupby("regime"):
|
||||
if "band_rmse_B3d-Sa" not in g or "band_rmse_Oracle" not in g:
|
||||
continue
|
||||
y = g["band_rmse_B3d-Sa"] ** 2 - g["band_rmse_Oracle"] ** 2
|
||||
x = g["sigma_post_ms"] ** 2
|
||||
if len(g) < 3 or x.var() == 0:
|
||||
continue
|
||||
beta = float((x * y).sum() / (x * x).sum())
|
||||
resid = y - beta * x
|
||||
add.append({"regime": reg, "n_cells": len(g), "beta_pu2_per_ms2": beta,
|
||||
"r2": float(1 - (resid ** 2).sum() / ((y - y.mean()) ** 2).sum()) if (y - y.mean()).abs().sum() > 0 else float("nan")})
|
||||
tables["s1_additivity"] = pd.DataFrame(add)
|
||||
return tables, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S2
|
||||
|
||||
def s2(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
_, run, diag = load_study(p, root, "S2")
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
s = p["studies"]["S2"]
|
||||
axes = {name: axis for axis, names in s["presets"].items() for name in names}
|
||||
levels = {name: i + 1 for names in s["presets"].values() for i, name in enumerate(names)}
|
||||
settings = {f"{reg}__{name}": root / "posterior" / f"{reg}__{name}" for reg in s["regimes"] for name in list(axes) + list(s.get("controls", {}).get("presets", []))}
|
||||
smc = sigma_post_table(settings)
|
||||
if len(smc):
|
||||
smc["regime"] = smc.setting.str.split("__").str[0]
|
||||
smc["preset"] = smc.setting.str.split("__").str[1]
|
||||
smc["axis"] = smc.preset.map(lambda n: axes.get(n, "control"))
|
||||
smc["level"] = smc.preset.map(lambda n: levels.get(n, 0))
|
||||
tables = {"s2_smc": smc}
|
||||
ref = p2r_runs(p)
|
||||
cells, h2a_rows, verdict = [], [], {"S2-H1": {"per_axis": {}}, "S2-H2": {"pairs": {}}}
|
||||
for (reg, name), g in run.groupby(["regime", "preset"]):
|
||||
h = h2a_cells(g, "B3d-Sa", POINT_TIES, rng, n_boot)
|
||||
if len(h):
|
||||
h2a_rows.append(h.assign(regime=reg, preset=name, axis=axes.get(name, "control"), level=levels.get(name, 0)))
|
||||
ratios = {}
|
||||
for N, gN in g.groupby("n_train"):
|
||||
mean = gN.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "preset": name, "axis": axes.get(name, "control"), "level": levels.get(name, 0), "c": 1.0, "n_train": N,
|
||||
"n_rid": gN.rid.nunique(), "n_seed": gN.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
pr = pair(gN, "M2-Sa", "B3d-Sa", rng, n_boot)
|
||||
row |= {f"m2_pm_{k}": v for k, v in pr.items()}
|
||||
ratios[N] = pr.get("ratio", np.nan)
|
||||
if "Ctl-GP" in mean.index: # disclosed (T2 ii)
|
||||
row |= {f"ctl_pm_{k}": v for k, v in pair(gN, "Ctl-GP", "B3d-Sa", rng, n_boot).items()}
|
||||
row |= {f"m2_ctl_{k}": v for k, v in pair(gN, "M2-Sa", "Ctl-GP", rng, n_boot).items()}
|
||||
pt = [m for m in POINT_TIES if m in mean.index]
|
||||
if pt and "B3d-Sa" in mean:
|
||||
best = mean.loc[pt].idxmin()
|
||||
row |= {"best_point_tie": best} | {f"pm_best_{k}": v for k, v in pair(gN, "B3d-Sa", best, rng, n_boot).items()}
|
||||
row["pm_no_harm"] = bool(row["pm_best_ratio"] <= sp13.GUARD)
|
||||
# degradation vs the P2r nominal cell (descriptive)
|
||||
if len(ref):
|
||||
nom = ref[(ref.regime == reg) & (ref.c == 1) & (ref.n_train == N)]
|
||||
for m in mean.index:
|
||||
nm = nom[nom.method == m]
|
||||
if len(nm):
|
||||
row[f"degradation_{m}"] = float(mean[m] / nm.band_rmse.mean())
|
||||
sm = smc[(smc.setting == f"{reg}__{name}") & (smc.n_train == N)] if len(smc) else pd.DataFrame()
|
||||
if len(sm):
|
||||
row |= {k: float(sm.iloc[0][k]) for k in ("sigma_post_ms", "warp_rmse_ms", "warp_cov90", "overconfidence")}
|
||||
row["wide"] = bool(row["sigma_post_ms"] >= 1.5)
|
||||
cells.append(row)
|
||||
if name in axes:
|
||||
mean_ratio = float(np.nanmean(list(ratios.values()))) if ratios else float("nan")
|
||||
verdict["S2-H2"]["pairs"][f"{reg}/{name}"] = {"mean_ratio_M2-Sa/B3d-Sa": mean_ratio, "ok": bool(mean_ratio <= sp13.GUARD),
|
||||
"n_cells": len(ratios)}
|
||||
tables["s2_cells"] = pd.DataFrame(cells)
|
||||
h2a = pd.concat(h2a_rows, ignore_index=True) if h2a_rows else pd.DataFrame()
|
||||
tables["s2_h2a"] = h2a
|
||||
for axis, names in s["presets"].items():
|
||||
l1 = names[0]
|
||||
t = h2a[(h2a.regime == "R10") & (h2a.preset == l1) & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||||
per = {}
|
||||
for reg in s["regimes"]:
|
||||
for name in names:
|
||||
tt = h2a[(h2a.regime == reg) & (h2a.preset == name) & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||||
per[f"{reg}/{name}"] = {int(r.n_train): {"cell_pass": bool(r.cell_pass), "ratio": r.ratio, "ci": [r.ratio_lo, r.ratio_hi], "best": r.best}
|
||||
for r in tt.itertuples()}
|
||||
verdict["S2-H1"]["per_axis"][axis] = {"L1_R10_cells_pass": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()},
|
||||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None,
|
||||
"complete": bool(len(t) == 2 and (t.n_rid == len(p["grid"]["realizations"])).all()),
|
||||
"all_cells": per}
|
||||
verdict["S2-H1"]["axes_pass"] = [a for a, v in verdict["S2-H1"]["per_axis"].items() if v["pass"]]
|
||||
verdict["S2-H1"]["pass_all_axes"] = bool(len(verdict["S2-H1"]["axes_pass"]) == len(s["presets"]))
|
||||
pairs = verdict["S2-H2"]["pairs"]
|
||||
expected = len(s["regimes"]) * sum(len(v) for v in s["presets"].values())
|
||||
verdict["S2-H2"]["complete"] = bool(len(pairs) == expected)
|
||||
verdict["S2-H2"]["pass"] = all(v["ok"] for v in pairs.values()) if len(pairs) == expected else None
|
||||
tables["s2_degradation"] = tables["s2_cells"][[c for c in tables["s2_cells"].columns if c.startswith("degradation_") or c in ("regime", "preset", "axis", "level", "n_train")]] if len(cells) else pd.DataFrame()
|
||||
return tables, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S3
|
||||
|
||||
def s3(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
_, run_b4, _ = load_study(p, root, "S3")
|
||||
ref = p2r_runs(p)
|
||||
if run_b4.empty or ref.empty:
|
||||
return {}, {"available": False}
|
||||
comp = POINT_TIES + list(p["studies"]["S3"]["methods"])
|
||||
run = pd.concat([ref, run_b4], ignore_index=True)
|
||||
rows, verdict = [], {"per_regime": {}}
|
||||
for reg, g in run.groupby("regime"):
|
||||
if "B3d-Sa" not in set(g.method):
|
||||
continue
|
||||
cells = h2a_cells(g, "B3d-Sa", comp, rng, n_boot)
|
||||
if not len(cells):
|
||||
continue
|
||||
rows.append(cells.assign(regime=reg, flag=np.where(cells.c == 2, "unstable posterior", "")))
|
||||
c1, c0 = cells[cells.c == 1], cells[cells.c == 0]
|
||||
macro = c0.m2_band_rmse.mean() / c0.best_band_rmse.mean() if len(c0) else float("nan")
|
||||
guard = bool(len(c0) == 2 and macro <= sp13.GUARD and (c0.ratio <= sp13.GUARD).all())
|
||||
verdict["per_regime"][reg] = {"c1_cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}", "best_at_c1": {int(r.n_train): r.best for r in c1.itertuples()},
|
||||
"zero_drift_macro_ratio": macro, "zero_drift_guard": guard,
|
||||
"regime_pass": bool(len(c1) == 2 and c1.cell_pass.all() and guard),
|
||||
"complete": bool((cells.n_rid == len(p["grid"]["realizations"])).all() and len(cells) == 6)}
|
||||
tab = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||||
h2a_regimes = ["R10", "R0", "Rm5"]
|
||||
verdict["pass"] = verdict["per_regime"].get("R10", {}).get("regime_pass")
|
||||
verdict["regimes_pass"] = [r for r in h2a_regimes if verdict["per_regime"].get(r, {}).get("regime_pass")]
|
||||
table = run.groupby(["regime", "c", "n_train", "method"])["band_rmse"].mean().unstack("method").reset_index()
|
||||
ctl = []
|
||||
if "Ctl-GP" in set(run.method): # T2-1 (disclosed): control bank across the P2r grid
|
||||
for (reg, c, N), g in run.groupby(["regime", "c", "n_train"]):
|
||||
if "Ctl-GP" not in set(g.method):
|
||||
continue
|
||||
ctl.append({"regime": reg, "c": c, "n_train": N, "n_rid": g.rid.nunique(), "flag": "unstable posterior" if c == 2 else ""}
|
||||
| {f"ctl_pm_{k}": v for k, v in pair(g, "Ctl-GP", "B3d-Sa", rng, n_boot).items()}
|
||||
| {f"m2_ctl_{k}": v for k, v in pair(g, "M2-Sa", "Ctl-GP", rng, n_boot).items()}
|
||||
| {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa", "B3d-Sa", rng, n_boot).items()})
|
||||
ctl = pd.DataFrame(ctl)
|
||||
if len(ctl) and {"m2_ctl_better", "ctl_pm_better"} <= set(ctl.columns):
|
||||
verdict["T2-1"] = {"cells": int(len(ctl)), "m2_better_than_ctl": int(ctl.m2_ctl_better.sum()),
|
||||
"m2_better_than_ctl_by_c": {f"c{c:g}": int(d.m2_ctl_better.sum()) for c, d in ctl.groupby("c")},
|
||||
"ctl_better_than_pm": int(ctl.ctl_pm_better.sum())}
|
||||
return {"s3_h2a": tab, "s3_table": table, "s3_control": ctl}, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S4
|
||||
|
||||
def s4(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
_, run, _ = load_study(p, root, "S4")
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
pt = [f"{m}-TCN" for m in POINT_TIES]
|
||||
rows, verdict = [], {}
|
||||
for reg, g in run.groupby("regime"):
|
||||
cells = h2a_cells(g, "B3d-Sa-TCN", pt, rng, n_boot)
|
||||
if len(cells):
|
||||
rows.append(cells.assign(regime=reg))
|
||||
h2a = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||||
t = h2a[(h2a.regime == "R10") & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||||
verdict["S4-H1"] = {"cells": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()}, "ratios": {int(r.n_train): [r.ratio, r.ratio_lo, r.ratio_hi] for r in t.itertuples()},
|
||||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None}
|
||||
cells = []
|
||||
ref = p2r_runs(p)
|
||||
for (reg, N), g in run.groupby(["regime", "n_train"]):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "c": 1.0, "n_train": N, "n_rid": g.rid.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
row |= {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa-TCN", "B3d-Sa-TCN", rng, n_boot).items()}
|
||||
if len(ref):
|
||||
nom = ref[(ref.regime == reg) & (ref.c == 1) & (ref.n_train == N)]
|
||||
for m in mean.index:
|
||||
nm = nom[nom.method == m.removesuffix("-TCN")]
|
||||
if len(nm):
|
||||
row[f"tcn_over_cnngru_{m.removesuffix('-TCN')}"] = float(mean[m] / nm.band_rmse.mean())
|
||||
cells.append(row)
|
||||
cells = pd.DataFrame(cells)
|
||||
wide = cells[(cells.n_train == 16) & cells.regime.isin(["Rm5", "R0h"])]
|
||||
verdict["S4-H2"] = {"cells": {r.regime: {"ratio": r.m2_pm_ratio, "ci": [r.m2_pm_ratio_lo, r.m2_pm_ratio_hi], "better": bool(r.m2_pm_better)} for r in wide.itertuples()},
|
||||
"pass": bool(wide.m2_pm_better.all()) if len(wide) == 2 else None}
|
||||
return {"s4_cells": cells, "s4_h2a": h2a}, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S8
|
||||
|
||||
def cross_spectrum(Y: np.ndarray, P: np.ndarray) -> np.ndarray:
|
||||
w = np.hanning(Y.shape[1])
|
||||
Fy = np.fft.rfft((Y - Y.mean(1, keepdims=True)) * w, NFFT)
|
||||
Fp = np.fft.rfft((P - P.mean(1, keepdims=True)) * w, NFFT)
|
||||
return np.real(np.conj(Fy) * Fp).sum(0)
|
||||
|
||||
|
||||
def s8(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||||
rows_all, run, _ = load_study(p, root, "S8")
|
||||
if run.empty:
|
||||
return {}, {"available": False}
|
||||
f = np.fft.rfftfreq(NFFT, 4.0 / 1000.0)
|
||||
f_c = 6.0
|
||||
budgets = study_budgets(p, "S8")
|
||||
cells, transfer, verdict = [], [], {"S8-H1": {"cells": {}}, "S8-H2": {"cells": {}}}
|
||||
for (reg, d, N), g in run.groupby(["regime", "delta_ms", "n_train"]):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"regime": reg, "delta_ms": d, "n_train": N, "n_rid": g.rid.nunique(), "n_seed": g.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
for a, b, tag in (("PM2", "Oracle", "pm_or"), ("BK2", "PM2", "bk_pm"), ("HM2", "PM2", "hm_pm"), ("BK2", "Oracle", "bk_or")):
|
||||
row |= {f"{tag}_{k}": v for k, v in pair(g, a, b, rng, n_boot).items()}
|
||||
# transfer Ĥ(f) relative to the Oracle predictions, pooled over rids, seeds and test wells
|
||||
S = {m: np.zeros(len(f)) for m in ("Oracle", "PM2", "BK2", "HM2")}
|
||||
for rid in sorted(g.rid.unique()):
|
||||
cell = Cell("S8", reg, None, 1.0, int(N), int(rid), tuple(p["studies"]["S8"]["methods"]), posterior="none", delta_ms=float(d))
|
||||
npz = train_paths(cell, root)["npz"]
|
||||
if not npz.exists():
|
||||
continue
|
||||
with np.load(npz) as z:
|
||||
Y = z["y_true"].astype(float)
|
||||
for m in S:
|
||||
for k in (k for k in z.files if k.startswith(f"{m}/s") and k.endswith(f"/b{budgets[m]}/mu")):
|
||||
S[m] += cross_spectrum(Y, z[k].astype(float))
|
||||
band = f >= f_c
|
||||
use = band & (S["Oracle"] >= 0.1 * S["Oracle"][band].max())
|
||||
lo, hi = 1000.0 / (2 * d), 3000.0 / (2 * d)
|
||||
flip = use & (f > lo) & (f < hi)
|
||||
for m in ("PM2", "BK2", "HM2"):
|
||||
H = S[m] / np.where(S["Oracle"] == 0, np.nan, S["Oracle"])
|
||||
theory = np.cos(np.pi * f * d / 1000.0)
|
||||
zero = f[band][np.flatnonzero(np.diff(np.sign(H[band])) != 0)[:1]]
|
||||
transfer.append({"regime": reg, "delta_ms": d, "n_train": N, "method": m, "flip_band_hz": [lo, hi], "n_freq_flip": int(flip.sum()),
|
||||
"mean_H_flip_band": float(np.nanmean(H[flip])) if flip.any() else float("nan"),
|
||||
"mean_cos_flip_band": float(theory[flip].mean()) if flip.any() else float("nan"),
|
||||
"first_zero_crossing_hz": float(zero[0]) if len(zero) else float("nan"), "theory_zero_hz": lo,
|
||||
"H": H.tolist(), "f_hz": f.tolist()})
|
||||
row[f"meanH_flip_{m}"] = transfer[-1]["mean_H_flip_band"]
|
||||
cells.append(row)
|
||||
if reg == "R10" and d == 32:
|
||||
verdict["S8-H1"]["cells"][int(N)] = {"mean_H_PM2_flip_band": row["meanH_flip_PM2"], "negative": bool(row["meanH_flip_PM2"] < 0)}
|
||||
if N == 16 and d in (16, 32):
|
||||
verdict["S8-H2"]["cells"][f"{reg}/d{d:g}"] = {"ratio_BK2_PM2": row.get("bk_pm_ratio"), "ci": [row.get("bk_pm_ratio_lo"), row.get("bk_pm_ratio_hi")],
|
||||
"better": bool(row.get("bk_pm_better", False))}
|
||||
cells = pd.DataFrame(cells)
|
||||
verdict["S8-H1"]["pass"] = all(v["negative"] for v in verdict["S8-H1"]["cells"].values()) if len(verdict["S8-H1"]["cells"]) == 2 else None
|
||||
d8 = cells[cells.delta_ms == 8]
|
||||
no_harm = float(d8.bk_pm_ratio.mean()) if len(d8) else float("nan")
|
||||
verdict["S8-H2"]["no_harm_mean_ratio_d8"] = no_harm
|
||||
verdict["S8-H2"]["pass"] = all(v["better"] for v in verdict["S8-H2"]["cells"].values()) if len(verdict["S8-H2"]["cells"]) == 4 else None
|
||||
verdict["S8-H2"]["d8_descriptive"] = {f"{r.regime}/n{int(r.n_train)}": [r.bk_pm_ratio, r.bk_pm_ratio_lo, r.bk_pm_ratio_hi] for r in d8.itertuples()}
|
||||
tr = pd.DataFrame(transfer)
|
||||
return {"s8_cells": cells, "s8_transfer": tr.drop(columns=["H", "f_hz"]) if len(tr) else tr,
|
||||
"s8_transfer_curves": tr}, verdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- equal-budget arm (disclosed, T2 v)
|
||||
|
||||
def equal_budget(p: dict, root: Path, rng, n_boot: int) -> pd.DataFrame:
|
||||
arm = p["training"].get("equal_budget_arm")
|
||||
if not arm:
|
||||
return pd.DataFrame()
|
||||
rows = []
|
||||
for study in p["studies"]:
|
||||
_, run, _ = load_study(p, root, study, arm=int(arm))
|
||||
if run.empty:
|
||||
continue
|
||||
keys = [k for k in ("regime", "preset", "delta_ms", "c", "n_train") if k in run.columns]
|
||||
for key, g in run.groupby(keys, dropna=False):
|
||||
mean = g.groupby("method")["band_rmse"].mean()
|
||||
row = {"study": study, "budget": int(arm)} | dict(zip(keys, key)) | {"n_rid": g.rid.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||||
sfx = "-TCN" if p["studies"][study].get("backbone", "cnngru") != "cnngru" else ""
|
||||
for a, b, tag in ((f"M2-Sa{sfx}", f"B3d-Sa{sfx}", "m2_pm"), (f"B3d-Sa{sfx}", f"Oracle{sfx}", "pm_or"), ("Ctl-GP", f"B3d-Sa{sfx}", "ctl_pm"),
|
||||
("BK2", "PM2", "bk_pm"), ("PM2", "Oracle", "pm2_or")):
|
||||
if a in mean.index and b in mean.index:
|
||||
row |= {f"{tag}_{k}": v for k, v in pair(g, a, b, rng, n_boot).items() if k in ("ratio", "ratio_lo", "ratio_hi", "better")}
|
||||
rows.append(row)
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- report
|
||||
|
||||
def _md(df: pd.DataFrame, cols=None, fmt: str = ".3f") -> str:
|
||||
if df is None or not len(df):
|
||||
return "(no data)"
|
||||
d = df[[c for c in cols if c in df.columns]] if cols else df
|
||||
return d.to_markdown(index=False, floatfmt=fmt)
|
||||
|
||||
|
||||
def summarize(p: dict, root: Path, n_boot: int = 2000, dev: bool = False, n_perm: int = 10000) -> dict:
|
||||
global USE_P2R
|
||||
USE_P2R = not dev
|
||||
out = root / "summary"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
rng = np.random.default_rng(0)
|
||||
tables, verdict = {}, {"protocol": "configs/protocol_bench.yaml", "dev": dev, "root": str(root)}
|
||||
sha = REPO_ROOT / "configs" / "protocol_bench.sha256"
|
||||
verdict["protocol_sha256"] = sha.read_text().split()[0] if sha.exists() else "UNLOCKED"
|
||||
for name, fn, extra in (("S1", s1, (n_perm,)), ("S2", s2, ()), ("S3", s3, ()), ("S4", s4, ()), ("S8", s8, ())):
|
||||
t, v = fn(p, root, rng, n_boot, *extra)
|
||||
tables |= t
|
||||
verdict[name] = v
|
||||
tables["equal_budget"] = equal_budget(p, root, rng, n_boot)
|
||||
for name, df in tables.items():
|
||||
if name == "s8_transfer_curves":
|
||||
(out / "s8_transfer_curves.json").write_text(df.to_json(orient="records"))
|
||||
elif isinstance(df, pd.DataFrame):
|
||||
df.to_csv(out / f"{name}.csv", index=False)
|
||||
(out / "verdict.json").write_text(json.dumps(verdict, indent=1, default=float))
|
||||
L = [f"# protocol_bench summary ({'DEV — never a result' if dev else 'main grid'})", "",
|
||||
"Rules of configs/protocol_bench.yaml applied as written. Realizations and seeds as recorded per cell.", ""]
|
||||
hyp = p["hypotheses"]
|
||||
for key in ("S1-H1", "S1-H2", "S2-H1", "S2-H2", "S3-H1", "S4-H1", "S4-H2", "S8-H1", "S8-H2"):
|
||||
v = verdict.get(key.split("-")[0], {})
|
||||
v = v.get(key, v) if key != "S3-H1" else v
|
||||
res = v.get("pass") if isinstance(v, dict) else None
|
||||
L.append(f"- **{key}** ({hyp[key]['kind']}): {'PASS' if res else 'FAIL' if res is False else 'not available'} — {hyp[key]['statement'].strip()[:160]}…")
|
||||
L.append("")
|
||||
sections = [("S1 cells (phase diagram)", "s1_cells", ["regime", "c", "n_train", "sigma_post_ms", "best_point_tie", "pm_best_ratio", "pm_best_ratio_lo", "pm_best_ratio_hi", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better", "n_rid"]),
|
||||
("S1 families (S1-H2)", "s1_families", None), ("S1 additivity (descriptive)", "s1_additivity", None),
|
||||
("S2 SMC diagnostics", "s2_smc", ["regime", "preset", "axis", "level", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90", "overconfidence", "phase_R_mean", "kappa_post", "r_post", "n_rid"]),
|
||||
("S2 cells", "s2_cells", ["regime", "preset", "axis", "level", "n_train", "best_point_tie", "pm_best_ratio", "pm_best_ratio_lo", "pm_best_ratio_hi", "pm_no_harm", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better", "wide", "n_rid"]),
|
||||
("S2 H2a rule per preset", "s2_h2a", ["regime", "preset", "axis", "level", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]),
|
||||
("S3 H2a rule with B4 competitors", "s3_h2a", ["regime", "c", "n_train", "best", "runner_up", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass", "flag"]),
|
||||
("S3 benchmark table (band RMSE)", "s3_table", None),
|
||||
("S3 control bank across the P2r grid (T2-1, disclosed)", "s3_control", ["regime", "c", "n_train", "ctl_pm_ratio", "ctl_pm_ratio_lo", "ctl_pm_ratio_hi", "ctl_pm_better", "m2_ctl_ratio", "m2_ctl_ratio_lo", "m2_ctl_ratio_hi", "m2_ctl_better", "m2_pm_ratio", "flag", "n_rid"]),
|
||||
("S4 cells (TCN)", "s4_cells", None), ("S4 H2a rule (TCN)", "s4_h2a", ["regime", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]),
|
||||
("S8 cells", "s8_cells", ["regime", "delta_ms", "n_train", "pm_or_ratio", "bk_pm_ratio", "bk_pm_ratio_lo", "bk_pm_ratio_hi", "bk_pm_better", "hm_pm_ratio", "meanH_flip_PM2", "meanH_flip_BK2", "n_rid"]),
|
||||
("S8 transfer", "s8_transfer", ["regime", "delta_ms", "n_train", "method", "n_freq_flip", "mean_H_flip_band", "mean_cos_flip_band", "first_zero_crossing_hz", "theory_zero_hz"]),
|
||||
("Equal-budget arm, 500 iterations for every method (disclosed, T2 v; no rule uses it)", "equal_budget", None)]
|
||||
for title, key, cols in sections:
|
||||
L += [f"## {title}", "", _md(tables.get(key), cols), ""]
|
||||
L += ["## Verdicts (json)", "", "```", json.dumps({k: v for k, v in verdict.items() if k.startswith("S")}, indent=1, default=float), "```", ""]
|
||||
(out / "summary.md").write_text("\n".join(L))
|
||||
print("\n".join(L[:14]))
|
||||
return verdict
|
||||
296
ml_porosity/benchmark/training.py
Normal file
296
ml_porosity/benchmark/training.py
Normal file
@@ -0,0 +1,296 @@
|
||||
"""Training of one protocol_bench cell: scripts/15_diag_train.py run_cell (variant "a": estR wavelet, γ = 1/κ) with
|
||||
three additions. (1) B4a–d from the protocol_p2 label banks (S3). (2) The S8 two-mode banks built from the true
|
||||
warp: per training well a side s = ±1 is drawn from a declared stream, the two modes are t_true and t_true + sΔ,
|
||||
PM2 labels sit at the posterior-mean warp t_true + sΔ/2, BK2 is the two-member bank with uniform π and the
|
||||
protocol λ, HM2 the same bank with the hard-min loss. (3) A second backbone (TCNHetero of ml_porosity/f3/training.py)
|
||||
trained with the same loop as bank_train.train_predict; the CNN-GRU path delegates to bank_train unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from ml_porosity.benchmark.cells import Cell
|
||||
from ml_porosity.benchmark.data import Inputs, load_script
|
||||
|
||||
REGISTER_METHODS = ("Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M1", "M2")
|
||||
POSTERIOR_METHODS = ("B3c-R", "B3d-Sa", "M2-Sa")
|
||||
TWO_MODE_METHODS = ("PM2", "BK2", "HM2")
|
||||
CONTROL_METHODS = ("Ctl-GP",)
|
||||
SIDE_STREAM = 20261030 # S8: rng [rid, SIDE_STREAM, 8, i] → side s_i = ±1 of training well i
|
||||
MIN_SLOPE_MS, MAX_ATTEMPTS = 0.05, 1280 # Ctl-GP: monotonicity guard and draw budget, as T2 (scripts/32)
|
||||
|
||||
|
||||
def budget_list(p: dict, method: str, backbone: str) -> list[int]:
|
||||
"""Registered budget plus, if declared, the equal-budget arm (one trajectory; predictions at both steps)."""
|
||||
b = {budget_of(p, method, backbone)}
|
||||
arm = p["training"].get("equal_budget_arm")
|
||||
if arm:
|
||||
b.add(int(arm))
|
||||
return sorted(b)
|
||||
|
||||
|
||||
def base_name(method: str) -> str:
|
||||
return method.removesuffix("-TCN")
|
||||
|
||||
|
||||
def budget_of(p: dict, method: str, backbone: str) -> int:
|
||||
b = base_name(method)
|
||||
if backbone != "cnngru":
|
||||
alt = p["training"].get(f"budgets_{backbone}") or {}
|
||||
if alt.get(b) is not None:
|
||||
return int(alt[b])
|
||||
return int(p["training"]["budgets"][b])
|
||||
|
||||
|
||||
def train_predict_tcn(X, Xte, spec: dict, cfg: dict, seed: int, budgets: list[int], device: str) -> dict:
|
||||
"""bank_train.train_predict with TCNHetero (f3.training) in place of CNNGRUHetero; cudnn deterministic as f3."""
|
||||
from ml_porosity.f3.training import TCNHetero
|
||||
from ml_porosity.losses.rml import bank_loss, gather_windows
|
||||
from ml_porosity.losses.softdtw import dilate_loss_fast, softdtw_loss_fast
|
||||
from ml_porosity.models.bank_train import WIN, window_starts_fixed
|
||||
from ml_porosity.models.train import predict
|
||||
|
||||
torch.backends.cudnn.benchmark = False
|
||||
torch.backends.cudnn.deterministic = True
|
||||
torch.default_generator.manual_seed(seed)
|
||||
if torch.device(device).type == "cuda":
|
||||
torch.cuda.set_device(device)
|
||||
torch.cuda.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
|
||||
x = T(X)
|
||||
N, _, L = X.shape
|
||||
starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device)
|
||||
kind = spec["kind"]
|
||||
if kind == "bank":
|
||||
Y, logpi, lam = T(spec["Y"]), T(spec["logpi"]), spec["lam"]
|
||||
loss_fn = lambda mu, s: bank_loss(mu, s, Y, logpi, starts, WIN, lam)
|
||||
elif kind in ("softdtw", "dilate"):
|
||||
yw = gather_windows(T(spec["Y"]).reshape(N, L), starts, WIN).reshape(-1, WIN)
|
||||
f = softdtw_loss_fast if kind == "softdtw" else dilate_loss_fast
|
||||
kw = {k: spec[k] for k in ("gamma", "band", "alpha") if k in spec}
|
||||
loss_fn = lambda mu, s: f(gather_windows(mu, starts, WIN).reshape(-1, WIN),
|
||||
gather_windows(s, starts, WIN).reshape(-1, WIN), yw, **kw)
|
||||
else:
|
||||
raise ValueError(kind)
|
||||
model = TCNHetero(X.shape[1], cfg["d_channels"], cfg["p_dropout"]).to(device)
|
||||
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
|
||||
out = {}
|
||||
for step in range(1, max(budgets) + 1):
|
||||
model.train()
|
||||
opt.zero_grad()
|
||||
mu, s = model(x)
|
||||
loss = loss_fn(mu[:, 0], s[:, 0])
|
||||
if not torch.isfinite(loss):
|
||||
raise FloatingPointError(f"non-finite loss at step {step}")
|
||||
loss.backward()
|
||||
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
|
||||
opt.step()
|
||||
if step in budgets:
|
||||
out[step] = predict(model, Xte, device)
|
||||
return out
|
||||
|
||||
|
||||
def train_predict_any(X, Xte, spec, cfg, seed, budgets, device, backbone: str) -> dict:
|
||||
if backbone == "cnngru":
|
||||
from ml_porosity.models.bank_train import train_predict
|
||||
return train_predict(X, Xte, spec, cfg, seed, budgets, device)
|
||||
if backbone == "tcn":
|
||||
return train_predict_tcn(X, Xte, spec, cfg, seed, budgets, device)
|
||||
raise ValueError(backbone)
|
||||
|
||||
|
||||
def posterior_banks(R, obs: list[dict], out: dict, reg: dict, ph: dict, smc, reg_seed: int, diag: list[dict]) -> tuple[dict, list]:
|
||||
"""B3c-R, B3d-Sa (mean of all particles) and M2-Sa (S particles without replacement, rng [reg_seed, i, 29],
|
||||
uniform π) exactly as scripts/15 (variant a: estR, g_acf). Appends per-well diagnostics to `diag`."""
|
||||
from ml_porosity.data.wavelet import statistical_wavelet
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.smc import phase_basis, phase_wavelet
|
||||
from ml_porosity.registration.tie_likelihood import synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors, warp_mean
|
||||
|
||||
cfg = R.cfg
|
||||
f, fac = cfg["fine_dt_ms"], int(round(R.dt / cfg["fine_dt_ms"]))
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"])
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
err = lambda t, o: warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
banks, logpi = {"B3c-R": [], "B3d-Sa": [], "M2-Sa": []}, []
|
||||
for i, o in enumerate(obs):
|
||||
y_aa = antialias(o["phi_log"], f, R.dt)
|
||||
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wR)[0]
|
||||
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
banks["B3c-R"].append(lab(y_aa, t3c))
|
||||
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
|
||||
tm = warp_mean(Tf, np.zeros(len(Tf)))
|
||||
banks["B3d-Sa"].append(lab(y_aa, tm))
|
||||
sub = np.random.default_rng([reg_seed, i, 29]).choice(len(Tf), reg["S"], replace=False)
|
||||
Y = lab(y_aa, Tf[sub])
|
||||
ok = np.all(np.isfinite(Y), 1)
|
||||
Y[~ok] = Y[ok][0]
|
||||
banks["M2-Sa"].append(Y)
|
||||
logpi.append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum()))
|
||||
diag[i] |= {"phase_R": ph["phase_R"], "B3c-R_warp_rmse_ms": err(t3c, o), "B3d-Sa_warp_rmse_ms": err(tm, o),
|
||||
"M2-Sa_n_valid": int(ok.sum()),
|
||||
"sigma_post_ms": warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_width90_ms"] / 3.29}
|
||||
return banks, logpi
|
||||
|
||||
|
||||
def control_gp_bank(R, obs: list[dict], smc: dict, reg: dict, reg_seed: int, diag: list[dict]) -> tuple[list, list]:
|
||||
"""Ctl-GP (T2 test ii, scripts/32 control_bank): S warps T̄ + η_s, η_s Gaussian with the empirical mean and
|
||||
covariance of the SMC particles on the warp grid (no information beyond the first two moments; no link between
|
||||
a member and the seismic). rng [reg_seed, i, 2029]; a draw is kept if t(τ) is strictly increasing (slope >
|
||||
MIN_SLOPE_MS per node), else redrawn (≤ MAX_ATTEMPTS); fallback: Gaussian in u = [b, g] (monotone by
|
||||
construction), flagged. Labels and invalid members as the SMC bank."""
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
|
||||
f = R.cfg["fine_dt_ms"]
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
banks, logpi = [], []
|
||||
for i, o in enumerate(obs):
|
||||
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
|
||||
Tg = R.grid.t_of_tau(U[:, 0], U[:, 1:])
|
||||
Tbar = Tg.mean(0)
|
||||
lam, V = np.linalg.eigh(np.cov(Tg.T, ddof=0))
|
||||
Lm = V * np.sqrt(np.clip(lam, 0.0, None))[None, :]
|
||||
rng = np.random.default_rng([reg_seed, i, 2029])
|
||||
members, n_rej, attempts = [], 0, 0
|
||||
while len(members) < reg["S"] and attempts < MAX_ATTEMPTS:
|
||||
t = Tbar + Lm @ rng.standard_normal(len(Tbar))
|
||||
attempts += 1
|
||||
if np.all(np.diff(t) > MIN_SLOPE_MS):
|
||||
members.append(t)
|
||||
else:
|
||||
n_rej += 1
|
||||
fallback = len(members) < reg["S"]
|
||||
if fallback:
|
||||
lu, Vu = np.linalg.eigh(np.cov(U.T, ddof=0))
|
||||
Lu = Vu * np.sqrt(np.clip(lu, 0.0, None))[None, :]
|
||||
ubar = U.mean(0)
|
||||
while len(members) < reg["S"]:
|
||||
u = ubar + Lu @ rng.standard_normal(len(ubar))
|
||||
members.append(R.grid.t_of_tau(u[0], u[1:])[0])
|
||||
Tc_grid = np.stack(members)
|
||||
Tc = np.stack([np.interp(R.tau_fine, R.grid.tau, t) for t in Tc_grid])
|
||||
Y = lab(antialias(o["phi_log"], f, R.dt), Tc)
|
||||
ok = np.all(np.isfinite(Y), 1)
|
||||
Y[~ok] = Y[ok][0]
|
||||
banks.append(Y)
|
||||
logpi.append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum()))
|
||||
diag[i] |= {"Ctl-GP_n_valid": int(ok.sum()), "Ctl-GP_n_rejected": n_rej, "Ctl-GP_fallback_u": bool(fallback),
|
||||
"Ctl-GP_sd_ratio": float(Tc_grid.std(0).mean() / Tg.std(0).mean())}
|
||||
return banks, logpi
|
||||
|
||||
|
||||
def two_mode_banks(R, obs: list[dict], delta_ms: float, diag: list[dict]) -> dict:
|
||||
"""S8 controlled cycle skip: modes t_true and t_true + s·Δ (s = ±1 per training well from rng
|
||||
[rid, SIDE_STREAM, 8, i]); PM2 at the mean warp t_true + sΔ/2; BK2/HM2 the two-member bank."""
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.ties import warp_errors
|
||||
|
||||
f = R.cfg["fine_dt_ms"]
|
||||
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
|
||||
banks = {"PM2": [], "BK2": []}
|
||||
for i, o in enumerate(obs):
|
||||
s = int(np.random.default_rng([R.rid, SIDE_STREAM, 8, i]).integers(2)) * 2 - 1
|
||||
y_aa = antialias(o["phi_log"], f, R.dt)
|
||||
t_true = o["t_of_tau_true"]
|
||||
Ypm = lab(y_aa, t_true + s * delta_ms / 2.0)
|
||||
Ybk = lab(y_aa, np.stack([t_true, t_true + s * delta_ms]))
|
||||
if not (np.all(np.isfinite(Ypm)) and np.all(np.isfinite(Ybk))):
|
||||
raise ValueError(f"{o['name']}: two-mode labels leave the label support at Δ = {delta_ms} ms")
|
||||
banks["PM2"].append(Ypm)
|
||||
banks["BK2"].append(Ybk)
|
||||
diag[i] |= {"delta_ms": delta_ms, "side": s,
|
||||
"PM2_warp_rmse_ms": warp_errors((t_true + s * delta_ms / 2.0)[None], R.tau_fine, t_true, R.t_main)["warp_rmse_ms"]}
|
||||
return banks
|
||||
|
||||
|
||||
def train_cell(cell: Cell, p: dict, inp: Inputs, device: str, post: dict[str, Path] | None, save_preds: bool = True,
|
||||
seeds=None, budget_lists: dict[str, list[int]] | None = None) -> tuple[list[dict], list[dict], dict, dict]:
|
||||
"""Returns (rows, diag, preds, meta). rows: one per (seed, method, budget, test well) with the P2r metrics.
|
||||
budget_lists (dev only): {method: [budgets]} evaluated along one trajectory instead of the locked budget."""
|
||||
from ml_porosity.models.bank_train import zscore_patch
|
||||
from ml_porosity.registration.pipeline import register
|
||||
|
||||
run_d2 = load_script("11_run_d2.py")
|
||||
t0 = time.time()
|
||||
P2, reg, tcfg = inp.P2, inp.reg, inp.tcfg
|
||||
reg_seed = int(p["registration"]["reg_seed"])
|
||||
seeds = list(p["grid"]["seeds"] if seeds is None else seeds)
|
||||
R = inp.realization(cell.rid, cell.preset)
|
||||
obs, test = inp.observe(R, cell.c, cell.regime, cell.n_train)
|
||||
X = np.stack([zscore_patch(o["seis"], R.main) for o in obs])
|
||||
Xte = np.stack([zscore_patch(o["seis"], R.main) for o in test])
|
||||
yt = 100 * np.stack([o["y_true"] for o in test])
|
||||
N = len(obs)
|
||||
out = register(R, obs, reg, reg_seed)
|
||||
m0, s0 = out["norm"]
|
||||
key = dict(rid=cell.rid, c=cell.c, n_train=N)
|
||||
diag = [key | {"reg_seed": reg_seed, "phase": out["phase"], "lam": out["lam"], "tau_c": out["tau_c"], "well": o["name"],
|
||||
"preset": cell.preset or "nominal", "backbone": cell.backbone} for o in obs]
|
||||
methods = [base_name(m) for m in cell.methods]
|
||||
specs = {}
|
||||
old = [m for m in methods if m in REGISTER_METHODS]
|
||||
if old:
|
||||
specs |= run_d2.method_specs(out, P2, old)
|
||||
single = lambda Y: {"kind": "bank", "Y": Y, "logpi": np.zeros((N, 1), np.float32), "lam": out["lam"]}
|
||||
nb = lambda v: ((np.stack(v) - m0) / s0).astype(np.float32)
|
||||
meta = {}
|
||||
if any(m in POSTERIOR_METHODS + CONTROL_METHODS for m in methods):
|
||||
if post is None:
|
||||
raise RuntimeError(f"{cell.tag}: posterior methods requested without a posterior directory")
|
||||
ph = json.loads(post["phase"].read_text())
|
||||
if ph["phase0"] != out["phase"]:
|
||||
raise RuntimeError(f"{cell.tag}: register phase ({out['phase']}) differs from the posterior run ({ph['phase0']})")
|
||||
with np.load(post["particles"]) as smc:
|
||||
smc = {k: smc[k] for k in smc.files}
|
||||
banks, logpi = posterior_banks(R, obs, out, reg, ph, smc, reg_seed, diag)
|
||||
specs["B3c-R"] = single(nb(banks["B3c-R"]))
|
||||
specs["B3d-Sa"] = single(nb(banks["B3d-Sa"]))
|
||||
specs["M2-Sa"] = {"kind": "bank", "Y": nb(banks["M2-Sa"]), "logpi": np.stack(logpi).astype(np.float32), "lam": out["lam"]}
|
||||
meta["posterior"] = str(post["particles"])
|
||||
if any(m in CONTROL_METHODS for m in methods):
|
||||
yc, lpc = control_gp_bank(R, obs, smc, reg, reg_seed, diag)
|
||||
specs["Ctl-GP"] = {"kind": "bank", "Y": nb(yc), "logpi": np.stack(lpc).astype(np.float32), "lam": out["lam"]}
|
||||
if any(m in TWO_MODE_METHODS for m in methods):
|
||||
banks = two_mode_banks(R, obs, float(cell.delta_ms), diag)
|
||||
specs["PM2"] = single(nb(banks["PM2"]))
|
||||
Ybk = nb(banks["BK2"])
|
||||
lp = np.full((N, 2), -np.log(2.0), np.float32)
|
||||
specs["BK2"] = {"kind": "bank", "Y": Ybk, "logpi": lp, "lam": out["lam"]}
|
||||
specs["HM2"] = {"kind": "bank", "Y": Ybk, "logpi": lp, "lam": None}
|
||||
missing = [m for m in methods if m not in specs]
|
||||
if missing:
|
||||
raise ValueError(f"no label specification for methods {missing}")
|
||||
rows, preds = [], {}
|
||||
suffix = "" if cell.backbone == "cnngru" else f"-{cell.backbone.upper()}"
|
||||
for seed in seeds:
|
||||
for m in methods:
|
||||
bud = list(budget_lists[m]) if budget_lists else budget_list(p, m, cell.backbone)
|
||||
for b, (mu, sg) in train_predict_any(X, Xte, specs[m], tcfg, seed, bud, device, cell.backbone).items():
|
||||
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
|
||||
name = m + suffix
|
||||
for w, r in zip(R.test, run_d2.evaluate(yt, mu_p, sg_p, inp.f_c)):
|
||||
rows.append(key | {"seed": seed, "method": name, "budget": b, "test_well": w.name,
|
||||
"regime": cell.regime, "preset": cell.preset or "nominal", "study": cell.study,
|
||||
"delta_ms": cell.delta_ms} | r)
|
||||
if save_preds:
|
||||
preds[f"{name}/s{seed}/b{b}/mu"] = mu_p.astype(np.float32)
|
||||
preds[f"{name}/s{seed}/b{b}/sigma"] = sg_p.astype(np.float32)
|
||||
preds = {"y_true": yt.astype(np.float32), "test_wells": np.array([w.name for w in R.test])} | preds
|
||||
meta |= {"wall_seconds": time.time() - t0, "device": device, "seeds": seeds, "methods": [m + suffix for m in methods],
|
||||
"budgets": {m + suffix: (list(budget_lists[m]) if budget_lists else budget_list(p, m, cell.backbone)) for m in methods},
|
||||
"registered_budgets": {m + suffix: budget_of(p, m, cell.backbone) for m in methods},
|
||||
"phase": out["phase"],
|
||||
"lam": out["lam"], "misspec_active": R.misspec_active, "n_train": N, "backbone": cell.backbone}
|
||||
return rows, diag, preds, meta
|
||||
Reference in New Issue
Block a user