Files
ML-Porosity/ml_porosity/benchmark/cells.py
lamlvh f3c30517fa Add P6 benchmark code, locked protocol_bench, T2 study and lock inputs
- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
  misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
  (sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- The eight protocol_bench inputs force-added from outputs/ (warp prior,
  wavelets, horizon cache, budgets) so load_protocol() and summarize work
  after a fresh clone. The 102 P2r reference artifacts (1.4 GB of particle
  npz) are not in git; they are only checked by posterior/train stages.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.

Main S1 runs are still training at this commit; results follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 01:06:59 +00:00

154 lines
6.3 KiB
Python

"""Cell enumeration and output paths of protocol_bench.
A cell is one (study, regime, preset, c, N, rid[, Δ]) with its method list, budgets and backbone. Paths are flat and
deterministic. Posterior files follow the protocol_p2r layout (r{rid}_c{c}_n{N}_s{reg_seed}{.csv,_particles.npz,
_phase.json}) so that scripts 15/18-style readers and the P2r reference share one reader.
"""
from __future__ import annotations
import itertools
from dataclasses import dataclass, field
from pathlib import Path
from ml_porosity.paths import outputs_dir
P2R_GRID = {"drift_factors": (0.0, 1.0, 2.0), "n_train": (4, 16)}
@dataclass(frozen=True)
class Cell:
study: str
regime: str
preset: str | None # misspecification preset of configs/d2_synth_bench.yaml (None: nominal)
c: float
n_train: int
rid: int
methods: tuple[str, ...]
backbone: str = "cnngru" # cnngru (bank_train.train_predict, as P2r) | tcn (f3.training.TCNHetero)
posterior: str = "bench" # bench (this protocol's SMC) | p2r (outputs/p2r/posterior) | none
delta_ms: float | None = None # S8 two-mode separation
tags: tuple[str, ...] = field(default_factory=tuple)
@property
def setting(self) -> str:
return self.regime if self.preset in (None, "nominal") else f"{self.regime}__{self.preset}"
@property
def tag(self) -> str:
t = f"r{self.rid}_c{self.c:g}_n{self.n_train}"
if self.delta_ms is not None:
t += f"_d{self.delta_ms:g}"
return t
def suffix(self) -> str:
return "" if self.backbone == "cnngru" else f"__{self.backbone}"
def bench_root(dev: bool = False, repro: bool = False) -> Path:
root = outputs_dir() / "bench"
return root / ("repro" if repro else "dev" if dev else "")
def posterior_dir(cell: Cell, root: Path) -> Path | None:
if cell.posterior == "none":
return None
if cell.posterior == "p2r":
return outputs_dir() / "p2r" / "posterior" / cell.regime
return root / "posterior" / cell.setting # shared by every study that needs the same (regime, preset) posterior
def posterior_paths(cell: Cell, root: Path, reg_seed: int) -> dict[str, Path]:
d = posterior_dir(cell, root)
tag = f"r{cell.rid}_c{cell.c:g}_n{cell.n_train}_s{reg_seed}"
return {"csv": d / f"{tag}.csv", "particles": d / f"{tag}_particles.npz", "phase": d / f"{tag}_phase.json",
"meta": d / f"{tag}.json"}
def train_dir(cell: Cell, root: Path) -> Path:
return root / cell.study.lower() / "train" / cell.setting / "cells"
def train_paths(cell: Cell, root: Path) -> dict[str, Path]:
d = train_dir(cell, root)
stem = cell.tag + cell.suffix()
return {"csv": d / f"{stem}.csv", "npz": d / f"{stem}.npz", "diag": d / f"{stem}_diag.csv", "meta": d / f"{stem}.json"}
# ---------------------------------------------------------------- study → cells
def _rids(p: dict, rids) -> list[int]:
return [int(r) for r in (p["grid"]["realizations"] if rids is None else rids)]
def _grid(s: dict, grid: dict | None) -> tuple[list, list]:
g = grid or {}
return list(g.get("drift_factors") or s.get("drift_factors", [])), list(g.get("n_train") or s["n_train"])
def s1_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
"""grid: dev-only override {drift_factors, n_train}; with an override the P2r-grid exclusion is lifted."""
s = p["studies"]["S1"]
cs, ns = _grid(s, grid)
cells = []
for reg in (regimes or s["regimes"]):
for c, N in itertools.product(cs, ns):
if grid is None and float(c) in P2R_GRID["drift_factors"] and int(N) in P2R_GRID["n_train"]:
continue # existing protocol_p2r cell: read, not recomputed
for rid in _rids(p, rids):
cells.append(Cell("S1", reg, None, float(c), int(N), rid, tuple(s["methods"])))
return cells
def s2_cells(p: dict, rids=None, regimes=None, presets=None, controls: bool = False, grid: dict | None = None) -> list[Cell]:
s = p["studies"]["S2"]
names = presets or [name for axis in s["presets"].values() for name in axis]
if controls:
names = list(names) + list(s.get("controls", {}).get("presets", []))
cs, ns0 = _grid(s, grid)
cells = []
for reg in (regimes or s["regimes"]):
for name in names:
ns = ns0 if (grid or name not in s.get("controls", {}).get("presets", [])) else s["controls"]["n_train"]
for c, N in itertools.product(cs, ns):
for rid in _rids(p, rids):
cells.append(Cell("S2", reg, name, float(c), int(N), rid, tuple(s["methods"])))
return cells
def s3_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
s = p["studies"]["S3"]
cs, ns = _grid(s, grid)
post = "bench" if grid is not None else s.get("posterior", "none") # dev override: dev posteriors of the setting
return [Cell("S3", reg, None, float(c), int(N), rid, tuple(s["methods"]), posterior=post)
for reg in (regimes or s["regimes"]) for c, N in itertools.product(cs, ns) for rid in _rids(p, rids)]
def s4_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
"""Dev override: posterior 'bench' (dev posteriors of the same setting) instead of the P2r particles."""
s = p["studies"]["S4"]
ns = _grid(s, grid)[1]
return [Cell("S4", cell["regime"], None, float(cell["c"]), int(N), rid, tuple(s["methods"]), backbone=s["backbone"],
posterior="bench" if grid is not None else s["posterior"])
for cell in s["cells"] if regimes is None or cell["regime"] in regimes
for N in ns for rid in _rids(p, rids)]
def s8_cells(p: dict, rids=None, regimes=None, grid: dict | None = None) -> list[Cell]:
s = p["studies"]["S8"]
cs, ns = _grid(s, grid)
return [Cell("S8", reg, None, float(c), int(N), rid, tuple(s["methods"]), posterior="none", delta_ms=float(d))
for reg in (regimes or s["regimes"]) for d in s["delta_ms"]
for c, N in itertools.product(cs, ns) for rid in _rids(p, rids)]
STUDIES = {"S1": s1_cells, "S2": s2_cells, "S3": s3_cells, "S4": s4_cells, "S8": s8_cells}
def study_cells(p: dict, study: str, rids=None, regimes=None, **kw) -> list[Cell]:
return STUDIES[study](p, rids=rids, regimes=regimes, **kw)
def needs_posterior(cell: Cell) -> bool:
return cell.posterior == "bench"