Summarize P6 benchmark, package it, write results, review proofs
- Benchmark summary: scripts/36_bench_verdicts.py applies the locked protocol_bench statements as worded (9/11 pass; S2-H1 fails for rock physics and wavelet phase), outside the lock hash. - S7 packaging: scripts/37_bench_package.py, benchmark/ (manifest, reference tables, README, draft Zenodo metadata). Deposit not done. - Paper: Experiment 3 (Sec. 6.5), T2 mechanism (Sec. 6.4), benchmark figures (scripts/38_bench_figures.py), dataset citations. - Proof review of Sec. 4 and App. A (14 of 15 findings fixed, 1 partly; no verdict or reported number changed); docs/theory.md synced. - Reproduction package: scripts/39_repro_package.py and repro/ (manifest, README, clean-room verify report: 12/12 stages pass). - Related work: preliminary novelty scan; full texts of AWSM, BootNet, Li et al. 2024, Guillon et al. 2020, Rizzuti et al. 2024/2025 and Castagna et al. 2026 checked; abstract-only markers updated and the Castagna sentence corrected. Paper compiles cleanly (68 pages). - Docs synced (AGENTS.md, plan.md, report.html, READMEs). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
149
scripts/36_bench_verdicts.py
Normal file
149
scripts/36_bench_verdicts.py
Normal file
@@ -0,0 +1,149 @@
|
||||
"""Final verdicts of protocol_bench (phase P6): the 11 pre-declared verdicts read exactly as their statements are worded.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/36_bench_verdicts.py
|
||||
|
||||
Runs after `scripts/34_run_bench.py summarize` and never edits its outputs. The locked summary code
|
||||
(ml_porosity/benchmark/summary.py) computes every cell correctly, but three verdict extractions differ from the
|
||||
statements of configs/protocol_bench.yaml (found after the main runs, before any paper text used them):
|
||||
|
||||
S1-H1 the statement names N ∈ {4, 16}; the code requires exactly two R10 c = 1.5 rows, but S1 has four N values
|
||||
(2, 4, 8, 16), so it returns pass = null. Here: the two rows N ∈ {4, 16} of s1_h2a.csv.
|
||||
S2-H1 the code stores one verdict per axis (per_axis) and no top-level `pass`, so summary.md prints
|
||||
"not available". Here: per axis from s2_h2a.csv (R10, preset *_L1, c = 1, N ∈ {4, 16}).
|
||||
S3-H1 the statement fixes the competitors {B3b, B3c, B3c-R, B4a, B4b, B4c, B4d}; the code uses POINT_TIES + every
|
||||
S3 method, which adds the disclosed control bank Ctl-GP (T2-1). Ctl-GP uses the posterior mean and
|
||||
covariance, so it is not a point tie or an anchor-free baseline. Here: h2a_cells of the locked code with the
|
||||
stated set (bootstrap rng 0, 2000 resamples, one generator per regime in the summary's regime order).
|
||||
|
||||
The other eight verdicts are copied from verdict.json. Both readings are written side by side; the as-run S3-H1
|
||||
result (with Ctl-GP) stays reported. The lock is checked first (code, protocol, inputs).
|
||||
→ outputs/bench/summary/verdict_final.json, verdict_final.md, s3_h2a_stated.csv
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
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.protocol import freeze, load_protocol
|
||||
|
||||
S3_COMP = S.POINT_TIES + ["B4a", "B4b", "B4c", "B4d"]
|
||||
H2A_REGIMES = ["R10", "R0", "Rm5"]
|
||||
ORDER = ["S1-H1", "S1-H2", "S2-H1/rock_physics", "S2-H1/wavelet", "S2-H1/drift", "S2-H2", "S3-H1", "S4-H1", "S4-H2",
|
||||
"S8-H1", "S8-H2"]
|
||||
PRED_S2 = {"rock_physics": "pass", "wavelet": "pass (phase sub-axis wv_L1)", "drift": "uncertain"} # S2-H1.prediction
|
||||
|
||||
|
||||
def _cell(r) -> dict:
|
||||
return {"best": r.best, "ratio": float(r.ratio), "ci": [float(r.ratio_lo), float(r.ratio_hi)], "dpcc": float(r.dpcc),
|
||||
"seeds_improve": int(r.seeds_improve), "rids_improve": int(r.rids_improve), "cell_pass": bool(r.cell_pass)}
|
||||
|
||||
|
||||
def s1_h1(out, n_rid: int) -> dict:
|
||||
t = pd.read_csv(out / "s1_h2a.csv")
|
||||
t = t[(t.regime == "R10") & (t.c == 1.5) & t.n_train.isin([4, 16])]
|
||||
ok = len(t) == 2 and bool((t.n_rid == n_rid).all())
|
||||
return {"cells": {int(r.n_train): _cell(r) for r in t.itertuples()}, "complete": ok,
|
||||
"pass": bool(t.cell_pass.all()) if ok else None}
|
||||
|
||||
|
||||
def s2_h1(out, n_rid: int) -> dict:
|
||||
t = pd.read_csv(out / "s2_h2a.csv")
|
||||
t = t[(t.regime == "R10") & t.preset.str.endswith("_L1") & (t.c == 1) & t.n_train.isin([4, 16])]
|
||||
res = {}
|
||||
for axis, g in t.groupby("axis"):
|
||||
ok = len(g) == 2 and bool((g.n_rid == n_rid).all())
|
||||
res[axis] = {"preset": g.preset.iloc[0], "cells": {int(r.n_train): _cell(r) for r in g.itertuples()},
|
||||
"complete": ok, "pass": bool(g.cell_pass.all()) if ok else None}
|
||||
return res
|
||||
|
||||
|
||||
def s3_h1(p: dict, n_boot: int) -> tuple[dict, pd.DataFrame]:
|
||||
_, run_b4, _ = S.load_study(p, bench_root(dev=False), "S3")
|
||||
run = pd.concat([S.p2r_runs(p), run_b4], ignore_index=True)
|
||||
assert set(S3_COMP) <= set(run.method), sorted(run.method.unique())
|
||||
rows, per = [], {}
|
||||
for reg, g in run.groupby("regime"):
|
||||
cells = S.h2a_cells(g, "B3d-Sa", S3_COMP, np.random.default_rng(0), n_boot)
|
||||
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 = float(c0.m2_band_rmse.mean() / c0.best_band_rmse.mean())
|
||||
guard = bool(len(c0) == 2 and macro <= S.sp13.GUARD and (c0.ratio <= S.sp13.GUARD).all())
|
||||
per[reg] = {"c1_cells": {int(r.n_train): _cell(r) for r in c1.itertuples()},
|
||||
"zero_drift_ratios": {int(r.n_train): float(r.ratio) for r in c0.itertuples()},
|
||||
"zero_drift_macro_ratio": macro, "zero_drift_guard": guard,
|
||||
"regime_pass": bool(len(c1) == 2 and c1.cell_pass.all() and guard),
|
||||
"b4_best_anywhere": sorted({f"c{r.c:g}/N{r.n_train}:{r.best}" for r in cells.itertuples() if r.best.startswith("B4")}),
|
||||
"complete": bool(len(cells) == 6 and (cells.n_rid == len(p["grid"]["realizations"])).all())}
|
||||
v = {"competitors": S3_COMP, "per_regime": per, "pass": per.get("R10", {}).get("regime_pass"),
|
||||
"regimes_pass": [r for r in H2A_REGIMES if per.get(r, {}).get("regime_pass")]}
|
||||
return v, pd.concat(rows, ignore_index=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
freeze(check=True)
|
||||
p = load_protocol()
|
||||
out = bench_root(dev=False) / "summary"
|
||||
raw = json.loads((out / "verdict.json").read_text())
|
||||
n_rid, n_boot = len(p["grid"]["realizations"]), 2000
|
||||
|
||||
s3, s3_tab = s3_h1(p, n_boot)
|
||||
s3_tab.to_csv(out / "s3_h2a_stated.csv", index=False)
|
||||
s2 = s2_h1(out, n_rid)
|
||||
as_run = {"S1-H1": raw["S1"]["S1-H1"].get("pass"), "S1-H2": raw["S1"]["S1-H2"]["pass"],
|
||||
**{f"S2-H1/{a}": raw["S2"]["S2-H1"]["per_axis"][a]["pass"] for a in ("rock_physics", "wavelet", "drift")},
|
||||
"S2-H2": raw["S2"]["S2-H2"]["pass"], "S3-H1": raw["S3"]["pass"], "S4-H1": raw["S4"]["S4-H1"]["pass"],
|
||||
"S4-H2": raw["S4"]["S4-H2"]["pass"], "S8-H1": raw["S8"]["S8-H1"]["pass"], "S8-H2": raw["S8"]["S8-H2"]["pass"]}
|
||||
detail = {"S1-H1": s1_h1(out, n_rid), "S1-H2": raw["S1"]["S1-H2"],
|
||||
**{f"S2-H1/{a}": s2[a] for a in ("rock_physics", "wavelet", "drift")},
|
||||
"S2-H2": raw["S2"]["S2-H2"], "S3-H1": s3, "S4-H1": raw["S4"]["S4-H1"], "S4-H2": raw["S4"]["S4-H2"],
|
||||
"S8-H1": raw["S8"]["S8-H1"], "S8-H2": raw["S8"]["S8-H2"]}
|
||||
final = {k: detail[k]["pass"] for k in ORDER}
|
||||
for a in ("rock_physics", "wavelet", "drift"): # the per-axis extraction of the code is correct
|
||||
assert final[f"S2-H1/{a}"] == as_run[f"S2-H1/{a}"], a
|
||||
note = {"S1-H1": "code filter: exactly 2 rows at R10 c = 1.5 (S1 has N = 2, 4, 8, 16) → null; statement: N ∈ {4, 16}",
|
||||
"S3-H1": "code competitors include Ctl-GP (POINT_TIES + S3 methods); statement: {B3b, B3c, B3c-R, B4a–d}"}
|
||||
verdict = {"protocol_sha256": raw["protocol_sha256"], "source": "outputs/bench/summary/verdict.json (scripts/34 summarize)",
|
||||
"final": final, "as_run": as_run, "differences": note, "detail": detail,
|
||||
"passed": [k for k in ORDER if final[k]], "failed": [k for k in ORDER if final[k] is False],
|
||||
"S2_axes_pass": [a for a in ("rock_physics", "wavelet", "drift") if final[f"S2-H1/{a}"]]}
|
||||
(out / "verdict_final.json").write_text(json.dumps(verdict, indent=1, default=float))
|
||||
|
||||
hyp = p["hypotheses"]
|
||||
fmt = lambda x: "PASS" if x else "FAIL" if x is False else "null"
|
||||
L = ["# protocol_bench final verdicts (scripts/36_bench_verdicts.py)", "",
|
||||
f"Protocol sha256 {raw['protocol_sha256'][:12]}…; lock checked. Statements of configs/protocol_bench.yaml applied as "
|
||||
"written; `as run` is verdict.json of scripts/34 summarize (locked code). No family-wise correction (11 verdicts).", "",
|
||||
"| verdict | final | as run | prediction | note |", "|---|---|---|---|---|"]
|
||||
for k in ORDER:
|
||||
pred = PRED_S2[k.split("/")[1]] if k.startswith("S2-H1") else str(hyp[k]["prediction"]).split(";")[0].strip()
|
||||
L.append(f"| {k} | **{fmt(final[k])}** | {fmt(as_run[k])} | {pred} | {note.get(k, '')} |")
|
||||
L += ["", "## S1-H1 (R10, c = 1.5)", ""]
|
||||
L += [f"- N = {n}: best {c['best']}, ratio {c['ratio']:.3f} [{c['ci'][0]:.3f}, {c['ci'][1]:.3f}], ΔPCC {c['dpcc']:+.3f}, "
|
||||
f"seeds {c['seeds_improve']}/5, rids {c['rids_improve']}/{n_rid}, cell_pass {c['cell_pass']}" for n, c in detail["S1-H1"]["cells"].items()]
|
||||
L += ["", "## S2-H1 per axis (R10, L1, c = 1)", ""]
|
||||
for a in ("rock_physics", "wavelet", "drift"):
|
||||
d = detail[f"S2-H1/{a}"]
|
||||
L += [f"- {a} ({d['preset']}), N = {n}: best {c['best']}, ratio {c['ratio']:.3f} [{c['ci'][0]:.3f}, {c['ci'][1]:.3f}], "
|
||||
f"ΔPCC {c['dpcc']:+.3f}, seeds {c['seeds_improve']}/5, rids {c['rids_improve']}/{n_rid} → {fmt(c['cell_pass'])}"
|
||||
for n, c in d["cells"].items()]
|
||||
L += ["", "## S3-H1 with the stated competitors", "", "| regime | c = 1, N = 4 | c = 1, N = 16 | c = 0 guard (macro) | regime | B4 best in |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for reg, d in s3["per_regime"].items():
|
||||
cc = [f"{d['c1_cells'][n]['ratio']:.3f} ({d['c1_cells'][n]['best']}) {fmt(d['c1_cells'][n]['cell_pass'])}" for n in (4, 16)]
|
||||
L.append(f"| {reg} | {cc[0]} | {cc[1]} | {fmt(d['zero_drift_guard'])} ({d['zero_drift_macro_ratio']:.3f}) | "
|
||||
f"{fmt(d['regime_pass'])} | {', '.join(d['b4_best_anywhere']) or '—'} |")
|
||||
r = raw["S3"]["per_regime"]
|
||||
L += ["", f"As run (with Ctl-GP): best at c = 1 is Ctl-GP in {sum(v['best_at_c1'] == {'4': 'Ctl-GP', '16': 'Ctl-GP'} for v in r.values())}/{len(r)} "
|
||||
f"regimes; R10 zero-drift macro ratio {r['R10']['zero_drift_macro_ratio']:.4f} → regime fail. Kept as a disclosed reading "
|
||||
"(see T2-1 in verdict.json).", ""]
|
||||
(out / "verdict_final.md").write_text("\n".join(L))
|
||||
print("\n".join(L))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
490
scripts/37_bench_package.py
Normal file
490
scripts/37_bench_package.py
Normal file
@@ -0,0 +1,490 @@
|
||||
"""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). 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.
|
||||
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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 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"]]
|
||||
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(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²)"},
|
||||
"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["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))},
|
||||
"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 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")
|
||||
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, pd.DataFrame, pd.DataFrame]:
|
||||
rules, 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))
|
||||
for m in ("B3d-Sa", "M2-Sa", "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()
|
||||
return first(rules, 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)", "",
|
||||
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, pairs, means = rule_tables(test, ref, a.name)
|
||||
for f, df in (("rule_point_ties.csv", rules), ("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)."]
|
||||
for m in ("B3d-Sa", "M2-Sa", "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 B3d-Sa |",
|
||||
"|---|---|---|---|---|---|---|"]
|
||||
rr = rules.set_index(CELL) if len(rules) 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 "—"
|
||||
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} | {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")
|
||||
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)})"
|
||||
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), "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()
|
||||
169
scripts/38_bench_figures.py
Normal file
169
scripts/38_bench_figures.py
Normal file
@@ -0,0 +1,169 @@
|
||||
"""Manuscript figures of Experiment 3 (protocol_bench, phase P6), drawn from the locked summary outputs only.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/38_bench_figures.py [--only bench_s1,bench_s8] [--flipband]
|
||||
|
||||
Outside the protocol_bench code hash (like scripts/36 and 37); checks the lock first and never writes under outputs/.
|
||||
Reads outputs/bench/summary/s1_cells.csv (S1 phase diagram) and outputs/bench/summary/s8_transfer_curves.json; the
|
||||
S8 usable band (Oracle cross-spectrum ≥ 0.1 × its maximum above 6 Hz) is recomputed from the S8 prediction files
|
||||
exactly as ml_porosity/benchmark/summary.py does, because the curves file does not store it.
|
||||
Style, palette and output folder are those of scripts/22_paper_figures.py (→ paper/figures/{bench_s1,bench_s8}.pdf).
|
||||
--flipband prints (stdout only) the Section 6.5 S8 comparison: mean cos(πfΔ), mean cos²(πfΔ) (Corollary 3, the λ → 0
|
||||
transfer of the equal-weight two-member bank, which contains the true warp but is not calibrated) and the measured
|
||||
PM2/BK2/HM2 transfer over the usable frequencies of the band 1/(2Δ) < f < 3/(2Δ), for every S8 cell.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from matplotlib.lines import Line2D
|
||||
from matplotlib.patches import Rectangle
|
||||
|
||||
from ml_porosity.benchmark import summary as S
|
||||
from ml_porosity.benchmark.cells import Cell, bench_root, train_paths
|
||||
from ml_porosity.benchmark.protocol import freeze, load_protocol
|
||||
from ml_porosity.eval import figstyle as fs
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("s22", REPO_ROOT / "scripts" / "22_paper_figures.py")
|
||||
F = importlib.util.module_from_spec(_spec) # style(), save(), text_on(), WIDTH of the other manuscript figures
|
||||
_spec.loader.exec_module(F)
|
||||
plt = F.plt
|
||||
SUMMARY = bench_root(dev=False) / "summary"
|
||||
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Fig. S1 phase diagram (Section 6.5)
|
||||
def bench_s1() -> None:
|
||||
d = pd.read_csv(SUMMARY / "s1_cells.csv")
|
||||
cs, Ns = sorted(d.c.unique()), sorted(d.n_train.unique())
|
||||
norm, cmap = fs.diverging_norm(0.65, 1.0, 1.15), fs.DIVERGING
|
||||
rows = [("pm_best", r"B3d-Sa / best point tie"), ("m2_pm", r"M2-Sa / B3d-Sa")]
|
||||
fig, axes = plt.subplots(2, len(REGIMES), figsize=(F.WIDTH, 3.55), sharex=True, sharey=True, layout="constrained")
|
||||
for i, (k, lab) in enumerate(rows):
|
||||
for j, reg in enumerate(REGIMES):
|
||||
ax = axes[i, j]
|
||||
t = d[d.regime == reg].set_index(["c", "n_train"])
|
||||
Z = t[f"{k}_ratio"].unstack("n_train").reindex(index=cs, columns=Ns).to_numpy()
|
||||
im = ax.imshow(Z, cmap=cmap, norm=norm, origin="lower", aspect="auto")
|
||||
for a, c in enumerate(cs):
|
||||
for b, N in enumerate(Ns):
|
||||
r = t.loc[(c, N)]
|
||||
txt = f"{r[k + '_ratio']:.2f}"
|
||||
ax.text(b, a, txt if r[k + "_better"] else f"({txt})", ha="center", va="center", fontsize=6,
|
||||
color=F.text_on(cmap(norm(r[k + "_ratio"]))))
|
||||
if k == "m2_pm" and r.sigma_post_ms >= 1.5:
|
||||
ax.add_patch(Rectangle((b - 0.42, a - 0.42), 0.84, 0.84, fill=False, ec=fs.INK, lw=0.6))
|
||||
ax.set_xticks(range(len(Ns)), [str(n) for n in Ns])
|
||||
ax.set_yticks(range(len(cs)), [f"{c:g}" for c in cs])
|
||||
ax.grid(False)
|
||||
for s in ax.spines.values():
|
||||
s.set_visible(False)
|
||||
ax.tick_params(length=0)
|
||||
ax.set_title(f"({'ab'[i]}{j + 1}) {reg}", loc="left", fontsize=8, color=fs.INK, pad=3)
|
||||
if i == 1:
|
||||
ax.set_xlabel(r"wells $N$")
|
||||
if j == 0:
|
||||
ax.set_ylabel(r"drift factor $c$")
|
||||
cb = fig.colorbar(im, ax=axes[i, :], shrink=0.95, pad=0.01, extend="both")
|
||||
cb.ax.axhline(1.0, color=fs.INK, lw=0.9)
|
||||
cb.set_label(lab, color=fs.INK2, fontsize=7)
|
||||
cb.outline.set_visible(False)
|
||||
F.save(fig, "bench_s1")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Fig. S8 two-mode transfer functions (Section 6.5)
|
||||
def oracle_spectrum(p: dict, reg: str, d: float, N: int) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Usable-frequency mask of an S8 cell, as in summary.s8 (Oracle cross-spectrum pooled over rids/seeds/wells)."""
|
||||
f = np.fft.rfftfreq(S.NFFT, 4.0 / 1000.0)
|
||||
b = S.study_budgets(p, "S8")["Oracle"]
|
||||
so = np.zeros(len(f))
|
||||
for rid in p["grid"]["realizations"]:
|
||||
cell = Cell("S8", reg, None, 1.0, int(N), int(rid), tuple(p["studies"]["S8"]["methods"]), posterior="none",
|
||||
delta_ms=float(d))
|
||||
with np.load(train_paths(cell, bench_root(dev=False))["npz"]) as z:
|
||||
Y = z["y_true"].astype(float)
|
||||
for k in (k for k in z.files if k.startswith("Oracle/s") and k.endswith(f"/b{b}/mu")):
|
||||
so += S.cross_spectrum(Y, z[k].astype(float))
|
||||
band = f >= 6.0
|
||||
return f, band & (so >= 0.1 * so[band].max())
|
||||
|
||||
|
||||
STYLE_S8 = {"PM2": dict(lw=1.3, marker="o", ms=1.6), "BK2": dict(lw=1.8, marker="o", ms=2.0),
|
||||
"HM2": dict(lw=0.9, ls=(0, (3, 1.5)))} # BK2 and HM2 nearly coincide: HM2 dashed on top
|
||||
|
||||
|
||||
def bench_s8(N: int = 16) -> None:
|
||||
p = load_protocol()
|
||||
curves = [c for c in json.loads((SUMMARY / "s8_transfer_curves.json").read_text()) if c["n_train"] == N]
|
||||
deltas = sorted({c["delta_ms"] for c in curves})
|
||||
cols = {"PM2": fs.ORANGE, "BK2": fs.BLUE, "HM2": fs.AQUA}
|
||||
fig, axes = plt.subplots(2, len(deltas), figsize=(F.WIDTH, 3.5), sharey=True, layout="constrained")
|
||||
for i, reg in enumerate(["R10", "Rm5"]):
|
||||
for j, d in enumerate(deltas):
|
||||
ax = axes[i, j]
|
||||
f, use = oracle_spectrum(p, reg, d, N)
|
||||
fmax = f[use].max()
|
||||
lo, hi = 1000.0 / (2 * d), 3000.0 / (2 * d)
|
||||
ax.axvspan(lo, min(hi, fmax + 5), color=fs.GRID, alpha=0.7, lw=0)
|
||||
ax.axhline(0.0, color=fs.AXIS, lw=0.8)
|
||||
ax.plot(f, np.cos(np.pi * f * d / 1000.0), color=fs.INK2, lw=0.9, ls="--")
|
||||
for m, col in cols.items():
|
||||
c = next(c for c in curves if c["regime"] == reg and c["delta_ms"] == d and c["method"] == m)
|
||||
H = np.where(use, np.asarray(c["H"], float), np.nan)
|
||||
ax.plot(f, H, color=col, **STYLE_S8[m])
|
||||
ax.set(xlim=(0, fmax + 5), ylim=(-1.4, 1.6))
|
||||
ax.set_title(f"({'ab'[i]}{j + 1}) {reg}, " + rf"$\Delta = {d:g}$ ms", loc="left", fontsize=8, color=fs.INK, pad=3)
|
||||
if i == 1:
|
||||
ax.set_xlabel("frequency (Hz)")
|
||||
if j == 0:
|
||||
ax.set_ylabel(r"transfer $\hat H(f)$ vs. Oracle")
|
||||
handles = [Line2D([], [], color=col, label=m, **STYLE_S8[m]) for m, col in cols.items()]
|
||||
handles.append(Line2D([], [], color=fs.INK2, lw=0.9, ls="--", label=r"$\cos(\pi f \Delta)$"))
|
||||
fig.legend(handles=handles, loc="outside lower center", ncol=4)
|
||||
F.save(fig, "bench_s8")
|
||||
|
||||
|
||||
def flipband() -> None:
|
||||
p = load_protocol()
|
||||
curves = json.loads((SUMMARY / "s8_transfer_curves.json").read_text())
|
||||
print("regime delta_ms N n_freq mean_cos mean_cos2 PM2 BK2 HM2")
|
||||
for reg in ["R10", "Rm5"]:
|
||||
for d in sorted({c["delta_ms"] for c in curves}):
|
||||
for N in sorted({c["n_train"] for c in curves}):
|
||||
f, use = oracle_spectrum(p, reg, d, N)
|
||||
fl = use & (f > 1000.0 / (2 * d)) & (f < 3000.0 / (2 * d))
|
||||
if not fl.any():
|
||||
print(f"{reg:6s} {d:8g} {N:2d} {0:6d} (no usable frequency in the band)")
|
||||
continue
|
||||
c = np.cos(np.pi * f[fl] * d / 1000.0)
|
||||
H = {m: np.asarray(next(x for x in curves if x["regime"] == reg and x["delta_ms"] == d
|
||||
and x["n_train"] == N and x["method"] == m)["H"], float)[fl].mean()
|
||||
for m in ("PM2", "BK2", "HM2")}
|
||||
print(f"{reg:6s} {d:8g} {N:2d} {int(fl.sum()):6d} {c.mean():8.3f} {(c ** 2).mean():9.3f} "
|
||||
+ " ".join(f"{H[m]:5.3f}" for m in ("PM2", "BK2", "HM2")))
|
||||
|
||||
|
||||
FIGURES = {"bench_s1": bench_s1, "bench_s8": bench_s8}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--only", default="", help="comma-separated subset of " + ",".join(FIGURES))
|
||||
ap.add_argument("--flipband", action="store_true", help="print the S8 flip-band table instead of drawing")
|
||||
args = ap.parse_args()
|
||||
freeze(check=True)
|
||||
if args.flipband:
|
||||
flipband()
|
||||
return
|
||||
F.style()
|
||||
for k in (args.only.split(",") if args.only else FIGURES):
|
||||
FIGURES[k]()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
627
scripts/39_repro_package.py
Normal file
627
scripts/39_repro_package.py
Normal file
@@ -0,0 +1,627 @@
|
||||
"""Reproduction package of the manuscript (phase P5): derived-data archives, a manifest and a clean-room check.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/39_repro_package.py build [--out DIR] [--dry-run]
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/39_repro_package.py check --root DIR
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/39_repro_package.py verify [--out DIR] [--work DIR] [--only STEP …] [--keep]
|
||||
.venv/bin/python scripts/39_repro_package.py code --rev REV [--out DIR]
|
||||
|
||||
DIR defaults to outputs/repro (gitignored). Documentation for readers: repro/README.md.
|
||||
|
||||
build Selects files of outputs/ by the first matching rule of RULES (anything without a rule stays out) and writes
|
||||
one deterministic tar.gz per archive of ARCHIVES (sorted members, fixed mtime and owner, gzip mtime 0) to DIR,
|
||||
and repro/MANIFEST.json (tracked in git): per archive its licence, size and sha256, per file its archive,
|
||||
producing script, size and sha256 (exact bytes). Members are stored as outputs/<path>, so extracting an
|
||||
archive in the repository root restores the original layout. The archives split by data licence (F3-derived
|
||||
CC BY-SA 3.0; Volve-derived CC BY-NC-SA 4.0; Teapot, licence to be verified) and, within F3, by size.
|
||||
--dry-run prints the selection and sizes without writing.
|
||||
check Recomputes the sha256 of every manifest file under DIR (a tree in which the archives were extracted, i.e.
|
||||
DIR/outputs/...) and reports missing and differing files.
|
||||
verify Clean-room check that the archives and the code suffice. Copies the code (git ls-files -co --exclude-standard,
|
||||
without logs/, refs/, code_thesis/, outputs_thesis/, .agents/; the tracked F3 well files under data/ are part
|
||||
of the repository) into WORK/repo, extracts the archives there, deletes the copied paper figures, and runs the
|
||||
steps of STEPS with WORK/repo first on PYTHONPATH (so `ml_porosity` and the default outputs/ and data/ roots
|
||||
are those of the copy; no SEG-Y, Volve or Teapot raw data). A sitecustomize audit hook logs the files each
|
||||
step opens and flags any read of the original repository. Afterwards every file a step rewrote is compared
|
||||
with the original: by sha256, and, if the bytes differ, by value (csv, json, npz, md); paper figures are
|
||||
rasterised with Ghostscript and compared pixel by pixel with paper/figures/; stdout steps are compared with the
|
||||
same command run on the original outputs. → repro/verify_report.md (git) and WORK/verify.json.
|
||||
WORK defaults to DIR/work and is deleted afterwards unless --keep.
|
||||
code git archive of REV → DIR/ML-Porosity_code_<rev>.tar.gz; refuses when tracked files differ from REV.
|
||||
|
||||
Outside every protocol lock (protocol_bench hashes ml_porosity/ and scripts/34 only). Nothing here trains, edits a
|
||||
locked output or touches the original outputs/: verify writes only inside WORK.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import difflib
|
||||
import fnmatch
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||||
|
||||
DOC = REPO_ROOT / "repro"
|
||||
MANIFEST = DOC / "MANIFEST.json"
|
||||
MTIME = int(datetime(2026, 11, 2, tzinfo=timezone.utc).timestamp()) # fixed member mtime of the archives
|
||||
|
||||
F3 = "CC-BY-SA-3.0"
|
||||
VOLVE = "CC-BY-NC-SA-4.0"
|
||||
TEAPOT = "CC0-1.0 (as recorded in the project notes; verify on the Texas Data Repository page before deposit)"
|
||||
ARCHIVES = {
|
||||
"f3_results": (F3, "Summaries, verdicts, post hoc tables, run-level metric tables and the small derived inputs "
|
||||
"behind every number of the manuscript; F3-derived and synthetic (D2 generator on F3 geometry)"),
|
||||
"f3_predictions": (F3, "Saved test predictions of the registered runs (P1, P2, P2r, T2, protocol_bench, P3) and "
|
||||
"the P2r SMC particles of the S4 cells, which the protocol_bench lock hashes"),
|
||||
"f3_volume": (F3, "Descriptive F3 porosity volume of the 20 P3 deployment models (649 interior inlines)"),
|
||||
"volve": (VOLVE, "Volve-derived well data, P4 summaries and post hoc tables, and the applicability tables that "
|
||||
"combine F3 and Volve (licence of the combination to be confirmed by the authors)"),
|
||||
"teapot": (TEAPOT, "Teapot Dome inventory (headers and curve coverage) and pilot P-a (knots, picks); no porosity"),
|
||||
}
|
||||
|
||||
# (pattern relative to outputs/, archive, producer). First match wins; fnmatch `*` also matches `/`; archive None
|
||||
# excludes. Files that match no rule stay out (large SMC particle files, training checkpoints, P3/P4 training runs,
|
||||
# smoke runs, superseded backups, the separately deposited benchmark package outputs/bench/package, and outputs/p4x,
|
||||
# which the manuscript never uses).
|
||||
RULES = [
|
||||
# F3 audit, tie and well inputs (historical artifacts of scripts 01, 02, 04: never rerun, hashes protected)
|
||||
("td_qc.csv", "f3_results", "scripts/02_td_qc.py"),
|
||||
("tie_qc.csv", "f3_results", "scripts/04_wavelet_tie.py"),
|
||||
("marker_vs_horizon.csv", "f3_results", "scripts/04_wavelet_tie.py"),
|
||||
("tie_local_shifts.csv", "f3_results", "scripts/04_wavelet_tie.py"),
|
||||
("wavelets.npz", "f3_results", "scripts/04_wavelet_tie.py"),
|
||||
("f3_wells.npz", "f3_results", "scripts/01_build_wells.py"),
|
||||
("f3_wells_summary.json", "f3_results", "scripts/01_build_wells.py"),
|
||||
# P1 LOWO baselines
|
||||
("p1/*.npz", "f3_predictions", "scripts/05_lowo.py"),
|
||||
("p1/*", "f3_results", "scripts/05_lowo.py, scripts/06_summarize_p1.py"),
|
||||
# D2 generator QC and horizon cache, warp prior
|
||||
("d2/qc.json", "f3_results", "scripts/10_build_d2.py"),
|
||||
("d2/horizon_grid.npz", "f3_results", "ml_porosity/data/synth_d2.py (horizon cache)"),
|
||||
("p2/warp_prior_f3.json", "f3_results", "scripts/09_fit_warp_prior_f3.py"),
|
||||
# P2 (protocol_p2)
|
||||
("p2/summary/*", "f3_results", "scripts/13_summarize_p2.py"),
|
||||
("p2/h1/*.npz", "f3_predictions", "scripts/12_h1_blur.py"),
|
||||
("p2/h1/*", "f3_results", "scripts/12_h1_blur.py"),
|
||||
("p2/main/*.npz", "f3_predictions", "scripts/11_run_d2.py --main"),
|
||||
("p2/main/*", "f3_results", "scripts/11_run_d2.py --main"),
|
||||
("p2/dev/*.npz", "f3_predictions", "scripts/11_run_d2.py --dev"),
|
||||
("p2/dev/*", "f3_results", "scripts/11_run_d2.py --dev"),
|
||||
("p2/diag/train/budgets.json", "f3_results", "scripts/15_diag_train.py (P2r dev budgets)"),
|
||||
("p2/diag/p2rdev/*", "f3_results", "scripts/17_summarize_p2r_dev.py"),
|
||||
("p2/diag/f3_posterior/*.npz", None, ""),
|
||||
("p2/diag/f3_posterior/*", "f3_results", "scripts/16_f3_posterior.py"),
|
||||
("p2/diag/*.csv", "f3_results", "scripts/run_p2r_dev.sh (dev realizations 900/901)"),
|
||||
("p2/diag/*.json", "f3_results", "scripts/run_p2r_dev.sh (dev realizations 900/901)"),
|
||||
("d1/*", "f3_results", "scripts/08_d1_label_check.py"),
|
||||
# P2r (protocol_p2r) and its post hoc analyses
|
||||
("p2r/summary/*", "f3_results", "scripts/18_summarize_p2r.py"),
|
||||
("p2r/posthoc/*", "f3_results", "scripts/31_p2r_posthoc.py"),
|
||||
("p2r/train/*.npz", "f3_predictions", "scripts/run_p2r_main.sh (scripts/15_diag_train.py)"),
|
||||
("p2r/train/*", "f3_results", "scripts/run_p2r_main.sh (scripts/15_diag_train.py)"),
|
||||
("p2r/posterior/*.csv", "f3_results", "scripts/run_p2r_main.sh (scripts/14_diag_posterior.py)"),
|
||||
("p2r/posterior/*.json", "f3_results", "scripts/run_p2r_main.sh (scripts/14_diag_posterior.py)"),
|
||||
("t2/*.npz", "f3_predictions", "scripts/32_t2_mechanism.py"),
|
||||
("t2/*", "f3_results", "scripts/32_t2_mechanism.py"),
|
||||
("t3/*", "f3_results", "scripts/27_t3_power.py"),
|
||||
("t4/*", "f3_results", "scripts/30_t4_coverage.py"),
|
||||
# protocol_bench (Experiment 3)
|
||||
("bench/summary/verdict_final.*", "f3_results", "scripts/36_bench_verdicts.py"),
|
||||
("bench/summary/s3_h2a_stated.csv", "f3_results", "scripts/36_bench_verdicts.py"),
|
||||
("bench/summary/*", "f3_results", "scripts/34_run_bench.py summarize"),
|
||||
("bench/repro/comparison.json", "f3_results", "scripts/34_run_bench.py repro"),
|
||||
("bench/repro/*", "f3_predictions", "scripts/34_run_bench.py repro"),
|
||||
("bench/dev/calibration.*", "f3_results", "scripts/35_bench_calibration.py"),
|
||||
("bench/dev/generator_*", "f3_results", "scripts/33_bench_generator_qc.py"),
|
||||
("bench/dev/smc_qc_rid*.json", "f3_results", "scripts/33_bench_generator_qc.py --smc"),
|
||||
("bench/dev/budgets_tcn.json", "f3_results", "scripts/34_run_bench.py dev-budgets"),
|
||||
("bench/dev/progress.json", None, ""),
|
||||
("bench/dev/summary/*", "f3_results", "scripts/34_run_bench.py summarize --dev"),
|
||||
("bench/dev/*.csv", "f3_results", "scripts/34_run_bench.py posterior train --dev"),
|
||||
("bench/dev/*.json", "f3_results", "scripts/34_run_bench.py posterior train --dev"),
|
||||
("bench/s[12348]/train/*.npz", "f3_predictions", "scripts/34_run_bench.py train"),
|
||||
("bench/s[12348]/train/*.csv", "f3_results", "scripts/34_run_bench.py train"),
|
||||
("bench/s[12348]/train/*.json", "f3_results", "scripts/34_run_bench.py train"),
|
||||
("bench/posterior/*.csv", "f3_results", "scripts/34_run_bench.py posterior"),
|
||||
("bench/posterior/*.json", "f3_results", "scripts/34_run_bench.py posterior"),
|
||||
# P3 F3 field test (protocol_f3; reproduce from tag protocol-f3)
|
||||
("p3/summary/predictions.npz", "f3_predictions", "scripts/20_summarize_f3.py"),
|
||||
("p3/summary/*", "f3_results", "scripts/20_summarize_f3.py"),
|
||||
("p3/diagnostics/*.npz", "f3_predictions", "scripts/19_run_f3.py diagnostics"),
|
||||
("p3/diagnostics/*", "f3_results", "scripts/19_run_f3.py diagnostics"),
|
||||
("p3/registration/*.npz", "f3_predictions", "scripts/19_run_f3.py register"),
|
||||
("p3/registration/*.json", "f3_results", "scripts/19_run_f3.py register"),
|
||||
("p3/volume/metadata.json", "f3_results", "scripts/21_predict_f3.py"),
|
||||
("p3/volume/state.json", "f3_results", "scripts/21_predict_f3.py"),
|
||||
("p3/volume/*", "f3_volume", "scripts/21_predict_f3.py"),
|
||||
("p3/completion_checks.json", "f3_results", "operations/check_f3_completion.py"),
|
||||
("p3/volume_recovery.json", "f3_results", "operations/resume_f3_volume.py"),
|
||||
("p3/deployment.json", "f3_results", "scripts/21_predict_f3.py"),
|
||||
("p3/benchmark.json", "f3_results", "scripts/19_run_f3.py benchmark"),
|
||||
("p3/registration_benchmark.json", "f3_results", "scripts/19_run_f3.py benchmark"),
|
||||
("p3/review_checks.json", "f3_results", "scripts/19_run_f3.py (review checks)"),
|
||||
# Volve (P4, protocol_volve; reproduce from tag protocol-volve) and the applicability study
|
||||
("volve/*", "volve", "scripts/07_volve_interp_qc.py, scripts/23_build_volve_wells.py"),
|
||||
("p4/summary/*", "volve", "scripts/24_run_volve.py summarize"),
|
||||
("p4/posthoc/*", "volve", "scripts/25_p4_posthoc.py"),
|
||||
("p4/registration/*.json", "volve", "scripts/24_run_volve.py register"),
|
||||
("p4/benchmark.json", "volve", "scripts/24_run_volve.py benchmark"),
|
||||
("applicability/*", "volve", "scripts/26_applicability.py"),
|
||||
# Teapot Dome (stopped at T0 and pilot P-a)
|
||||
("teapot/inventory/*", "teapot", "python -P scripts/28_teapot_inventory.py"),
|
||||
("teapot/pilot_pa/*", "teapot", "python -P scripts/29_teapot_pilot.py"),
|
||||
]
|
||||
S4_PRODUCER = "scripts/run_p2r_main.sh (scripts/14_diag_posterior.py); hashed by the protocol_bench lock"
|
||||
|
||||
# Clean-room steps: (name, argv after the interpreter, kind). kind: "files" (compare rewritten outputs), "figures"
|
||||
# (also compare paper/figures/<name>.pdf), "stdout" (compare stdout with the same command on the original outputs).
|
||||
STEPS = [
|
||||
("p1_summary", ["scripts/06_summarize_p1.py"], "files"),
|
||||
("p2_summary", ["scripts/13_summarize_p2.py", "--mode", "main"], "files"),
|
||||
("p2r_summary", ["scripts/18_summarize_p2r.py"], "files"),
|
||||
("p2r_posthoc", ["scripts/31_p2r_posthoc.py"], "files"),
|
||||
("t4_coverage", ["scripts/30_t4_coverage.py"], "files"),
|
||||
("t3_power", ["scripts/27_t3_power.py"], "files"),
|
||||
("bench_summarize", ["scripts/34_run_bench.py", "summarize"], "files"),
|
||||
("bench_verdicts", ["scripts/36_bench_verdicts.py"], "files"),
|
||||
("bench_tables", ["scripts/37_bench_package.py", "tables", "--out", "outputs/bench/package"], "files"),
|
||||
("figures_main", ["scripts/22_paper_figures.py"], "figures"),
|
||||
("figures_bench", ["scripts/38_bench_figures.py"], "figures"),
|
||||
("s8_flipband", ["scripts/38_bench_figures.py", "--flipband"], "stdout"),
|
||||
]
|
||||
# Files outside outputs/ that a step rewrites in the repository, compared with the original repository files.
|
||||
REPO_OUTPUTS = {"bench_tables": ["benchmark/reference/cells.csv", "benchmark/reference/main_table.md"]}
|
||||
NO_CODE = ("logs/", "refs/", "code_thesis/", "outputs_thesis/", ".agents/")
|
||||
|
||||
SITECUSTOMIZE = '''
|
||||
import os, sys
|
||||
_log = os.environ.get("REPRO_AUDIT_LOG")
|
||||
if _log:
|
||||
_W = os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_APPEND
|
||||
def _hook(event, args, _f=open(_log, "a", buffering=1), _seen=set()):
|
||||
if event == "open" and args and isinstance(args[0], (str, bytes, os.PathLike)):
|
||||
try:
|
||||
p = os.path.abspath(os.fsdecode(args[0]))
|
||||
except Exception:
|
||||
return
|
||||
mode = args[1] if len(args) > 1 else None
|
||||
flags = args[2] if len(args) > 2 and isinstance(args[2], int) else 0
|
||||
w = any(c in mode for c in "wax+") if isinstance(mode, str) else bool(flags & _W)
|
||||
key = ("W " if w else "R ") + p
|
||||
if key not in _seen:
|
||||
_seen.add(key)
|
||||
_f.write(key + "\\n")
|
||||
sys.addaudithook(_hook)
|
||||
'''
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- selection and manifest
|
||||
def sha256(path: Path, bufsize: int = 1 << 22) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
while b := f.read(bufsize):
|
||||
h.update(b)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def s4_reference_files() -> list[Path]:
|
||||
from ml_porosity.benchmark.protocol import load_protocol, p2r_reference_files
|
||||
return [f for f in p2r_reference_files(load_protocol()) if "/posterior/" in f.as_posix()]
|
||||
|
||||
|
||||
def select(root: Path) -> list[dict]:
|
||||
"""Every file of the package: path (outputs/...), archive, producer."""
|
||||
s4 = {f.resolve() for f in s4_reference_files()}
|
||||
rows, seen = [], set()
|
||||
for f in sorted(root.rglob("*")):
|
||||
if not f.is_file() or f.is_symlink():
|
||||
continue
|
||||
rel = f.relative_to(root).as_posix()
|
||||
if f.resolve() in s4:
|
||||
rows.append({"path": f"outputs/{rel}", "archive": "f3_predictions", "producer": S4_PRODUCER})
|
||||
seen.add(f.resolve())
|
||||
continue
|
||||
if rel.startswith(("p2r/posterior/", "bench/posterior/", "bench/dev/")) and rel.endswith(".npz"):
|
||||
continue # other particles and dev predictions: no table reads them
|
||||
for pat, arc, prod in RULES:
|
||||
if fnmatch.fnmatchcase(rel, pat):
|
||||
if arc:
|
||||
rows.append({"path": f"outputs/{rel}", "archive": arc, "producer": prod})
|
||||
break
|
||||
if missing := s4 - seen:
|
||||
raise FileNotFoundError(f"{len(missing)} S4 reference files missing under {root}")
|
||||
return rows
|
||||
|
||||
|
||||
def tar_gz(path: Path, members: list[tuple[str, Path]]) -> None:
|
||||
tmp = path.with_suffix(path.suffix + ".part")
|
||||
with open(tmp, "wb") as raw, gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0, compresslevel=6) as gz, \
|
||||
tarfile.open(fileobj=gz, mode="w", format=tarfile.PAX_FORMAT) as tar:
|
||||
for arc, src in sorted(members):
|
||||
ti = tarfile.TarInfo(arc)
|
||||
ti.size, ti.mtime, ti.mode = src.stat().st_size, MTIME, 0o644
|
||||
ti.uid = ti.gid = 0
|
||||
ti.uname = ti.gname = ""
|
||||
with open(src, "rb") as f:
|
||||
tar.addfile(ti, f)
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def build(a) -> None:
|
||||
root, out = outputs_dir(), Path(a.out)
|
||||
rows = select(root)
|
||||
for r in rows:
|
||||
r["bytes"] = (root / r["path"][len("outputs/"):]).stat().st_size
|
||||
df = pd.DataFrame(rows)
|
||||
print(df.groupby("archive").agg(files=("path", "size"), MB=("bytes", lambda b: round(b.sum() / 1e6, 1))).to_string())
|
||||
if a.dry_run:
|
||||
for arc, g in df.groupby("archive"):
|
||||
top = g.assign(top=g.path.str.split("/").str[1:3].str.join("/")).groupby("top").bytes.agg(["size", "sum"])
|
||||
print(f"\n{arc}\n" + (top.assign(MB=(top["sum"] / 1e6).round(2)).drop(columns="sum")).to_string())
|
||||
return
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
t0 = time.time()
|
||||
for r in rows:
|
||||
r["sha256"] = sha256(root / r["path"][len("outputs/"):])
|
||||
archives = {}
|
||||
for arc, (lic, desc) in ARCHIVES.items():
|
||||
sel = [r for r in rows if r["archive"] == arc]
|
||||
name = f"ML-Porosity_derived_{arc}.tar.gz"
|
||||
tar_gz(out / name, [(r["path"], root / r["path"][len("outputs/"):]) for r in sel])
|
||||
archives[arc] = {"file": name, "licence": lic, "description": desc, "n_files": len(sel),
|
||||
"bytes_uncompressed": int(sum(r["bytes"] for r in sel)),
|
||||
"bytes": (out / name).stat().st_size, "sha256": sha256(out / name)}
|
||||
print(f"wrote {out / name}: {len(sel)} files, {archives[arc]['bytes'] / 1e6:.1f} MB ({time.time() - t0:.0f} s)")
|
||||
DOC.mkdir(exist_ok=True)
|
||||
man = {"package": "ML-Porosity derived data for the manuscript (reproduction package, phase P5)",
|
||||
"layout": "members are outputs/<path>; extract each archive in the repository root",
|
||||
"hash": "sha256 of the exact file bytes", "archives": archives,
|
||||
"files": [{k: r[k] for k in ("path", "archive", "producer", "bytes", "sha256")} for r in rows]}
|
||||
MANIFEST.write_text(json.dumps(man, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
print(f"wrote {MANIFEST} ({len(rows)} files)")
|
||||
|
||||
|
||||
def check_tree(root: Path, man: dict) -> dict:
|
||||
res = {"ok": [], "missing": [], "differs": []}
|
||||
for r in man["files"]:
|
||||
f = root / r["path"]
|
||||
if not f.exists():
|
||||
res["missing"].append(r["path"])
|
||||
elif f.stat().st_size != r["bytes"] or sha256(f) != r["sha256"]:
|
||||
res["differs"].append(r["path"])
|
||||
else:
|
||||
res["ok"].append(r["path"])
|
||||
return res
|
||||
|
||||
|
||||
def check(a) -> None:
|
||||
man = json.loads(MANIFEST.read_text(encoding="utf-8"))
|
||||
res = check_tree(Path(a.root), man)
|
||||
print(f"{len(res['ok'])}/{len(man['files'])} files match; {len(res['missing'])} missing, {len(res['differs'])} differ")
|
||||
for k in ("missing", "differs"):
|
||||
for p in res[k][:20]:
|
||||
print(f" {k}: {p}")
|
||||
if res["missing"] or res["differs"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- comparison helpers
|
||||
def _num_equal(x, y, tol=1e-12) -> float:
|
||||
"""Max relative difference of two numeric arrays (NaN-aware); inf if shapes or NaN patterns differ."""
|
||||
x, y = np.asarray(x, float), np.asarray(y, float)
|
||||
if x.shape != y.shape or not np.array_equal(np.isnan(x), np.isnan(y)):
|
||||
return float("inf")
|
||||
m = ~np.isnan(x)
|
||||
if not m.any():
|
||||
return 0.0
|
||||
return float(np.max(np.abs(x[m] - y[m]) / np.maximum(1.0, np.abs(y[m]))))
|
||||
|
||||
|
||||
def _json_diff(a, b, path="", out=None, tol=1e-9):
|
||||
out = [] if out is None else out
|
||||
if isinstance(a, dict) and isinstance(b, dict):
|
||||
for k in sorted(set(a) | set(b), key=str):
|
||||
if k not in a or k not in b:
|
||||
out.append(f"{path}/{k}: only in {'new' if k in a else 'original'}")
|
||||
else:
|
||||
_json_diff(a[k], b[k], f"{path}/{k}", out, tol)
|
||||
elif isinstance(a, list) and isinstance(b, list) and len(a) == len(b):
|
||||
for i, (x, y) in enumerate(zip(a, b)):
|
||||
_json_diff(x, y, f"{path}[{i}]", out, tol)
|
||||
elif isinstance(a, (int, float)) and isinstance(b, (int, float)) and not isinstance(a, bool):
|
||||
if not (a == b or (np.isnan(a) and np.isnan(b)) or abs(a - b) <= tol * max(1.0, abs(b))):
|
||||
out.append(f"{path}: {b!r} → {a!r}")
|
||||
elif a != b:
|
||||
out.append(f"{path}: {str(b)[:60]!r} → {str(a)[:60]!r}")
|
||||
return out
|
||||
|
||||
|
||||
def compare_file(new: Path, orig: Path, root: Path | None = None) -> dict:
|
||||
"""identical (bytes) | equal (values within 1e-9 relative, or bytes equal once the clean-room root `root` is
|
||||
replaced by the original repository root) | differs (with a short detail) | missing."""
|
||||
if not new.exists():
|
||||
return {"status": "missing", "detail": "not regenerated"}
|
||||
if sha256(new) == sha256(orig):
|
||||
return {"status": "identical"}
|
||||
suf = "".join(new.suffixes[-2:]) if new.name.endswith(".csv.gz") else new.suffix
|
||||
text = None
|
||||
if root is not None and suf in (".csv", ".json", ".md", ".txt"):
|
||||
text = new.read_text(encoding="utf-8").replace(str(root), str(REPO_ROOT))
|
||||
if text.encode("utf-8") == orig.read_bytes():
|
||||
return {"status": "equal", "detail": "differs only in the clean-room path"}
|
||||
try:
|
||||
if suf in (".csv", ".csv.gz"):
|
||||
x, y = pd.read_csv(io.StringIO(text) if text is not None else new), pd.read_csv(orig)
|
||||
if list(x.columns) != list(y.columns) or x.shape != y.shape:
|
||||
return {"status": "differs", "detail": f"shape/columns {x.shape} vs {y.shape}"}
|
||||
worst, cols = 0.0, []
|
||||
for c in x.columns:
|
||||
if pd.api.types.is_numeric_dtype(x[c]) and pd.api.types.is_numeric_dtype(y[c]):
|
||||
d = _num_equal(x[c], y[c])
|
||||
if d > 1e-9:
|
||||
cols.append(f"{c} ({d:.2g})")
|
||||
worst = max(worst, d)
|
||||
elif not x[c].astype(str).equals(y[c].astype(str)):
|
||||
cols.append(f"{c} (text)")
|
||||
return ({"status": "equal", "detail": f"max rel. diff {worst:.1e}"} if not cols else
|
||||
{"status": "differs", "detail": "columns " + ", ".join(cols[:6])})
|
||||
if suf == ".json":
|
||||
d = _json_diff(json.loads(text if text is not None else new.read_text(encoding="utf-8")),
|
||||
json.loads(orig.read_text(encoding="utf-8")))
|
||||
return {"status": "equal"} if not d else {"status": "differs", "detail": "; ".join(d[:4]) + (f" (+{len(d) - 4})" if len(d) > 4 else "")}
|
||||
if suf == ".npz":
|
||||
with np.load(new, allow_pickle=False) as x, np.load(orig, allow_pickle=False) as y:
|
||||
if sorted(x.files) != sorted(y.files):
|
||||
return {"status": "differs", "detail": "keys"}
|
||||
bad = [k for k in x.files if not np.array_equal(x[k], y[k], equal_nan=x[k].dtype.kind == "f")]
|
||||
return {"status": "equal"} if not bad else {"status": "differs", "detail": "arrays " + ", ".join(bad[:5])}
|
||||
if suf in (".md", ".txt"):
|
||||
d = [l for l in difflib.unified_diff(orig.read_text().splitlines(),
|
||||
(text if text is not None else new.read_text()).splitlines(), lineterm="", n=0)
|
||||
if l[:1] in "+-" and not l.startswith(("+++", "---"))]
|
||||
return {"status": "differs", "detail": f"{len(d)} changed lines, e.g. {d[0][:80]!r}" if d else "whitespace"}
|
||||
except Exception as e: # noqa: BLE001 - reported, not fatal
|
||||
return {"status": "differs", "detail": f"compare failed: {e}"}
|
||||
return {"status": "differs", "detail": "bytes differ"}
|
||||
|
||||
|
||||
def raster(pdf: Path, png: Path) -> np.ndarray:
|
||||
from PIL import Image
|
||||
subprocess.run(["gs", "-q", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-sDEVICE=png16m", "-r110", f"-sOutputFile={png}",
|
||||
str(pdf)], check=True)
|
||||
return np.asarray(Image.open(png).convert("RGB"), dtype=np.int16)
|
||||
|
||||
|
||||
def compare_pdf(new: Path, orig: Path, tmp: Path) -> dict:
|
||||
x, y = raster(new, tmp / f"{new.stem}_new.png"), raster(orig, tmp / f"{new.stem}_orig.png")
|
||||
if x.shape != y.shape:
|
||||
return {"status": "differs", "detail": f"page size {x.shape} vs {y.shape}"}
|
||||
d = np.abs(x - y).max(axis=2)
|
||||
frac = float((d > 0).mean())
|
||||
return {"status": "identical" if frac == 0 else ("equal" if frac < 1e-4 else "differs"),
|
||||
"detail": f"{100 * frac:.3f}% pixels differ (max {int(d.max())}/255) at 110 dpi"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- clean room
|
||||
def code_files() -> list[str]:
|
||||
out = subprocess.run(["git", "ls-files", "-co", "--exclude-standard", "-z"], cwd=REPO_ROOT, check=True,
|
||||
capture_output=True).stdout.decode().split("\0")
|
||||
return sorted(f for f in out if f and not f.startswith(NO_CODE) and (REPO_ROOT / f).is_file())
|
||||
|
||||
|
||||
def run_step(name, argv, repo: Path, logs: Path, audit: Path) -> dict:
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("ML_POROSITY_")}
|
||||
env |= {"CUDA_VISIBLE_DEVICES": "", "OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2",
|
||||
"MPLBACKEND": "Agg", "PYTHONPATH": f"{audit}{os.pathsep}{repo}", "PYTHONDONTWRITEBYTECODE": "1",
|
||||
"REPRO_AUDIT_LOG": str(logs / f"{name}.opens"), "REPRO_ORIGINAL_ROOT": str(REPO_ROOT)}
|
||||
t0 = time.time()
|
||||
with open(logs / f"{name}.log", "w") as log:
|
||||
rc = subprocess.run([sys.executable, *argv], cwd=repo, env=env, stdout=log, stderr=subprocess.STDOUT).returncode
|
||||
return {"rc": rc, "seconds": round(time.time() - t0, 1)}
|
||||
|
||||
|
||||
def audit_summary(opens: Path, repo: Path, work: Path) -> dict:
|
||||
"""Files under the clean room's outputs/ and data/ that a step read or wrote, and reads of the original repository
|
||||
(anything under REPO_ROOT except the clean room itself and the shared interpreter REPO_ROOT/.venv)."""
|
||||
rd, wr, leak = set(), set(), set()
|
||||
allowed = (str(work) + os.sep, str(REPO_ROOT / ".venv") + os.sep)
|
||||
if opens.exists():
|
||||
for line in opens.read_text().splitlines():
|
||||
mode, p = line[:1], line[2:]
|
||||
if p.startswith(str(REPO_ROOT) + os.sep) and not p.startswith(allowed):
|
||||
leak.add(p)
|
||||
elif p.startswith(str(repo / "outputs") + os.sep) or p.startswith(str(repo / "data") + os.sep):
|
||||
(wr if mode == "W" else rd).add(Path(p).relative_to(repo).as_posix())
|
||||
return {"read": sorted(rd - wr), "written": sorted(wr), "original_repo_reads": sorted(leak)}
|
||||
|
||||
|
||||
def verify(a) -> None:
|
||||
man = json.loads(MANIFEST.read_text(encoding="utf-8"))
|
||||
out = Path(a.out)
|
||||
work = Path(a.work) if a.work else out / "work"
|
||||
if work.exists():
|
||||
shutil.rmtree(work)
|
||||
repo, logs, audit, tmp = work / "repo", work / "logs", work / "audit", work / "raster"
|
||||
for d in (repo, logs, audit, tmp):
|
||||
d.mkdir(parents=True)
|
||||
(audit / "sitecustomize.py").write_text(SITECUSTOMIZE)
|
||||
t0 = time.time()
|
||||
files = code_files()
|
||||
for f in files:
|
||||
(repo / f).parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(REPO_ROOT / f, repo / f)
|
||||
figs = sorted(f.name for f in (repo / "paper" / "figures").glob("*.pdf"))
|
||||
for f in figs: # regenerated by the figure steps, never copied
|
||||
(repo / "paper" / "figures" / f).unlink()
|
||||
for rel in (r for rels in REPO_OUTPUTS.values() for r in rels):
|
||||
(repo / rel).unlink()
|
||||
for arc, info in man["archives"].items():
|
||||
if sha256(out / info["file"]) != info["sha256"]:
|
||||
raise SystemExit(f"archive {info['file']} does not match the manifest")
|
||||
with tarfile.open(out / info["file"], "r:gz") as tar:
|
||||
tar.extractall(repo, filter="data")
|
||||
(repo / "outputs" / "figures").mkdir(parents=True, exist_ok=True) # quick-look PNGs (06, 13) are not packaged
|
||||
pre = check_tree(repo, man)
|
||||
print(f"clean room {repo}: {len(files)} code files, {len(pre['ok'])}/{len(man['files'])} package files "
|
||||
f"({time.time() - t0:.0f} s)", flush=True)
|
||||
if pre["missing"] or pre["differs"]:
|
||||
raise SystemExit("extracted package does not match the manifest")
|
||||
probe = subprocess.run([sys.executable, "-c", "import ml_porosity, ml_porosity.paths as p; print(ml_porosity.__file__, p.outputs_dir())"],
|
||||
cwd=repo, env={**os.environ, "PYTHONPATH": str(repo)}, capture_output=True, text=True).stdout.split()
|
||||
if not probe or not probe[0].startswith(str(repo)):
|
||||
raise SystemExit(f"ml_porosity resolves outside the clean room: {probe}")
|
||||
|
||||
by_path = {r["path"]: r for r in man["files"]}
|
||||
report = {"git_head": subprocess.run(["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, capture_output=True, text=True).stdout.strip(),
|
||||
"git_dirty": bool(subprocess.run(["git", "status", "--porcelain", "--untracked-files=no"], cwd=REPO_ROOT,
|
||||
capture_output=True, text=True).stdout.strip()),
|
||||
"python": sys.version.split()[0], "started_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"code_files": len(files), "package_files": len(man["files"]), "steps": []}
|
||||
steps = [s for s in STEPS if not a.only or s[0] in a.only]
|
||||
for name, argv, kind in steps:
|
||||
before = set(p.relative_to(repo).as_posix() for p in (repo / "outputs").rglob("*") if p.is_file())
|
||||
t_step = time.time()
|
||||
r = run_step(name, argv, repo, logs, audit)
|
||||
au = audit_summary(logs / f"{name}.opens", repo, work)
|
||||
cmp_ = []
|
||||
for rel in au["written"]:
|
||||
f = repo / rel
|
||||
if rel.startswith("outputs/") and f.is_file():
|
||||
if rel in by_path:
|
||||
cmp_.append({"path": rel, **compare_file(f, REPO_ROOT / rel, repo)})
|
||||
else:
|
||||
cmp_.append({"path": rel, "status": "new" if rel not in before else "not in package"})
|
||||
for rel in REPO_OUTPUTS.get(name, []):
|
||||
cmp_.append({"path": rel, **compare_file(repo / rel, REPO_ROOT / rel, repo)})
|
||||
if kind == "figures":
|
||||
for f in sorted((repo / "paper" / "figures").glob("*.pdf")):
|
||||
if f.stat().st_mtime >= t_step:
|
||||
cmp_.append({"path": f"paper/figures/{f.name}", **compare_pdf(f, REPO_ROOT / "paper" / "figures" / f.name, tmp)})
|
||||
if kind == "stdout":
|
||||
env = {**os.environ, "CUDA_VISIBLE_DEVICES": "", "OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2",
|
||||
"OPENBLAS_NUM_THREADS": "2"}
|
||||
ref = subprocess.run([sys.executable, *argv], cwd=REPO_ROOT, env=env, capture_output=True, text=True).stdout
|
||||
new = (logs / f"{name}.log").read_text()
|
||||
same = new.strip() == ref.strip()
|
||||
nd = sum(1 for l in difflib.unified_diff(ref.splitlines(), new.splitlines(), lineterm="", n=0)
|
||||
if l[:1] in "+-" and not l.startswith(("+++", "---")))
|
||||
cmp_.append({"path": "stdout (vs. the same command on the original outputs)",
|
||||
"status": "identical" if same else "differs", "detail": "" if same else f"{nd} changed lines"})
|
||||
rec = {"name": name, "command": "python " + " ".join(argv), "kind": kind, **r,
|
||||
"n_read_package": sum(1 for p in au["read"] if p in by_path),
|
||||
"read_outside_package": [p for p in au["read"] if p not in by_path and not p.startswith("data/")][:20],
|
||||
"read_data": sorted({"/".join(p.split("/")[:3]) for p in au["read"] if p.startswith("data/")}),
|
||||
"original_repo_reads": au["original_repo_reads"][:20], "compared": cmp_}
|
||||
if r["rc"]:
|
||||
rec["log_tail"] = (logs / f"{name}.log").read_text(errors="replace").splitlines()[-15:]
|
||||
n = {s: sum(c["status"] == s for c in cmp_) for s in ("identical", "equal", "differs", "missing", "new", "not in package")}
|
||||
print(f"[{name}] rc={r['rc']} {r['seconds']:.0f} s; rewritten: {n}; outside reads: "
|
||||
f"{len(rec['read_outside_package'])}; original-repo reads: {len(rec['original_repo_reads'])}", flush=True)
|
||||
report["steps"].append(rec)
|
||||
(work / "verify.json").write_text(json.dumps(report, indent=1))
|
||||
if not a.only:
|
||||
report["figures_not_regenerated"] = [f for f in figs if not (repo / "paper" / "figures" / f).exists()]
|
||||
report["finished_utc"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
(work / "verify.json").write_text(json.dumps(report, indent=1))
|
||||
write_report(report, work, DOC / "verify_report.md" if not a.only else work / "verify_report.md")
|
||||
if not a.keep and not a.only:
|
||||
shutil.rmtree(work)
|
||||
|
||||
|
||||
def write_report(rep: dict, work: Path, dest: Path) -> None:
|
||||
L = ["# Clean-room verification of the reproduction package", "",
|
||||
f"Written by `scripts/39_repro_package.py verify` ({rep['started_utc']} → {rep['finished_utc']}). Code: "
|
||||
f"{rep['code_files']} files of the working tree at {rep['git_head'][:10]}"
|
||||
f"{' with uncommitted changes' if rep['git_dirty'] else ''}; package: {rep['package_files']} files from the "
|
||||
"archives listed in `repro/MANIFEST.json`; Python " + rep["python"] + ", CPU only. No SEG-Y, Volve or "
|
||||
"Teapot raw data in the clean room; the F3 well files tracked in git are present.", "",
|
||||
"Status of a rewritten file: identical = same bytes as the original; equal = same values (csv/json/npz "
|
||||
"within 1e-9 relative, or bytes equal once the clean-room path is replaced by the original one; figures with "
|
||||
"< 0.01% differing pixels at 110 dpi); differs = see detail; missing = expected but not rewritten; new = "
|
||||
"written by the step but not part of the package. Reads are those of files under outputs/ (package) and "
|
||||
"data/ (tracked F3 well files); a read of the original repository would mean the clean room leaked.", "",
|
||||
"| step | command | exit | s | identical | equal | differs | missing | new | reads outside package | reads of original repo |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|"]
|
||||
keys = ("identical", "equal", "differs", "missing")
|
||||
for s in rep["steps"]:
|
||||
c = s["compared"]
|
||||
n = {k: sum(x["status"] == k for x in c) for k in keys}
|
||||
n["new"] = sum(x["status"] in ("new", "not in package") for x in c)
|
||||
L.append(f"| {s['name']} | `{s['command']}` | {s['rc']} | {s['seconds']:.0f} | "
|
||||
+ " | ".join(str(n[k]) for k in (*keys, "new"))
|
||||
+ f" | {len(s['read_outside_package'])} | {len(s['original_repo_reads'])} |")
|
||||
if "figures_not_regenerated" in rep:
|
||||
L += ["", "Paper figures deleted from the clean room and not regenerated: "
|
||||
+ (", ".join(rep["figures_not_regenerated"]) or "none") + "."]
|
||||
L += ["", "## Details", ""]
|
||||
for s in rep["steps"]:
|
||||
L.append(f"### {s['name']}")
|
||||
L.append(f"- package files read: {s['n_read_package']}"
|
||||
+ (f"; tracked data read: {', '.join(s['read_data'])}" if s["read_data"] else ""))
|
||||
for p in s["read_outside_package"]:
|
||||
L.append(f"- read outside the package: `{p}`")
|
||||
for p in s["original_repo_reads"]:
|
||||
L.append(f"- read of the original repository: `{p}`")
|
||||
for k in ("differs", "missing", "new", "not in package", "equal"):
|
||||
xs = [x for x in s["compared"] if x["status"] == k]
|
||||
for x in xs[:25]:
|
||||
L.append(f"- {k}: `{x['path']}`" + (f" ({x['detail']})" if x.get("detail") else ""))
|
||||
if len(xs) > 25:
|
||||
L.append(f"- … {len(xs) - 25} more {k}")
|
||||
L.append(f"- identical: {sum(x['status'] == 'identical' for x in s['compared'])} file(s)")
|
||||
if s.get("log_tail"):
|
||||
L += ["- log tail:", "", "```", *s["log_tail"], "```"]
|
||||
L.append("")
|
||||
dest.write_text("\n".join(L) + "\n", encoding="utf-8")
|
||||
print(f"wrote {dest}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- code snapshot
|
||||
def code(a) -> None:
|
||||
if subprocess.run(["git", "diff", "--quiet", a.rev, "--"], cwd=REPO_ROOT).returncode:
|
||||
raise SystemExit(f"tracked files differ from {a.rev}: commit first, then archive that commit")
|
||||
rev = subprocess.run(["git", "rev-parse", "--short=10", a.rev], cwd=REPO_ROOT, check=True, capture_output=True,
|
||||
text=True).stdout.strip()
|
||||
out = Path(a.out) / f"ML-Porosity_code_{rev}.tar.gz"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out, "wb") as f:
|
||||
subprocess.run(["git", "archive", "--format=tar.gz", f"--prefix=ML-Porosity-{rev}/", a.rev], cwd=REPO_ROOT,
|
||||
check=True, stdout=f)
|
||||
print(f"wrote {out} ({out.stat().st_size / 1e6:.1f} MB, sha256 {sha256(out)})")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
b = sub.add_parser("build")
|
||||
b.add_argument("--dry-run", action="store_true")
|
||||
c = sub.add_parser("check")
|
||||
c.add_argument("--root", required=True)
|
||||
v = sub.add_parser("verify")
|
||||
v.add_argument("--work", default=None)
|
||||
v.add_argument("--only", nargs="+", default=None, choices=[s[0] for s in STEPS])
|
||||
v.add_argument("--keep", action="store_true")
|
||||
k = sub.add_parser("code")
|
||||
k.add_argument("--rev", required=True)
|
||||
for x in (b, v, k):
|
||||
x.add_argument("--out", default=str(outputs_dir() / "repro"))
|
||||
a = ap.parse_args()
|
||||
{"build": build, "check": check, "verify": verify, "code": code}[a.cmd](a)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user