"""Summary of the dev experiments preparing protocol_p2r (scripts/run_p2r_dev.sh). Uses dev realizations 900/901 only. python scripts/17_summarize_p2r_dev.py # every section with available data python scripts/17_summarize_p2r_dev.py --only screen Sections: screen posterior stress grid (outputs/p2/diag/stress/snr*_{full,half,topbottom}/). Each cell (SNR, anchor density, c) is averaged over rid × N × well: - σ_post = width90/3.29 of τ(t); - warp error, 90% coverage; - r at the posterior-mean warp and at the true warp; κ; γ. A cell is "wide" if σ_post (estR wavelet, γ = 1/κ) ≥ 1.5 ms. Threshold from Proposition 1: the transfer coefficient at 50 Hz is exp(−2π²σ²f²) ≤ 0.90. Wide cells are written to wide_cells.txt, which the train stage of run_p2r_dev.sh reads. stability independent SMC runs (stability/p256, p1024; same registration seed): - |Δτ̄(t)| between each pair of runs over the main window; - p95 against the 0.5 ms criterion; - spread of σ_post and of the re-estimated phase. sigma_a registration with σ_a = 3.5 or 14 ms versus 7 ms; data are always generated with σ_a = 7 ms. f3 F3 (f3_posterior/), descriptive only: σ_post, r, κ per well; |Δτ̄| between runs. blur B(σ): band-RMSE penalty when dev Oracle predictions are blurred by σ (Proposition 1); a bound on the attainable gain for H2b. train training in the wide cells (train_stress/*) and H3 with the SMC posterior (h3_smc): - band RMSE of M2-Sa / B3d-Sa / B3c-R / Oracle per cell; - M2-Sa/B3d-Sa ratio per seed and per realization, joined with the cell's σ_post; - H3 results written by scripts/15 (h3.json). → outputs/p2/diag/p2rdev/: screen.csv, wide_cells.txt, stability.csv, sigma_a.csv, f3.csv, train.csv, blur.csv, summary.md """ from __future__ import annotations import argparse import itertools import json import re from pathlib import Path import numpy as np import pandas as pd import yaml from ml_porosity.paths import REPO_ROOT, outputs_dir Z90 = 3.29 # width of the Gaussian 90% interval = 3.29 σ WIDE_MS = 1.5 STAB_MS = 0.5 SMC = ["SMC_g_acf", "SMC_g_one"] DIAG = outputs_dir() / "p2" / "diag" def load_dir(d: Path, k_files: bool = False) -> pd.DataFrame | None: files = [f for f in sorted(d.glob("r*_s*.csv")) if bool(re.search(r"_k\d+\.csv$", f.name)) == k_files] return pd.concat([pd.read_csv(f) for f in files], ignore_index=True) if files else None def cell_stats(df: pd.DataFrame, by: list[str]) -> pd.DataFrame: s = df[df.method.isin(SMC)].assign(sigma_post_ms=lambda d: d.warp_width90_ms / Z90) tab = s.groupby(by + ["wavelet", "method"]).agg( sigma_post_ms=("sigma_post_ms", "mean"), sigma_post_min=("sigma_post_ms", "min"), warp_rmse_ms=("warp_rmse_ms", "mean"), warp_cov90=("warp_cov90", "mean"), r_post=("r_post", "mean"), r_true=("r_true", "mean"), kappa_post=("kappa_post", "mean"), gamma=("gamma", "mean"), n=("well", "size")) b3c = (df[df.method == "B3c"].groupby(by + ["wavelet"])["warp_rmse_ms"].mean().rename("b3c_warp_rmse_ms")) return tab.join(b3c, on=by + ["wavelet"]).reset_index() # ---------------------------------------------------------------- screen def screen(out: Path) -> pd.DataFrame | None: parts = [load_dir(d) for d in sorted((DIAG / "stress").glob("snr*_*")) if re.fullmatch(r"snr-?\d+_[a-z]+", d.name)] parts = [p for p in parts if p is not None] if not parts: return None df = pd.concat(parts, ignore_index=True) by = ["snr_db", "anchor_density", "c"] tab = cell_stats(df, by) per_n = cell_stats(df, by + ["n_train"]) tab.to_csv(out / "screen.csv", index=False) per_n.to_csv(out / "screen_per_n.csv", index=False) key = tab[(tab.wavelet == "estR") & (tab.method == "SMC_g_acf")] wide = key[key.sigma_post_ms >= WIDE_MS] with open(out / "wide_cells.txt", "w") as fh: for (snr, dens), d in wide.groupby(["snr_db", "anchor_density"]): fh.write(f"{snr:g} {dens} {' '.join(f'{c:g}' for c in sorted(d.c))}\n") return tab # ---------------------------------------------------------------- stability def d2_axes() -> tuple: from ml_porosity.registration.warp_prior import WarpGrid P = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text()) cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text()) f, dt = cfg["fine_dt_ms"], cfg["dt_ms"] grid = WarpGrid(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1], cfg["warp_dtau_ms"]) tau_fine = np.arange(cfg["log_tau_ms"][0], cfg["log_tau_ms"][1] + f / 2, f) t_ext = np.arange(cfg["ext_window_ms"][0], cfg["ext_window_ms"][1] + dt / 2, dt) m0, m1 = cfg["main_window_ms"] return grid, tau_fine, t_ext[(t_ext >= m0) & (t_ext <= m1)] def tau_of_t(U: np.ndarray, grid, tau_fine, t_main) -> np.ndarray: from ml_porosity.registration.labels import invert_warps return invert_warps(grid.t_of_tau(U[:, 0], U[:, 1:], tau=tau_fine), tau_fine, t_main) def pair_diffs(means: dict) -> tuple[np.ndarray, list[float]]: """means: {k: τ̄_k(t)} → |Δ| concatenated over all pairs, and max |Δ| of each pair.""" d = [np.abs(means[a] - means[b]) for a, b in itertools.combinations(sorted(means), 2)] return (np.concatenate(d) if d else np.array([])), [float(np.nanmax(x)) for x in d] def stability(out: Path) -> pd.DataFrame | None: dirs = sorted(d for d in (DIAG / "stability").glob("p*") if d.is_dir()) if (DIAG / "stability").exists() else [] if not dirs: return None grid, tau_fine, t_main = d2_axes() rows = [] for d in dirs: runs = {} for f in sorted(d.glob("r*_s*_k*_particles.npz")): rid, c, N, s, k = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)_s(\d+)_k(\d+)_particles", f.stem).groups() runs.setdefault((int(rid), float(c), int(N)), {})[int(k)] = f for (rid, c, N), ks in runs.items(): if len(ks) < 2: continue zs = {k: np.load(f) for k, f in ks.items()} ph = {k: json.loads(f.with_name(f.name.replace("_particles.npz", "_phase.json")).read_text())["phase_R"] for k, f in ks.items()} wells = sorted({key.split("/")[0] for key in zs[min(zs)].files}) for variant in ("estR/g_acf", "estR/g_one"): for w in wells: means, sig = {}, {} for k, z in zs.items(): T = tau_of_t(z[f"{w}/{variant}"].astype(float), grid, tau_fine, t_main) means[k] = np.nanmean(T, 0) q05, q95 = np.nanquantile(T, [0.05, 0.95], axis=0) sig[k] = float(np.mean(q95 - q05)) / Z90 dd, mx = pair_diffs(means) rows.append({"particles": d.name, "rid": rid, "c": c, "n_train": N, "variant": variant, "well": w, "runs": len(ks), "d_p50": float(np.nanmedian(dd)), "d_p95": float(np.nanquantile(dd, 0.95)), "d_max": float(np.nanmax(dd)), "pairs_max_gt1": int(sum(m > 1 for m in mx)), "pairs": len(mx), "sigma_post_mean": float(np.mean(list(sig.values()))), "sigma_post_sd": float(np.std(list(sig.values()))), "phase_R_range": float(np.ptp(list(ph.values())))}) df = pd.DataFrame(rows) df.to_csv(out / "stability.csv", index=False) return df def stability_table(df: pd.DataFrame) -> pd.DataFrame: """The pooled p95 of |Δ| over all wells × t × pairs is not a weighted mean of the per-well p95, so both the median per-well p95 and the maximum p95 are reported; the criterion applies to the p95 of each cell (rid, c, N) averaged over wells.""" g = df.groupby(["particles", "variant", "c"]) return g.agg(runs=("runs", "max"), wells=("well", "size"), d_p50=("d_p50", "median"), d_p95_median=("d_p95", "median"), d_p95_mean=("d_p95", "mean"), d_p95_max=("d_p95", "max"), d_max=("d_max", "max"), pairs_max_gt1=("pairs_max_gt1", "sum"), pairs=("pairs", "sum"), sigma_post=("sigma_post_mean", "mean"), sigma_post_sd=("sigma_post_sd", "mean"), phase_R_range=("phase_R_range", "max")).reset_index() # ---------------------------------------------------------------- σ_a, F3 def sigma_a(out: Path) -> pd.DataFrame | None: parts = [] for d in [DIAG / "stress" / "snr10_full", *sorted((DIAG / "stress").glob("snr10_full_sa*"))]: df = load_dir(d) if d.exists() else None if df is not None: parts.append(df) if len(parts) < 2: return None df = pd.concat(parts, ignore_index=True) old = df[df.method.isin(["M1", "M2"])].groupby(["sigma_a_reg", "c", "method"])[["warp_rmse_ms", "warp_cov90", "warp_width90_ms"]].mean() tab = cell_stats(df, ["sigma_a_reg", "c"]) tab.to_csv(out / "sigma_a.csv", index=False) old.reset_index().to_csv(out / "sigma_a_anchor.csv", index=False) return tab def f3(out: Path) -> tuple[pd.DataFrame, pd.DataFrame] | None: d = DIAG / "f3_posterior" if not (d / "wells.csv").exists(): return None df = pd.read_csv(d / "wells.csv") cols = ["sigma_post_ms", "sd_post_ms", "r_post", "kappa_post", "kappa0", "shift_vs_b3b_rms_ms", "r_b3b", "r_b3c", "r_best_tie_calibrated", "n_anchor"] tab = df.groupby(["setting", "posterior", "well"])[cols].mean() tab["sigma_post_sd_runs"] = df.groupby(["setting", "posterior", "well"])["sigma_post_ms"].std() tab = tab.reset_index() z = np.load(d / "particles.npz") rows = [] for setting, post, w in tab[["setting", "posterior", "well"]].itertuples(index=False): means = {int(re.search(r"/k(\d+)/", k).group(1)): z[k] for k in z.files if k.startswith(f"{setting}/k") and k.endswith(f"/{w}/{post}/mean_tau")} dd, mx = pair_diffs(means) if len(dd): rows.append({"setting": setting, "posterior": post, "well": w, "d_p95": float(np.nanquantile(dd, 0.95)), "d_max": float(np.nanmax(dd))}) stab = pd.DataFrame(rows) tab = tab.merge(stab, on=["setting", "posterior", "well"], how="left") if len(stab) else tab tab.to_csv(out / "f3.csv", index=False) ph = json.loads((d / "phase.json").read_text()) return tab, pd.DataFrame([{"run": k, "phase0": v["phase0"], "phase_R": v["phase_R"], "edge": v.get("edge")} for k, v in ph.items()]) # ---------------------------------------------------------------- train TRAIN_METHODS = ["Oracle", "B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa", "B3d-S1", "M2-S1", "M2"] def train(out: Path, screen_tab: pd.DataFrame | None) -> pd.DataFrame | None: dirs = [(re.fullmatch(r"snr(-?\d+)_([a-z]+)", d.name), d) for d in sorted((DIAG / "train_stress").glob("snr*_*"))] \ if (DIAG / "train_stress").exists() else [] srcs = [(float(m.group(1)), m.group(2), d) for m, d in dirs if m and (d / "runs.csv").exists()] if (DIAG / "h3_smc" / "runs.csv").exists(): srcs.append((10.0, "full", DIAG / "h3_smc")) if not srcs: return None rows = [] for snr, dens, d in srcs: run = pd.read_csv(d / "runs.csv") for (c, N), g in run.groupby(["c", "n_train"]): mean = g.groupby("method")["band_rmse"].mean() pcc = g.groupby("method")["band_pcc"].mean() r = {"source": d.name, "snr_db": snr, "anchor_density": dens, "c": c, "n_train": N, **{f"band_rmse_{m}": mean.get(m, np.nan) for m in TRAIN_METHODS}, **{f"band_pcc_{m}": pcc.get(m, np.nan) for m in TRAIN_METHODS}} for a, b in (("M2-Sa", "B3d-Sa"), ("M2-S1", "B3d-S1"), ("M2-Sa", "B3c-R"), ("B3d-Sa", "B3c-R")): if a in mean and b in mean: x = g[g.method == a].set_index(["rid", "seed"])["band_rmse"] y = g[g.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index) r |= {f"ratio_{a}/{b}": mean[a] / mean[b], f"seeds_better_{a}/{b}": int(((x - y).groupby("seed").mean() < 0).sum()), f"rids_better_{a}/{b}": int(((x - y).groupby("rid").mean() < 0).sum()), "n_seed": int(x.index.get_level_values("seed").nunique()), "n_rid": int(x.index.get_level_values("rid").nunique())} rows.append(r) df = pd.DataFrame(rows) if screen_tab is not None: key = screen_tab[(screen_tab.wavelet == "estR") & (screen_tab.method == "SMC_g_acf")] df = df.merge(key[["snr_db", "anchor_density", "c", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]], on=["snr_db", "anchor_density", "c"], how="left") df.to_csv(out / "train.csv", index=False) return df # ---------------------------------------------------------------- blur BLUR_SIGMAS = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0] def blur(P: np.ndarray, sigma_ms: float, dt_ms: float = 4.0, L: int = 512) -> np.ndarray: """Gaussian filter of Proposition 1, exp(−2π²σ²f²), along the time axis (reflect padding).""" n = P.shape[1] a = L // 2 - n // 2 m = P.mean(1, keepdims=True) Pp = np.pad(P - m, ((0, 0), (a, L - n - a)), mode="reflect") f = np.fft.rfftfreq(L, dt_ms / 1000) out = np.fft.irfft(np.fft.rfft(Pp) * np.exp(-2 * np.pi ** 2 * (sigma_ms / 1000) ** 2 * f ** 2), L) return out[:, a:a + n] + m def blur_sources() -> list[tuple[str, Path]]: """(source, cells directory) pairs with saved predictions: h3_smc (SNR 10, full) and train_stress/snr*_* (same source names as train()).""" srcs = [("h3_smc", DIAG / "h3_smc" / "cells")] if (DIAG / "train_stress").exists(): srcs += [(d.name, d / "cells") for d in sorted((DIAG / "train_stress").glob("snr*_*"))] return [(s, d) for s, d in srcs if d.exists() and any(d.glob("r*_c*_n*.npz"))] def blur_curve(out: Path) -> pd.DataFrame | None: """Band-RMSE penalty when (dev) Oracle predictions are blurred by σ: B(σ) = band_rmse(blur_σ(μ)) / band_rmse(μ). This bounds the gain from removing label blur: if B3d labels have errors ~ N(0, σ²) and RML removes them fully, the best attainable M2/B3d ratio is ≈ 1/B(σ). Computed per source (regime), since noisy inputs already make predictions smoother. Dev realizations only (cells/*.npz of h3_smc and train_stress).""" from ml_porosity.eval.metrics import band_metrics rows = [] for src, cells in blur_sources(): for f in sorted(cells.glob("r*_c*_n*.npz")): rid, c, N = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)", f.stem).groups() z = np.load(f) Y = z["y_true"].astype(float) for k in (k for k in z.files if k.startswith("Oracle/") and k.endswith("/mu")): P0 = z[k].astype(float) b0 = np.mean([band_metrics(Y[i], P0[i], 6)["band_rmse"] for i in range(len(Y))]) for s in BLUR_SIGMAS: Pb = blur(P0, s) rows.append({"source": src, "rid": int(rid), "c": float(c), "n_train": int(N), "seed": k.split("/")[1], "sigma_ms": s, "ratio": np.mean([band_metrics(Y[i], Pb[i], 6)["band_rmse"] for i in range(len(Y))]) / b0}) if not rows: return None df = pd.DataFrame(rows).groupby(["source", "n_train", "sigma_ms"])["ratio"].agg(["mean", "min", "max", "size"]).reset_index() df.to_csv(out / "blur.csv", index=False) return df def dose_response(tr: pd.DataFrame, bl: pd.DataFrame | None) -> tuple[pd.DataFrame, pd.DataFrame]: """H2b on dev: M2-Sa/B3d-Sa ratio versus σ_post (c > 0), with the bound 1/B(σ_post) of the same source and N (linear interpolation on the BLUR_SIGMAS grid; σ outside the grid is clamped to the edge). Spearman per N over all cells.""" from scipy.stats import spearmanr t = tr[(tr.c > 0) & tr["ratio_M2-Sa/B3d-Sa"].notna() & tr.sigma_post_ms.notna()].copy() if bl is not None: def bound(r): b = bl[(bl.source == r.source) & (bl.n_train == r.n_train)] return 1.0 / np.interp(r.sigma_post_ms, b.sigma_ms, b["mean"]) if len(b) else np.nan t["bound_1/B"] = t.apply(bound, axis=1) rows = [] for N, g in t.groupby("n_train"): rho, p = spearmanr(g.sigma_post_ms, g["ratio_M2-Sa/B3d-Sa"]) if len(g) > 2 else (np.nan, np.nan) wide, narrow = g[g.sigma_post_ms >= WIDE_MS], g[g.sigma_post_ms < WIDE_MS] rows.append({"n_train": N, "cells": len(g), "spearman_rho": rho, "spearman_p": p, "wide_cells": len(wide), "wide_ratio_mean": wide["ratio_M2-Sa/B3d-Sa"].mean(), "wide_cells_ratio_lt1": int((wide["ratio_M2-Sa/B3d-Sa"] < 1).sum()), "narrow_cells": len(narrow), "narrow_ratio_max": narrow["ratio_M2-Sa/B3d-Sa"].max()}) return t, pd.DataFrame(rows) # ---------------------------------------------------------------- report def md(df: pd.DataFrame, fmt: str = ".3f") -> str: return df.to_markdown(index=False, floatfmt=fmt) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--only", nargs="+", default=None, choices=["screen", "stability", "sigma_a", "f3", "train", "blur"]) args = ap.parse_args() want = lambda s: args.only is None or s in args.only out = DIAG / "p2rdev" out.mkdir(parents=True, exist_ok=True) pd.set_option("display.width", 250) lines = ["# Dev experiments for protocol_p2r (realizations 900/901)", ""] tab = screen(out) if want("screen") or want("train") else None if tab is not None: key = tab[(tab.wavelet == "estR") & (tab.method == "SMC_g_acf")] show = key[["snr_db", "anchor_density", "c", "sigma_post_ms", "sigma_post_min", "warp_rmse_ms", "warp_cov90", "r_post", "r_true", "kappa_post", "gamma", "b3c_warp_rmse_ms"]].sort_values(["c", "anchor_density", "snr_db"]) lines += ["## Stress grid: SMC posterior (estR, γ = 1/κ)", "", md(show), "", f"Wide cells (σ_post ≥ {WIDE_MS} ms): {len(key[key.sigma_post_ms >= WIDE_MS])}/{len(key)}", ""] print(show.round(3).to_string(index=False)) if want("stability") and (st := stability(out)) is not None: t = stability_table(st) t["pass"] = t.d_p95_max <= STAB_MS lines += ["## Run-to-run stability of SMC", "", md(t), "", f"Criterion: p95 of |Δτ̄(t)| ≤ {STAB_MS} ms in every cell (column d_p95_max).", ""] print(t.round(3).to_string(index=False)) if want("sigma_a") and (sa := sigma_a(out)) is not None: show = sa[sa.method == "SMC_g_acf"][["sigma_a_reg", "c", "wavelet", "sigma_post_ms", "warp_rmse_ms", "warp_cov90", "r_post", "gamma"]] lines += ["## Registration σ_a (data generated with σ_a = 7 ms)", "", md(show), ""] print(show.round(3).to_string(index=False)) if want("f3") and (r := f3(out)) is not None: ft, ph = r lines += ["## F3 (descriptive only)", "", md(ft), "", md(ph), ""] print(ft.round(3).to_string(index=False)) print(ph.to_string(index=False)) tr = train(out, tab) if want("train") else None if tr is not None: cols = [c for c in tr.columns if c.startswith(("source", "snr", "anchor", "c", "n_train", "sigma_post", "ratio_", "seeds_better", "rids_better")) or c in {f"band_rmse_{m}" for m in ("Oracle", "B3c-R", "B3d-Sa", "M2-Sa")}] lines += ["## Training in the wide cells and H3", "", md(tr[cols]), ""] print(tr[cols].round(3).to_string(index=False)) for src in sorted(set(tr.source)): for d in (DIAG / "train_stress" / src, DIAG / src): if (d / "h3.json").exists(): h3 = pd.DataFrame(json.loads((d / "h3.json").read_text())).T lines += [f"### H3 — {src}", "", md(h3.reset_index(names="ensemble/cell")), ""] break bl = blur_curve(out) if want("blur") else None if bl is not None: lines += ["## Band-RMSE penalty from blur (Proposition 1) on dev Oracle predictions", "", md(bl), "", "B(σ) = band_rmse(blurred by σ) / band_rmse(original); 1/B(σ) is the best attainable M2/B3d ratio " "if RML removes all blur.", ""] print(bl.round(4).to_string(index=False)) if want("train") and tr is not None: cells, dr = dose_response(tr, bl) cols = ["source", "c", "n_train", "sigma_post_ms", "ratio_M2-Sa/B3d-Sa", "seeds_better_M2-Sa/B3d-Sa", "rids_better_M2-Sa/B3d-Sa", *(["bound_1/B"] if "bound_1/B" in cells else [])] cells = cells[cols].sort_values(["n_train", "sigma_post_ms"]) cells.to_csv(out / "dose_response.csv", index=False) lines += ["## H2b on dev: M2-Sa/B3d-Sa versus σ_post", "", md(cells), "", md(dr), ""] print(cells.round(3).to_string(index=False)) print(dr.round(3).to_string(index=False)) (out / "summary.md").write_text("\n".join(lines)) print(f"→ {out}") if __name__ == "__main__": main()