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:
2026-11-02 07:12:58 +00:00
parent 2e4f618947
commit 423a333ae9
40 changed files with 82893 additions and 170 deletions

627
scripts/39_repro_package.py Normal file
View 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()