Experiments declared and hashed before computing (docs/research/gp-review-*.md). The SMC-mean gain holds against a practitioner tie, all budgets and a same-target point tie, but is lost at anchor errors of 2 ms or less and reverses with per-well bulk error. No locked protocol, verdict or threshold changed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
526 lines
32 KiB
Python
526 lines
32 KiB
Python
"""S7 packaging of protocol_bench (phase P6): the registration-aware benchmark as files, with one command to generate
|
||
the tasks and one command to score predictions against the reference methods.
|
||
|
||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/37_bench_package.py generate [--out DIR] [--split test dev]
|
||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/37_bench_package.py tables [--out DIR]
|
||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/37_bench_package.py score --pred DIR --name NAME [--out DIR]
|
||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/37_bench_package.py selftest [--out DIR]
|
||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/37_bench_package.py check [--out DIR]
|
||
|
||
DIR defaults to outputs/bench/package. Documentation for users of the benchmark: benchmark/README.md.
|
||
|
||
generate One npz per task (setting, c, realization) in DIR/tasks/<split>/<setting>/, the hidden truth in
|
||
DIR/truth/<split>/<setting>/, the generator inputs and the analyst's knowledge in DIR/inputs/, an index
|
||
(DIR/tasks/index.csv) and DIR/MANIFEST.json. The manifest records the sha256 of the array content of each
|
||
file (key, dtype, shape, bytes; independent of zip metadata). The first run writes benchmark/MANIFEST.json
|
||
(tracked in git); later runs must reproduce it exactly or fail (--update-manifest overwrites it).
|
||
Observations are those of the runner (ml_porosity.benchmark.data.Inputs.observe): the 16 pool wells (a
|
||
task with N training wells uses the first N) and the 8 test wells at the regime SNR.
|
||
tables Reference runs of every method of protocol_p2r and protocol_bench at its registered budget, one row per
|
||
(setting, c, N, realization, seed, method) → DIR/reference/runs.csv.gz, and the per-cell means with σ_post
|
||
→ benchmark/reference/cells.csv and benchmark/reference/main_table.md (and copies in DIR/reference/).
|
||
score Predictions <pred>/<split>/<setting>/r{rid}_c{c}_n{N}_s{seed}.npz with `mu` (8, 126) and optionally `sigma`
|
||
(8, 126), porosity in p.u., test wells in task order. Metrics are those of the runner (scripts/11 evaluate).
|
||
On the test split the locked rules of ml_porosity/benchmark/summary.py are applied per cell: the H2a cell
|
||
rule against the best point tie {B3b, B3c, B3c-R}, and the `better` rule against B3d-Sa, M2-Sa, Oracle
|
||
(PM2, BK2, Oracle in the two-mode settings). Scorer v1.1 (17/11/2026, after the Geophysical Prospecting
|
||
review) adds the anchor mean B3d: the same H2a cell rule against the best of {B3b, B3c, B3c-R, B3d}
|
||
(rule_point_ties_anchor.csv; only the nominal settings have B3d) and the `better` rule against B3d. The v1
|
||
outputs are unchanged and no task file or hash changed. Reference rows are restricted to the submitted
|
||
realizations and seeds. Bootstrap CIs use one generator (rng 0) per cell, so they can differ slightly from
|
||
the summary tables; no rule uses a CI. → <pred>/score/
|
||
selftest Writes saved predictions of reference methods as a submission (S1 R10 c = 1.5, S2 R10 wv_L1, P2r R10 c = 1,
|
||
S8 R10 Δ = 16), scores it, and checks that metrics and rule outputs equal those of the reference runs and
|
||
that the package truth equals the y_true saved by the runner; v1.1 also checks the anchor-mean rule.
|
||
check Recomputes the content hashes of DIR against benchmark/MANIFEST.json (for a downloaded copy).
|
||
|
||
Outside the code hash of the protocol_bench lock (scripts/34 and ml_porosity/ only); generate and tables check the
|
||
lock first. Nothing here trains a model or changes a locked output.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import math
|
||
import re
|
||
import shutil
|
||
from pathlib import Path
|
||
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
from ml_porosity.benchmark import summary as S
|
||
from ml_porosity.benchmark.cells import bench_root
|
||
from ml_porosity.benchmark.data import load_inputs, load_script
|
||
from ml_porosity.benchmark.protocol import freeze, load_protocol
|
||
from ml_porosity.benchmark.training import SIDE_STREAM
|
||
from ml_porosity.data import synth_d2
|
||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||
|
||
PKG = outputs_dir() / "bench" / "package"
|
||
DOC = REPO_ROOT / "benchmark"
|
||
GAUSS = ["nll", "crps", "mean_sigma", "coverage_50", "coverage_80", "coverage_90", "coverage_95"]
|
||
CELL = ["setting", "c", "n_train"]
|
||
RUN = ["setting", "c", "n_train", "rid", "seed", "method"]
|
||
PRED = re.compile(r"r(\d+)_c([\d.]+)_n(\d+)_s(\d+)")
|
||
WIDE_MS = 1.5 # rules.wide of protocol_bench
|
||
N_BOOT = 2000
|
||
SCORER_VERSION = "1.1" # 1.0: 02/11/2026; 1.1: anchor mean B3d added as a competitor (17/11/2026)
|
||
ANCHOR_TIES = [*S.POINT_TIES, "B3d"]
|
||
SIGMA_A_STRESS = (3.5, 14.0) # σ_a stated in the task file of the settings R10__sa3.5 and R10__sa14 (true value 7 ms)
|
||
|
||
|
||
# ---------------------------------------------------------------- tasks
|
||
|
||
def settings(p: dict) -> list[dict]:
|
||
"""Every (regime, preset, Δ) of the benchmark with its drift factors: S1 (nominal), S2 (presets), S8 (two-mode)."""
|
||
st = p["studies"]
|
||
out = [dict(setting=r, regime=r, preset="nominal", delta_ms=None, cs=st["S1"]["drift_factors"]) for r in p["grid"]["regimes"]]
|
||
out += [dict(setting=f"{r}__{pr}", regime=r, preset=pr, delta_ms=None, cs=st["S2"]["drift_factors"])
|
||
for r in st["S2"]["regimes"] for axis in st["S2"]["presets"].values() for pr in axis]
|
||
out += [dict(setting=f"{r}__s8d{d:g}", regime=r, preset="nominal", delta_ms=float(d), cs=st["S8"]["drift_factors"])
|
||
for r in st["S8"]["regimes"] for d in st["S8"]["delta_ms"]]
|
||
# σ_a stress (added 10/11/2026, after review): the data are those of R10, c = 1; the task file states the wrong σ_a
|
||
out += [dict(setting=f"R10__sa{v:g}", regime="R10", preset="nominal", delta_ms=None, cs=[1.0], sigma_a_stated=v, tag=f"sa{v:g}")
|
||
for v in SIGMA_A_STRESS]
|
||
return out
|
||
|
||
|
||
def task_arrays(inp, R, s: dict, c: float) -> tuple[dict, dict]:
|
||
reg = inp.regime(s["regime"])
|
||
obs, test = inp.observe(R, c, s["regime"], len(R.pool))
|
||
task = {"rid": np.int64(R.rid), "c": np.float64(c), "snr_db": np.float64(reg["snr_db"]),
|
||
"anchor_density": np.array(reg["anchor_density"]), "sigma_a_ms": np.float64(s.get("sigma_a_stated", inp.sigma_a)),
|
||
"t_seis_ms": R.t_ext, "t_label_ms": R.t_main, "tau_ms": R.tau_fine,
|
||
"train_names": np.array([o["name"] for o in obs]), "train_seis": np.stack([o["seis"] for o in obs]),
|
||
"train_phi_log": np.stack([o["phi_log"] for o in obs]), "train_ai_log": np.stack([o["ai_log"] for o in obs]),
|
||
"train_ilxl": np.array([[w.il, w.xl] for w in R.pool]), "train_xy": np.array([[w.x, w.y] for w in R.pool]),
|
||
"anchor_well": np.concatenate([np.full(len(o["tau_k"]), i) for i, o in enumerate(obs)]),
|
||
"anchor_tau_ms": np.concatenate([o["tau_k"] for o in obs]), "anchor_t_ms": np.concatenate([o["t_k"] for o in obs]),
|
||
"test_names": np.array([o["name"] for o in test]), "test_seis": np.stack([o["seis"] for o in test]),
|
||
"test_ilxl": np.array([[w.il, w.xl] for w in R.test]), "test_xy": np.array([[w.x, w.y] for w in R.test])}
|
||
truth = {"y_test": 100 * np.stack([o["y_true"] for o in test]), "test_names": task["test_names"],
|
||
"train_t_of_tau_ms": np.stack([o["t_of_tau_true"] for o in obs]),
|
||
"train_b_ms": np.array([o["b"] for o in obs]), "train_g": np.stack([o["g"] for o in obs])}
|
||
if s["delta_ms"] is not None: # S8: modes t_true and t_true + s·Δ (training.two_mode_banks)
|
||
d = s["delta_ms"]
|
||
side = np.array([int(np.random.default_rng([R.rid, SIDE_STREAM, 8, i]).integers(2)) * 2 - 1 for i in range(len(obs))])
|
||
task |= {"delta_ms": np.float64(d),
|
||
"two_mode_t_of_tau_ms": np.stack([np.stack([o["t_of_tau_true"], o["t_of_tau_true"] + si * d])
|
||
for o, si in zip(obs, side)])}
|
||
truth["two_mode_side"] = side
|
||
return task, truth
|
||
|
||
|
||
def content_sha(arrs: dict) -> str:
|
||
h = hashlib.sha256()
|
||
for k in sorted(arrs):
|
||
a = np.ascontiguousarray(np.asarray(arrs[k]))
|
||
h.update(f"{k}|{a.dtype.str}|{a.shape}|".encode())
|
||
h.update(a.tobytes())
|
||
return h.hexdigest()
|
||
|
||
|
||
def npz_sha(f: Path) -> str:
|
||
with np.load(f) as z:
|
||
return content_sha({k: z[k] for k in z.files})
|
||
|
||
|
||
def file_sha(f: Path) -> str:
|
||
return hashlib.sha256(f.read_bytes()).hexdigest()
|
||
|
||
|
||
def analyst(p: dict, inp) -> dict:
|
||
"""What a method may assume: the analyst's (nominal) wavelet, warp prior, anchor noise and rock physics."""
|
||
cfg, wp = inp.cfg, p["inputs"]["warp_prior"]
|
||
return {
|
||
"units": {"time": "ms two-way time", "tau": "ms sonic time τ of the logs (0.5 ms grid)",
|
||
"labels": "porosity in percent (p.u.) = 100 × fraction", "phi_log": "porosity fraction"},
|
||
"seismic": {"dt_ms": cfg["dt_ms"], "window_ms": cfg["ext_window_ms"], "label_window_ms": cfg["main_window_ms"],
|
||
"patch": "3 × 3 traces around each well: inline offset −1..1 (outer) × crossline offset −1..1 "
|
||
"(inner); the centre trace is index 4; labels refer to the centre trace"},
|
||
"anchors": {"sigma_a_ms": inp.sigma_a,
|
||
"model": "unit-boundary picks: anchor_tau_ms exact on the log, anchor_t_ms = true time + N(0, σ_a²)",
|
||
"note": "the σ_a to use is the `sigma_a_ms` of the task file; it equals sigma_a_ms here except in the settings "
|
||
"R10__sa3.5 and R10__sa14, where it is deliberately wrong (the picks were generated with the value "
|
||
"given here)"},
|
||
"rock_physics_nominal": {"phi_dt": [synth_d2.PHI_DT_A, synth_d2.PHI_DT_B], "rhob": [synth_d2.RHO_0, synth_d2.RHO_1],
|
||
"formula": "DT = (φ − A)/B µs/m; RHOB = ρ0 − ρ1·φ kg/m³; AI = RHOB·1e6/DT; "
|
||
"train_ai_log = AI(train_phi_log)"},
|
||
"wavelet_nominal": {"file": "inputs/wavelets.npz", "key": p["inputs"]["wavelet"]["key"], "dt_ms": cfg["dt_ms"],
|
||
"note": "zero phase; the reference registrations re-estimate a constant phase on a 15° grid"},
|
||
"warp_prior": {"file": "inputs/warp_prior_f3.json", "fit": wp["fit"], "hyper": inp.prior_hyper,
|
||
"sigma_b_ms": inp.reg["sigma_b_ms"],
|
||
"model": "t(τ) = b + ∫ exp(g) dτ on a 4 ms τ grid; g a stationary GP (fit), b ~ N(0, σ_b²)"},
|
||
"metric": {"primary": "band RMSE: RMSE after a 4th-order zero-phase Butterworth high-pass at f_c, mean over "
|
||
"the 8 test wells", "f_c_hz": inp.f_c, "secondary": "band PCC"},
|
||
}
|
||
|
||
|
||
def generate(a) -> None:
|
||
if not a.skip_lock_check:
|
||
freeze(check=True)
|
||
p = load_protocol()
|
||
inp = load_inputs(p)
|
||
out = Path(a.out)
|
||
rids = {"test": p["grid"]["realizations"], "dev": p["grid"]["dev_realizations"]}
|
||
for d in ("tasks", "truth"):
|
||
for sp in a.split:
|
||
shutil.rmtree(out / d / sp, ignore_errors=True)
|
||
rows, files = [], {}
|
||
for sp in a.split:
|
||
for rid in rids[sp]:
|
||
cache = {}
|
||
for s in settings(p):
|
||
R = cache.get(s["preset"]) or cache.setdefault(s["preset"], inp.realization(rid, None if s["preset"] == "nominal" else s["preset"]))
|
||
for c in s["cs"]:
|
||
task, truth = task_arrays(inp, R, s, float(c))
|
||
rel = Path(sp) / s["setting"] / f"r{rid}_c{float(c):g}.npz"
|
||
for d, arr in (("tasks", task), ("truth", truth)):
|
||
(out / d / rel).parent.mkdir(parents=True, exist_ok=True)
|
||
np.savez_compressed(out / d / rel, **arr)
|
||
files[f"{d}/{rel}"] = content_sha(arr)
|
||
rows.append({"split": sp, "setting": s["setting"], "regime": s["regime"], "preset": s.get("tag", s["preset"]),
|
||
"delta_ms": s["delta_ms"], "c": float(c), "rid": rid, "snr_db": float(task["snr_db"]),
|
||
"anchor_density": str(task["anchor_density"]), "n_pool": len(task["train_names"]),
|
||
"n_test": len(task["test_names"]), "n_anchors": len(task["anchor_tau_ms"]),
|
||
"task": f"tasks/{rel}", "truth": f"truth/{rel}"})
|
||
print(f"{sp} r{rid}: {sum(r['rid'] == rid and r['split'] == sp for r in rows)} tasks", flush=True)
|
||
idx = pd.DataFrame(rows)
|
||
if (out / "tasks" / "index.csv").exists(): # keep the rows of splits not regenerated
|
||
old = pd.read_csv(out / "tasks" / "index.csv")
|
||
idx = pd.concat([old[~old.split.isin(a.split)], idx], ignore_index=True)
|
||
idx.to_csv(out / "tasks" / "index.csv", index=False)
|
||
|
||
src = out / "inputs"
|
||
src.mkdir(parents=True, exist_ok=True)
|
||
for k in ("d2_config", "warp_prior", "wavelet", "horizon_cache"):
|
||
shutil.copy2(REPO_ROOT / p["inputs"][k]["path"], src / Path(p["inputs"][k]["path"]).name)
|
||
shutil.copy2(REPO_ROOT / "configs" / "protocol_bench.yaml", src / "protocol_bench.yaml")
|
||
(src / "analyst.json").write_text(json.dumps(analyst(p, inp), indent=1, ensure_ascii=False, default=float))
|
||
|
||
old = json.loads((out / "MANIFEST.json").read_text()) if (out / "MANIFEST.json").exists() else {}
|
||
keep = {k: v for k, v in old.get("files", {}).items() if k.split("/")[1] not in a.split}
|
||
lock = json.loads((REPO_ROOT / "configs" / "protocol_bench.lock.json").read_text())
|
||
man = {"benchmark": "protocol_bench v1 (registration-aware D2 benchmark)", "protocol_sha256": lock["protocol_sha256"],
|
||
"code_sha256_at_lock": lock["code_sha256"], "hash": "sha256 of array content: for each key in sorted order, "
|
||
"'key|dtype|shape|' then the C-order bytes (scripts/37_bench_package.py content_sha)",
|
||
"inputs": {f"inputs/{f.name}": file_sha(f) for f in sorted(src.iterdir()) if f.name != "analyst.json"},
|
||
"splits": {sp: rids[sp] for sp in sorted(set(old.get("splits", {})) | set(a.split))},
|
||
"scorer_version": SCORER_VERSION, "n_tasks": int(len(idx)), "files": dict(sorted((keep | files).items()))}
|
||
(out / "MANIFEST.json").write_text(json.dumps(man, indent=1))
|
||
ref = DOC / "MANIFEST.json"
|
||
if ref.exists() and not a.update_manifest:
|
||
want = json.loads(ref.read_text())
|
||
bad = [k for k, v in man["files"].items() if want["files"].get(k) != v]
|
||
bad += [k for k in want["files"] if k.split("/")[1] in a.split and k not in man["files"]]
|
||
if bad or want["inputs"] != man["inputs"]:
|
||
raise SystemExit(f"generated content differs from benchmark/MANIFEST.json: {len(bad)} files, e.g. {bad[:3]}; "
|
||
f"inputs equal: {want['inputs'] == man['inputs']}")
|
||
print(f"content hashes equal to benchmark/MANIFEST.json ({len(man['files'])} files)")
|
||
else:
|
||
DOC.mkdir(exist_ok=True)
|
||
shutil.copy2(out / "MANIFEST.json", ref)
|
||
print(f"wrote benchmark/MANIFEST.json ({len(man['files'])} files)")
|
||
if (DOC / "README.md").exists():
|
||
shutil.copy2(DOC / "README.md", out / "README.md")
|
||
print(f"{len(idx)} tasks → {out}")
|
||
|
||
|
||
def check(a) -> None:
|
||
out, want = Path(a.out), json.loads((DOC / "MANIFEST.json").read_text())
|
||
bad = [k for k, v in want["files"].items() if not (out / k).exists() or npz_sha(out / k) != v]
|
||
bad += [k for k, v in want["inputs"].items() if not (out / k).exists() or file_sha(out / k) != v]
|
||
print(f"{len(want['files']) + len(want['inputs']) - len(bad)}/{len(want['files']) + len(want['inputs'])} files match")
|
||
if bad:
|
||
raise SystemExit(f"mismatch: {bad[:10]}")
|
||
|
||
|
||
# ---------------------------------------------------------------- reference tables
|
||
|
||
def setting_of(df: pd.DataFrame) -> pd.Series:
|
||
preset = df["preset"].fillna("nominal")
|
||
d = df["delta_ms"] if "delta_ms" in df else pd.Series(np.nan, index=df.index)
|
||
s8 = df["regime"] + "__s8d" + d.map(lambda x: f"{x:g}" if pd.notna(x) else "")
|
||
return pd.Series(np.where(d.notna(), s8, np.where(preset == "nominal", df["regime"], df["regime"] + "__" + preset)),
|
||
index=df.index)
|
||
|
||
|
||
def reference_runs(p: dict) -> pd.DataFrame:
|
||
parts = [S.p2r_runs(p).assign(study="P2r")]
|
||
for v in SIGMA_A_STRESS: # P2r σ_a arm: methods registered with σ_a = v on data generated with 7 ms
|
||
f = REPO_ROOT / p["reference"]["p2r"]["root"] / "train" / f"R10_sa{v:g}" / "runs.csv"
|
||
parts.append(pd.read_csv(f).assign(regime="R10", preset=f"sa{v:g}", study="P2r-sa"))
|
||
for st in ("S1", "S2", "S3", "S4", "S8"):
|
||
parts.append(S.load_study(p, bench_root(), st)[1].assign(study=st))
|
||
df = pd.concat(parts, ignore_index=True)
|
||
df["preset"] = df["preset"].fillna("nominal")
|
||
df["setting"] = setting_of(df)
|
||
dup = df.duplicated(RUN)
|
||
if dup.any():
|
||
raise RuntimeError(f"{int(dup.sum())} duplicated reference runs, e.g. {df[dup][RUN].head(3).to_dict('records')}")
|
||
return df[["study", "regime", "preset", "delta_ms", *RUN, *S.METRICS]].sort_values(RUN).reset_index(drop=True)
|
||
|
||
|
||
def sigma_post(p: dict) -> pd.DataFrame:
|
||
a = pd.read_csv(REPO_ROOT / p["reference"]["p2r"]["root"] / "summary" / "sigma_post.csv")
|
||
a["setting"] = a["setting"].str.replace("_sa", "__sa", regex=False)
|
||
d = bench_root() / "posterior"
|
||
b = S.sigma_post_table({x.name: x for x in sorted(d.iterdir()) if x.is_dir()})
|
||
cols = ["setting", "c", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]
|
||
return pd.concat([a[cols], b[cols]], ignore_index=True)
|
||
|
||
|
||
def tables(a) -> None:
|
||
freeze(check=True)
|
||
p = load_protocol()
|
||
out = Path(a.out) / "reference"
|
||
out.mkdir(parents=True, exist_ok=True)
|
||
runs = reference_runs(p)
|
||
runs.to_csv(out / "runs.csv.gz", index=False, float_format="%.10g")
|
||
g = runs.groupby(["setting", "regime", "preset", "delta_ms", "c", "n_train", "method"], dropna=False)
|
||
cells = g.agg(n_rid=("rid", "nunique"), n_seed=("seed", "nunique"), band_rmse=("band_rmse", "mean"),
|
||
band_pcc=("band_pcc", "mean"), rmse=("rmse", "mean"), pcc=("pcc", "mean"), crps=("crps", "mean"),
|
||
coverage_90=("coverage_90", "mean")).reset_index()
|
||
sp = sigma_post(p)
|
||
if sp.duplicated(CELL).any():
|
||
raise RuntimeError("duplicated σ_post cells")
|
||
cells = cells.merge(sp, on=CELL, how="left")
|
||
cells["wide"] = np.where(cells.sigma_post_ms.notna(), cells.sigma_post_ms >= WIDE_MS, np.nan)
|
||
rdoc = DOC / "reference"
|
||
rdoc.mkdir(parents=True, exist_ok=True)
|
||
cells.to_csv(rdoc / "cells.csv", index=False, float_format="%.6g")
|
||
shutil.copy2(rdoc / "cells.csv", out / "cells.csv")
|
||
|
||
main = cells[(cells.preset == "nominal") & cells.delta_ms.isna() & (cells.c == 1) & cells.n_train.isin([4, 16])]
|
||
order = ["Oracle", "B3b", "B3c", "B3c-R", "B3d", "B4a", "B4b", "B4c", "B4d", "B3d-Sa", "M2-Sa", "Ctl-GP"]
|
||
t = main.pivot_table(index="method", columns=["setting", "n_train"], values="band_rmse").reindex(order).dropna(how="all")
|
||
regs = [r for r in p["grid"]["regimes"] if r in t.columns.get_level_values(0)]
|
||
head = "| method | " + " | ".join(f"{r} N={n}" for r in regs for n in (4, 16)) + " |"
|
||
L = ["# Reference band RMSE (p.u.), nominal settings, c = 1", "",
|
||
"Mean over 8 test realizations × 5 network seeds at the registered budgets (CNN–GRU). σ_post (ms) is the "
|
||
"SMC posterior width over the training wells; 'wide' means σ_post ≥ 1.5 ms. Full table: cells.csv.", "",
|
||
head, "|" + "---|" * (1 + 2 * len(regs))]
|
||
for m, r in t.iterrows():
|
||
L.append(f"| {m} | " + " | ".join(f"{r.get((g, n), np.nan):.3f}" for g in regs for n in (4, 16)) + " |")
|
||
s1 = main.drop_duplicates(CELL).set_index(["setting", "n_train"])["sigma_post_ms"]
|
||
L.append("| σ_post | " + " | ".join(f"{s1.get((g, n), np.nan):.2f}" for g in regs for n in (4, 16)) + " |")
|
||
(rdoc / "main_table.md").write_text("\n".join(L) + "\n")
|
||
shutil.copy2(rdoc / "main_table.md", out / "main_table.md")
|
||
print("\n".join(L))
|
||
print(f"{len(runs)} reference runs, {len(cells)} cell rows → {out}, {rdoc}")
|
||
|
||
|
||
# ---------------------------------------------------------------- scoring
|
||
|
||
def read_predictions(pred: Path, pkg: Path, name: str, f_c: float) -> pd.DataFrame:
|
||
run_d2 = load_script("11_run_d2.py")
|
||
rows = []
|
||
files = sorted(f for f in pred.glob("*/*/r*_c*_n*_s*.npz") if f.parent.parent.name in ("test", "dev"))
|
||
if not files:
|
||
raise SystemExit(f"no predictions under {pred}/<split>/<setting>/r<rid>_c<c>_n<N>_s<seed>.npz")
|
||
for f in files:
|
||
m = PRED.fullmatch(f.stem)
|
||
if m is None:
|
||
raise SystemExit(f"{f}: name must be r<rid>_c<c>_n<N>_s<seed>.npz")
|
||
rid, c, N, seed = int(m[1]), float(m[2]), int(m[3]), int(m[4])
|
||
split, setting = f.parent.parent.name, f.parent.name
|
||
tf = pkg / "truth" / split / setting / f"r{rid}_c{c:g}.npz"
|
||
if not tf.exists():
|
||
raise SystemExit(f"{f}: no task {tf.relative_to(pkg)}")
|
||
if not 1 <= N <= 16:
|
||
raise SystemExit(f"{f}: N = {N} outside 1..16")
|
||
with np.load(tf) as t:
|
||
yt, names = t["y_test"], t["test_names"]
|
||
with np.load(f) as z:
|
||
mu = z["mu"].astype(float)
|
||
sg = z["sigma"].astype(float) if "sigma" in z.files else None
|
||
if mu.shape != yt.shape or not np.isfinite(mu).all():
|
||
raise SystemExit(f"{f}: mu must be finite with shape {yt.shape}, got {mu.shape}")
|
||
if sg is not None and (sg.shape != yt.shape or not (np.isfinite(sg).all() and (sg > 0).all())):
|
||
raise SystemExit(f"{f}: sigma must be finite, positive, shape {yt.shape}")
|
||
with np.errstate(all="ignore"):
|
||
res = run_d2.evaluate(yt, mu, np.ones_like(mu) if sg is None else sg, f_c)
|
||
for w, r in zip(names, res):
|
||
if sg is None:
|
||
r = r | {k: np.nan for k in GAUSS}
|
||
rows.append({"split": split, "setting": setting, "c": c, "n_train": N, "rid": rid, "seed": seed,
|
||
"method": name, "test_well": str(w)} | r)
|
||
return pd.DataFrame(rows)
|
||
|
||
|
||
def rule_tables(run: pd.DataFrame, ref: pd.DataFrame, name: str) -> tuple[pd.DataFrame, ...]:
|
||
rules, anch, pairs, means = [], [], [], []
|
||
for (setting, c, N), sub in run.groupby(CELL):
|
||
r = ref[(ref.setting == setting) & (ref.c == c) & (ref.n_train == N) & ref.rid.isin(sub.rid) & ref.seed.isin(sub.seed)]
|
||
both = pd.concat([sub[RUN + S.METRICS], r[RUN + S.METRICS]], ignore_index=True)
|
||
key = {"setting": setting, "c": c, "n_train": N, "n_rid": sub.rid.nunique(), "n_seed": sub.seed.nunique()}
|
||
means.append(key | both.groupby("method").band_rmse.mean().add_prefix("band_rmse_").to_dict())
|
||
if set(S.POINT_TIES) <= set(r.method):
|
||
cells = S.h2a_cells(both, name, S.POINT_TIES, np.random.default_rng(0), N_BOOT)
|
||
rules.append(cells.drop(columns=["c", "n_train", "n_rid", "n_seed"]).assign(**key))
|
||
if set(ANCHOR_TIES) <= set(r.method): # v1.1: anchor mean among the competitors
|
||
cells = S.h2a_cells(both, name, ANCHOR_TIES, np.random.default_rng(0), N_BOOT)
|
||
anch.append(cells.drop(columns=["c", "n_train", "n_rid", "n_seed"]).assign(**key))
|
||
for m in ("B3d-Sa", "M2-Sa", "B3d", "PM2", "BK2", "Oracle"):
|
||
if m in set(r.method):
|
||
d = S.pair(both, name, m, np.random.default_rng(0), N_BOOT)
|
||
pairs.append(key | {"reference": m} | d)
|
||
first = lambda df, cols: df[[*cols, *[k for k in df.columns if k not in cols]]] if len(df) else df
|
||
k = ["setting", "c", "n_train", "n_rid", "n_seed"]
|
||
rules = pd.concat(rules, ignore_index=True) if rules else pd.DataFrame()
|
||
anch = pd.concat(anch, ignore_index=True) if anch else pd.DataFrame()
|
||
return first(rules, k), first(anch, k), first(pd.DataFrame(pairs), k + ["reference"]), first(pd.DataFrame(means), k)
|
||
|
||
|
||
def score(a) -> None:
|
||
pkg, pred = Path(a.out), Path(a.pred)
|
||
ref = pd.read_csv(pkg / "reference" / "runs.csv.gz")
|
||
if a.name in set(ref.method) or a.name == "M2":
|
||
raise SystemExit(f"--name {a.name} is a reference method name; choose another")
|
||
f_c = float(json.loads((pkg / "inputs" / "analyst.json").read_text())["metric"]["f_c_hz"])
|
||
well = read_predictions(pred, pkg, a.name, f_c)
|
||
run = well.groupby(["split", *RUN], as_index=False)[S.METRICS].mean()
|
||
out = pred / "score"
|
||
out.mkdir(exist_ok=True)
|
||
well.to_csv(out / "per_well.csv", index=False)
|
||
run.to_csv(out / "runs.csv", index=False)
|
||
test = run[run.split == "test"].drop(columns="split")
|
||
L = [f"# Score of `{a.name}` (scripts/37_bench_package.py score, scorer v{SCORER_VERSION})", "",
|
||
f"{len(well.groupby(['split', *RUN]))} predictions; test split: {len(test)} runs in {test.groupby(CELL).ngroups} cells.",
|
||
"Rules: protocol_bench (improves: band RMSE ≤ 0.90 × best point tie or band PCC ≥ +0.05; cell_pass: ≥ 4/5 seeds "
|
||
"and > 1/2 of realizations; better: lower band RMSE in ≥ 4/5 seeds and > 1/2 of realizations).", ""]
|
||
if len(test):
|
||
rules, anch, pairs, means = rule_tables(test, ref, a.name)
|
||
for f, df in (("rule_point_ties.csv", rules), ("rule_point_ties_anchor.csv", anch), ("pairs.csv", pairs),
|
||
("cells.csv", means)):
|
||
df.to_csv(out / f, index=False)
|
||
complete = lambda df: df[(df.n_rid == 8) & (df.n_seed == 5)] if len(df) else df
|
||
if len(rules):
|
||
rc = complete(rules)
|
||
L += [f"- H2a cell rule vs best point tie: {int(rules.cell_pass.sum())}/{len(rules)} cells pass "
|
||
f"({int(rc.cell_pass.sum())}/{len(rc)} among complete cells: 8 realizations × 5 seeds)."]
|
||
if len(anch):
|
||
ac = complete(anch)
|
||
L += [f"- v1.1 H2a cell rule vs best of point ties and anchor mean B3d: {int(anch.cell_pass.sum())}/{len(anch)} "
|
||
f"cells pass ({int(ac.cell_pass.sum())}/{len(ac)} among complete cells; nominal settings only)."]
|
||
for m in ("B3d-Sa", "M2-Sa", "B3d", "PM2", "BK2", "Oracle"):
|
||
q = pairs[pairs.reference == m] if len(pairs) else pairs
|
||
if len(q):
|
||
L += [f"- better than {m}: {int(q.better.sum())}/{len(q)} cells; median ratio {q.ratio.median():.3f}."]
|
||
L += ["", "| setting | c | N | n_rid × n_seed | ratio vs best point tie (best) | cell_pass | "
|
||
"ratio vs best of point ties and B3d (best) | cell_pass (v1.1) | ratio vs B3d-Sa |",
|
||
"|---|---|---|---|---|---|---|---|---|"]
|
||
rr = rules.set_index(CELL) if len(rules) else None
|
||
ra = anch.set_index(CELL) if len(anch) else None
|
||
pb = pairs[pairs.reference == "B3d-Sa"].set_index(CELL) if len(pairs) else None
|
||
for row in means.itertuples():
|
||
k = (row.setting, row.c, row.n_train)
|
||
h = f"{rr.loc[k, 'ratio']:.3f} ({rr.loc[k, 'best']})" if rr is not None and k in rr.index else "—"
|
||
cp = str(bool(rr.loc[k, "cell_pass"])) if rr is not None and k in rr.index else "—"
|
||
ha = f"{ra.loc[k, 'ratio']:.3f} ({ra.loc[k, 'best']})" if ra is not None and k in ra.index else "—"
|
||
ca = str(bool(ra.loc[k, "cell_pass"])) if ra is not None and k in ra.index else "—"
|
||
b = f"{pb.loc[k, 'ratio']:.3f}" if pb is not None and k in pb.index else "—"
|
||
L.append(f"| {row.setting} | {row.c:g} | {row.n_train} | {row.n_rid} × {row.n_seed} | {h} | {cp} | {ha} | {ca} | {b} |")
|
||
dev = run[run.split == "dev"]
|
||
if len(dev):
|
||
L += ["", f"Dev split: {len(dev)} runs, metrics only (runs.csv); dev labels may be used for design."]
|
||
(out / "score.md").write_text("\n".join(L) + "\n")
|
||
print("\n".join(L[:12]))
|
||
print(f"→ {out}")
|
||
|
||
|
||
# ---------------------------------------------------------------- self-test
|
||
|
||
SELFTEST = [ # (setting, train dir relative to outputs/, tag suffix, c, method)
|
||
("R10", "bench/s1/train/R10/cells", "", 1.5, "B3d-Sa"),
|
||
("R10__wv_L1", "bench/s2/train/R10__wv_L1/cells", "", 1.0, "B3d-Sa"),
|
||
("R10", "p2r/train/R10/cells", "", 1.0, "B3d-Sa"),
|
||
("R10__s8d16", "bench/s8/train/R10/cells", "_d16", 1.0, "BK2"),
|
||
]
|
||
|
||
|
||
def selftest(a) -> None:
|
||
p = load_protocol()
|
||
pkg = Path(a.out)
|
||
sub = pkg / "selftest_submission"
|
||
shutil.rmtree(sub, ignore_errors=True)
|
||
bud, name = p["training"]["budgets"], "SelfTest"
|
||
worst_y = 0.0
|
||
for setting, d, suf, c, m in SELFTEST:
|
||
for N in (4, 16):
|
||
for rid in p["grid"]["realizations"]:
|
||
with np.load(outputs_dir() / d / f"r{rid}_c{c:g}_n{N}{suf}.npz") as z, \
|
||
np.load(pkg / "truth" / "test" / setting / f"r{rid}_c{c:g}.npz") as t:
|
||
worst_y = max(worst_y, float(np.abs(z["y_true"] - t["y_test"]).max()))
|
||
if not (z["test_wells"] == t["test_names"]).all():
|
||
raise SystemExit(f"{setting} r{rid}: test well order differs")
|
||
for seed in p["grid"]["seeds"]:
|
||
f = sub / "test" / setting / f"r{rid}_c{c:g}_n{N}_s{seed}.npz"
|
||
f.parent.mkdir(parents=True, exist_ok=True)
|
||
k = f"{m}/s{seed}/b{bud[m]}"
|
||
np.savez(f, mu=z[f"{k}/mu"], sigma=z[f"{k}/sigma"])
|
||
score(argparse.Namespace(out=str(pkg), pred=str(sub), name=name))
|
||
ref = pd.read_csv(pkg / "reference" / "runs.csv.gz")
|
||
got = pd.read_csv(sub / "score" / "runs.csv")
|
||
rules = pd.read_csv(sub / "score" / "rule_point_ties.csv")
|
||
anch = pd.read_csv(sub / "score" / "rule_point_ties_anchor.csv")
|
||
pairs = pd.read_csv(sub / "score" / "pairs.csv")
|
||
msg, ok = [f"max |y_true(runner, float32) − y_test(package)| = {worst_y:.2e} p.u."], worst_y < 1e-4
|
||
for setting, _, _, c, m in SELFTEST:
|
||
g = got[(got.setting == setting) & (got.c == c)].set_index(["n_train", "rid", "seed"])
|
||
r = ref[(ref.setting == setting) & (ref.c == c) & (ref.method == m)].set_index(["n_train", "rid", "seed"]).reindex(g.index)
|
||
dm = float(np.abs(g.band_rmse - r.band_rmse).max())
|
||
ok &= dm < 1e-4 and len(g) == 2 * 8 * 5
|
||
line = f"{setting} c={c:g} copy of {m}: {len(g)} runs, max |Δ band RMSE| = {dm:.1e}"
|
||
cell = ref[(ref.setting == setting) & (ref.c == c)]
|
||
for N in (4, 16):
|
||
cr = cell[cell.n_train == N]
|
||
if set(S.POINT_TIES) <= set(cr.method):
|
||
want = S.h2a_cells(cr, m, S.POINT_TIES, np.random.default_rng(0), N_BOOT).iloc[0]
|
||
have = rules[(rules.setting == setting) & (rules.c == c) & (rules.n_train == N)].iloc[0]
|
||
same = want.best == have.best and bool(want.cell_pass) == bool(have.cell_pass) and abs(want.ratio - have.ratio) < 1e-4
|
||
line += f"; N={N} ratio {have.ratio:.4f} vs {want.ratio:.4f} ({want.best}, pass {bool(want.cell_pass)})"
|
||
if set(ANCHOR_TIES) <= set(cr.method): # v1.1 anchor-mean rule
|
||
wa = S.h2a_cells(cr, m, ANCHOR_TIES, np.random.default_rng(0), N_BOOT).iloc[0]
|
||
ha = anch[(anch.setting == setting) & (anch.c == c) & (anch.n_train == N)].iloc[0]
|
||
same &= wa.best == ha.best and bool(wa.cell_pass) == bool(ha.cell_pass) and abs(wa.ratio - ha.ratio) < 1e-4
|
||
line += f" | v1.1 {ha.ratio:.4f} vs {wa.ratio:.4f} ({wa.best}, pass {bool(wa.cell_pass)})"
|
||
else:
|
||
want = S.pair(cr, m, "PM2", np.random.default_rng(0), N_BOOT)
|
||
have = pairs[(pairs.setting == setting) & (pairs.c == c) & (pairs.n_train == N) & (pairs.reference == "PM2")].iloc[0]
|
||
same = bool(want["better"]) == bool(have.better) and abs(want["ratio"] - have.ratio) < 1e-4
|
||
line += f"; N={N} ratio vs PM2 {have.ratio:.4f} vs {want['ratio']:.4f}"
|
||
ok &= same
|
||
msg.append(line)
|
||
print("\n".join(msg))
|
||
(pkg / "selftest.json").write_text(json.dumps({"pass": bool(ok), "scorer_version": SCORER_VERSION, "checks": msg}, indent=1))
|
||
shutil.rmtree(sub)
|
||
if not ok:
|
||
raise SystemExit("selftest FAILED")
|
||
print("selftest PASS")
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||
sp = ap.add_subparsers(dest="cmd", required=True)
|
||
g = sp.add_parser("generate")
|
||
g.add_argument("--split", nargs="+", default=["test", "dev"], choices=["test", "dev"])
|
||
g.add_argument("--update-manifest", action="store_true")
|
||
g.add_argument("--skip-lock-check", action="store_true")
|
||
s = sp.add_parser("score")
|
||
s.add_argument("--pred", required=True)
|
||
s.add_argument("--name", required=True)
|
||
for name in ("tables", "selftest", "check"):
|
||
sp.add_parser(name)
|
||
for x in sp.choices.values():
|
||
x.add_argument("--out", default=str(PKG))
|
||
a = ap.parse_args()
|
||
{"generate": generate, "tables": tables, "score": score, "selftest": selftest, "check": check}[a.cmd](a)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|