"""Paired S3-vs-S2 statistics for each model under runs/, at TWO levels: * per_image (Method 1) -- pool every test image across all phases, pair S3 vs S2 by (phase, sample_id). * phase_level (Method 2) -- one paired value per phase = the phase-mean of the metric; pair S3-mean vs S2-mean across phases. Same paired machinery as ablation_stats.py: paired t-test, Wilcoxon signed-rank (zero_method="wilcox"), sign-flip permutation, bootstrap CI for the mean delta, Hodges-Lehmann estimate + CI, Cohen's dz, rank-biserial r, Shapiro-Wilk on the diffs, Holm correction. HD95 is the only lower-is-better metric. Auto-discovers every model folder directly under runs/ (each distinct MODEL_NAME). One .xlsx per model + a combined cross-model summary. Usage: python model_stats_s2_vs_s3.py # scans ./runs python model_stats_s2_vs_s3.py --runs-root X """ from __future__ import annotations import argparse import json import pathlib import re from collections import defaultdict import numpy as np import pandas as pd from scipy import stats # metric -> higher_is_better METRICS = { "biou_contour": True, # manuscript's reported "BIoU" (1-px contour) "biou": True, # Cheng et al. CVPR 2021 d-pixel band Boundary IoU "dice": True, "iou": True, "ppv": True, "sen": True, "hd95": False, # lower is better } PRIMARY = "biou_contour" ALPHA = 0.05 N_BOOT = 20000 N_BOOT_HL = 4000 N_PERM = 20000 SEED = 20260709 # S3 is the first arm, S2 the second: Mean_delta = S3 - S2, positive favours S3 LABEL = {2: "S2 (baseline)", 3: "S3 (refinement)"} # ---------------------------------------------------------------- stats helpers def holm(pvals): pvals = np.asarray(pvals, dtype=float) order = np.argsort(pvals) m = len(pvals) adj = np.empty(m) running = 0.0 for rank, idx in enumerate(order): running = max(running, (m - rank) * pvals[idx]) adj[idx] = min(running, 1.0) return adj def boot_ci_mean(d, rng): idx = rng.integers(0, len(d), size=(N_BOOT, len(d))) return np.percentile(d[idx].mean(axis=1), [2.5, 97.5]) def hodges_lehmann(d): i, j = np.triu_indices(len(d), k=0) return float(np.median((d[i] + d[j]) / 2.0)) def boot_ci_hl(d, rng): idx = rng.integers(0, len(d), size=(N_BOOT_HL, len(d))) return np.percentile([hodges_lehmann(d[r]) for r in idx], [2.5, 97.5]) def sign_flip_perm_p(d, rng): obs = abs(d.mean()) signs = rng.choice([-1.0, 1.0], size=(N_PERM, len(d))) null = np.abs((signs * d).mean(axis=1)) return (np.sum(null >= obs - 1e-15) + 1) / (N_PERM + 1) def rank_biserial(d): nz = d[d != 0] if len(nz) == 0: return 0.0 r = stats.rankdata(np.abs(nz)) rp, rm = r[nz > 0].sum(), r[nz < 0].sum() return float((rp - rm) / (rp + rm)) def analyse(x, y, metric, higher_better, level, rng): """x = S3 vector, y = S2 vector (paired). Returns (rows, delta).""" d = np.asarray(x, float) - np.asarray(y, float) n = len(d) mean_d, sd_d = float(d.mean()), float(d.std(ddof=1)) if n > 1 else float("nan") se = sd_d / np.sqrt(n) if n > 1 else float("nan") if n >= 2: t_stat, p_t = stats.ttest_rel(x, y) crit = stats.t.ppf(1 - ALPHA / 2, df=n - 1) t_ci = (mean_d - crit * se, mean_d + crit * se) else: t_stat, p_t, t_ci = np.nan, 1.0, (np.nan, np.nan) if n >= 1 and not np.allclose(d, 0): try: w_stat, p_w = stats.wilcoxon(x, y, zero_method="wilcox", alternative="two-sided") except ValueError: w_stat, p_w = np.nan, 1.0 else: w_stat, p_w = np.nan, 1.0 p_perm = sign_flip_perm_p(d, rng) if n >= 1 else 1.0 b_lo, b_hi = boot_ci_mean(d, rng) if n >= 2 else (np.nan, np.nan) hl = hodges_lehmann(d) if n >= 1 else np.nan hl_lo, hl_hi = boot_ci_hl(d, rng) if n >= 2 else (np.nan, np.nan) shapiro_p = float(stats.shapiro(d).pvalue) if (n >= 3 and not np.allclose(d, 0)) else np.nan p_holm_c = holm([p_t, p_w, p_perm]) better = (mean_d > 0) == higher_better winner = LABEL[3] if better else LABEL[2] rows = [] for name, stat, p_raw, p_adj in [ ("Paired t-test", float(t_stat), float(p_t), p_holm_c[0]), ("Wilcoxon signed-rank", float(w_stat), float(p_w), p_holm_c[1]), ("Sign-flip permutation", mean_d, float(p_perm), p_holm_c[2]), ]: rows.append({ "Level": level, "Metric": metric, "Higher_is_better": higher_better, "Contrast": "S3 - S2", "Test": name, "n_pairs": n, "n_zero_diff": int(np.sum(d == 0)), "Statistic": stat, "Mean_delta": mean_d, "SD_delta": sd_d, "p_raw": p_raw, "p_Holm_within_metric_level": p_adj, "Sig_within_metric_level": "Yes" if p_adj < ALPHA else "No", "Better_arm": winner if p_adj < ALPHA else "n.s.", "t_CI_low": t_ci[0], "t_CI_high": t_ci[1], "boot_CI_low": b_lo, "boot_CI_high": b_hi, "CI_excludes_zero": "Yes" if (b_lo > 0) or (b_hi < 0) else "No", "HodgesLehmann_delta": hl, "HL_CI_low": hl_lo, "HL_CI_high": hl_hi, "Cohens_dz": mean_d / sd_d if (sd_d and sd_d > 0) else np.nan, "Rank_biserial_r": rank_biserial(d), "Shapiro_p_on_diffs": shapiro_p, "Diffs_normal_at_0.05": "n/a" if np.isnan(shapiro_p) else ("No" if shapiro_p < ALPHA else "Yes"), }) return rows, d # ---------------------------------------------------------------- discovery def read_threshold(final_dir: pathlib.Path): rc = final_dir / "run_config.json" if rc.exists(): try: return json.loads(rc.read_text()).get("threshold") except Exception: return None return None def discover(runs_root: pathlib.Path): """model -> phase -> strategy -> {'per_sample': {sid: row}, 'threshold': float}""" data: dict[str, dict[int, dict[int, dict]]] = defaultdict(lambda: defaultdict(dict)) for ev in runs_root.glob("*/**/strategy_*/final/evaluation.json"): final_dir = ev.parent ms = re.search(r"strategy_(\d+)", final_dir.parent.name) if not ms: continue s = int(ms.group(1)) if s not in (2, 3): continue try: model = ev.relative_to(runs_root).parts[0] except ValueError: continue pm = re.search(r"phase_(\d+)", str(ev)) phase = int(pm.group(1)) if pm else 1 try: payload = json.loads(ev.read_text()) except Exception: continue data[model][phase][s] = { "per_sample": {row["sample_id"]: row for row in payload.get("per_sample", [])}, "threshold": read_threshold(final_dir), } return data # ---------------------------------------------------------------- per model def analyse_model(model, phase_map, rng): phases = sorted(p for p in phase_map if 2 in phase_map[p] and 3 in phase_map[p]) if not phases: return None # per-image pooled arrays + per-phase means img = {m: {2: [], 3: []} for m in METRICS} phase_mean = {m: {2: [], 3: []} for m in METRICS} phase_used, n_img_per_phase, split_warnings = [], [], [] thr = {2: None, 3: None} for p in phases: s2, s3 = phase_map[p][2], phase_map[p][3] thr[2] = thr[2] or s2.get("threshold") thr[3] = thr[3] or s3.get("threshold") set2, set3 = set(s2["per_sample"]), set(s3["per_sample"]) if set2 != set3: split_warnings.append(f"phase {p}: S2/S3 sample_id sets differ " f"(|S2|={len(set2)}, |S3|={len(set3)}, common={len(set2 & set3)})") ids = sorted(set2 & set3) if not ids: continue phase_used.append(p) n_img_per_phase.append(len(ids)) for m in METRICS: v2 = np.array([s2["per_sample"][i][m] for i in ids], float) v3 = np.array([s3["per_sample"][i][m] for i in ids], float) img[m][2].append(v2) img[m][3].append(v3) phase_mean[m][2].append(float(v2.mean())) phase_mean[m][3].append(float(v3.mean())) test_rows, desc_rows = [], [] per_image = {"phase": np.concatenate([[p] * n for p, n in zip(phase_used, n_img_per_phase)]).astype(int)} per_phase = {"phase": np.array(phase_used, int)} for m, hib in METRICS.items(): x_img = np.concatenate(img[m][3]) if img[m][3] else np.array([]) y_img = np.concatenate(img[m][2]) if img[m][2] else np.array([]) pm2 = np.array(phase_mean[m][2], float) pm3 = np.array(phase_mean[m][3], float) # descriptives, both levels for s, arr_img, arr_ph in [(2, y_img, pm2), (3, x_img, pm3)]: desc_rows.append({ "Metric": m, "Higher_is_better": hib, "Arm": LABEL[s], "n_images": len(arr_img), "img_Mean": arr_img.mean() if len(arr_img) else np.nan, "img_SD": arr_img.std(ddof=1) if len(arr_img) > 1 else np.nan, "img_Median": np.median(arr_img) if len(arr_img) else np.nan, "n_phases": len(arr_ph), "phase_Mean": arr_ph.mean() if len(arr_ph) else np.nan, "phase_SD": arr_ph.std(ddof=1) if len(arr_ph) > 1 else np.nan, }) # per_image tests rows, d_img = analyse(x_img, y_img, m, hib, "per_image", rng) test_rows.extend(rows) per_image[f"{m}__S2"] = y_img per_image[f"{m}__S3"] = x_img per_image[f"{m}__delta_S3_minus_S2"] = d_img # phase_level tests rows_ph, d_ph = analyse(pm3, pm2, m, hib, "phase_level", rng) test_rows.extend(rows_ph) per_phase[f"{m}__S2_phase_mean"] = pm2 per_phase[f"{m}__S3_phase_mean"] = pm3 per_phase[f"{m}__delta_S3_minus_S2"] = d_ph tests_df = pd.DataFrame(test_rows) # global Holm across this model's whole workbook (metrics x 2 levels x 3 tests) tests_df["p_Holm_global"] = holm(tests_df["p_raw"].values) tests_df["Sig_global"] = np.where(tests_df["p_Holm_global"] < ALPHA, "Yes", "No") return { "phases": phase_used, "thr": thr, "split_warnings": split_warnings, "tests": tests_df, "descriptives": pd.DataFrame(desc_rows), "per_image": pd.DataFrame(per_image), "per_phase": pd.DataFrame(per_phase), } def readme_frame(model, res): return pd.DataFrame({"Field": [ "Model", "Contrast", "Phases used", "n phases", "S2 threshold", "S3 threshold", "per_image level", "phase_level level", "Metrics", "PRIMARY", "hd95 direction", "Wilcoxon zero handling", "Bootstrap", "Permutation", "Holm scope", "Split check", "Split warnings", "Seed", ], "Value": [ model, "S3 (refinement) - S2 (baseline); positive delta favours S3", ", ".join(map(str, res["phases"])), len(res["phases"]), str(res["thr"][2]), str(res["thr"][3]), "pool all test images across phases, paired by (phase, sample_id) [manuscript Method 1]", "one paired value per phase = phase-mean of the metric, paired across phases [manuscript Method 2]", ", ".join(METRICS), PRIMARY, "LOWER is better; direction handled in Better_arm", "zero_method='wilcox' (zero diffs dropped)", f"{N_BOOT} resamples for mean-delta CI; {N_BOOT_HL} for Hodges-Lehmann", f"{N_PERM} sign flips; p floor ~= 1/{N_PERM + 1}", "Holm across every test in this workbook (metrics x 2 levels x 3 tests) = p_Holm_global", "asserted S2 and S3 test sample_id sets identical within each phase", "; ".join(res["split_warnings"]) if res["split_warnings"] else "none", f"numpy default_rng({SEED})", ]}) def write_workbook(model, res, out_dir): out = out_dir / f"{model}__s2_vs_s3_stats.xlsx" try: with pd.ExcelWriter(out, engine="openpyxl") as xl: readme_frame(model, res).to_excel(xl, sheet_name="README", index=False) res["descriptives"].to_excel(xl, sheet_name="Descriptives", index=False) res["tests"].to_excel(xl, sheet_name="Tests", index=False) res["per_phase"].to_excel(xl, sheet_name="PerPhase", index=False) res["per_image"].to_excel(xl, sheet_name="PerImage", index=False) for sh in xl.book.worksheets: for col in sh.columns: w = max((len(str(c.value)) if c.value is not None else 0) for c in col) sh.column_dimensions[col[0].column_letter].width = min(max(w + 2, 12), 62) sh.freeze_panes = "A2" return out except Exception as exc: # openpyxl missing -> CSV fallback print(f"[stats] xlsx failed for {model} ({exc}); writing CSVs instead") res["tests"].to_csv(out_dir / f"{model}__tests.csv", index=False) res["descriptives"].to_csv(out_dir / f"{model}__descriptives.csv", index=False) res["per_phase"].to_csv(out_dir / f"{model}__per_phase.csv", index=False) return None def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--runs-root", default="runs") args = ap.parse_args() runs_root = pathlib.Path(args.runs_root).resolve() if not runs_root.is_dir(): print(f"[stats] runs root not found: {runs_root}") return 1 data = discover(runs_root) if not data: print(f"[stats] no evaluation.json found under {runs_root}") return 1 out_dir = runs_root / "_stats" out_dir.mkdir(parents=True, exist_ok=True) rng = np.random.default_rng(SEED) summary_rows = [] for model in sorted(data): res = analyse_model(model, data[model], rng) if res is None: print(f"[stats] {model}: no phase has both S2 and S3 -- skipped") continue wb = write_workbook(model, res, out_dir) print(f"[stats] {model:28s} phases={len(res['phases'])} -> {wb.name if wb else '(csv)'}" + (" [SPLIT WARNINGS]" if res["split_warnings"] else "")) # headline: Wilcoxon row per metric per level for the cross-model summary t = res["tests"] for m in METRICS: for level in ("per_image", "phase_level"): r = t[(t.Metric == m) & (t.Level == level) & (t.Test == "Wilcoxon signed-rank")] if r.empty: continue r = r.iloc[0] summary_rows.append({ "Model": model, "Metric": m, "Level": level, "n_pairs": int(r.n_pairs), "S3_minus_S2": r.Mean_delta, "Wilcoxon_p_raw": r.p_raw, "p_Holm_global": r.p_Holm_global, "Sig_global": r.Sig_global, "Better_arm": r.Better_arm, "Cohens_dz": r.Cohens_dz, "boot_CI_low": r.boot_CI_low, "boot_CI_high": r.boot_CI_high, }) summary_df = pd.DataFrame(summary_rows) summary_df.to_csv(out_dir / "ALL_MODELS_summary.csv", index=False) try: with pd.ExcelWriter(out_dir / "ALL_MODELS_summary.xlsx", engine="openpyxl") as xl: summary_df.to_excel(xl, sheet_name="Summary", index=False) for sh in xl.book.worksheets: for col in sh.columns: w = max((len(str(c.value)) if c.value is not None else 0) for c in col) sh.column_dimensions[col[0].column_letter].width = min(max(w + 2, 12), 40) sh.freeze_panes = "A2" except Exception: pass print(f"\n[stats] wrote per-model workbooks + ALL_MODELS_summary to {out_dir}") if not summary_df.empty: pd.set_option("display.width", 240, "display.max_columns", 40) prim = summary_df[summary_df.Metric == PRIMARY] print(f"\n=== PRIMARY ({PRIMARY}) S3-vs-S2, both levels ===") print(prim.to_string(index=False, float_format=lambda v: f"{v:.4g}")) return 0 if __name__ == "__main__": raise SystemExit(main())