"""926/B — aggregate per-subject diffusion runs into results.json / summary.md.""" import json from pathlib import Path import numpy as np B = Path("/home/hubin/926/results/B") METRICS = ["chamfer_l2", "chamfer_l1", "fscore_0.1", "fscore_0.05", "emd_256"] LOWER_BETTER = {"chamfer_l2": True, "chamfer_l1": True, "fscore_0.1": False, "fscore_0.05": False, "emd_256": True} REF = "paired_4avg" def boot(d, n=10000, seed=0): rng = np.random.default_rng(seed) m = d[rng.integers(0, len(d), (n, len(d)))].mean(1) return [float(np.quantile(m, 0.025)), float(np.quantile(m, 0.975))] def main(): subs = {} for p in sorted((B / "per_subject").glob("sub*.json")): d = json.load(open(p)) by = {} for r in d["rows"]: by.setdefault(r["condition"], []).append(r) subs[d["subject"]] = {c: {k: float(np.mean([r[k] for r in rs])) for k in METRICS} | {"n": len(rs)} for c, rs in by.items()} conds = [c for c in json.load(open(next((B / "per_subject").glob("sub*.json"))))["conditions"]] \ if "conditions" in json.load(open(next((B / "per_subject").glob("sub*.json")))) else list(next(iter(subs.values()))) complete = [s for s in subs if all(c in subs[s] and subs[s][c]["n"] == 144 for c in conds)] S = sorted(complete) def delta(c, ref, k): d = np.array([subs[s][c][k] - subs[s][ref][k] for s in S]) return {"delta": float(d.mean()), "ci95_subject": boot(d), "per_subject": dict(zip(S, d.tolist())), "n_worse": int((d > 0).sum() if LOWER_BETTER[k] else (d < 0).sum())} table = {c: {k: {"mean": float(np.mean([subs[s][c][k] for s in S])), "sd_subject": float(np.std([subs[s][c][k] for s in S], ddof=1)) if len(S) > 1 else None} for k in METRICS} for c in conds} deltas = {c: {k: delta(c, REF, k) for k in METRICS} for c in conds if c != REF} deltas_single = {c: delta(c, "paired_single", "chamfer_l2") for c in conds if c != "paired_single"} checks = [] def chk(name, c, ref, want): d = delta(c, ref, "chamfer_l2") lo, hi = d["ci95_subject"] ok = hi < 0 if want == "better" else lo > 0 checks.append({"check": name, "input": c, "reference": ref, "want": f"{want} than reference (Chamfer-L2)", "delta": d["delta"], "ci95_subject": d["ci95_subject"], "pass": bool(ok)}) chk("trial-matched target mean", "target_trialmatched4", REF, "better") chk("trial-matched wrong mean", "wrong_trialmatched4", REF, "worse") chk("within-subject target mean", "target_within", REF, "better") chk("within-subject wrong mean", "wrong_within", REF, "worse") for m in ("varnorm", "spectrum", "cov"): chk(f"target mean vs moment-matched paired ({m})", "target_within", f"paired_match_{m}", "better") chk(f"wrong mean vs moment-matched paired ({m})", "wrong_within", f"paired_match_{m}", "worse") passed = len(S) > 1 and all(c["pass"] for c in checks) meta = json.load(open(next((B / "per_subject").glob("sub*.json")))) res = {"experiment": "926_B_mean_input_controls", "decoder": "released Neuro-3D point diffusion, 200k steps, frozen; 200 sampling steps; batch 48; " "seed = 20260722 + batch start (identical across inputs)", "checkpoint_step": meta.get("checkpoint_step"), "subjects_complete": S, "n_subjects": len(S), "objects_per_subject": 144, "reference": REF, "note": "diffusion-to-target distances (~0.4) live in their own column and are NOT the main endpoint (A)", "wrong_category": "(c + 1) mod 72", "per_condition": table, "delta_vs_paired_4avg": deltas, "delta_vs_paired_single_chamfer_l2": deltas_single, "pass_checks": checks, "decision": "keep" if passed else "drop", "test_status": "secondary (main endpoint is A)", "per_subject": subs} json.dump(res, open(B / "results.json", "w"), indent=1) L = [f"# B — mean inputs to the frozen diffusion decoder\n", f"**decision: {res['decision']}** (secondary test; {len(S)} subjects complete: {', '.join(S)})\n", "Released Neuro-3D point diffusion (200k), frozen; same targets, weights and sampling seed for every input. " "Wrong category = (c+1) mod 72. Statistical unit = subject; 95% CI = bootstrap over subjects. " "These diffusion-to-target distances (~0.4) are a separate column and are not the main endpoint.\n", "## Per input (subject means)\n", "| input | Chamfer-L2 | Δ vs paired 4-avg [95% CI] | F@0.1 | Δ F@0.1 | EMD | Δ EMD |", "|---|---|---|---|---|---|---|"] for c in conds: t = table[c] if c == REF: L.append(f"| {c} | {t['chamfer_l2']['mean']:.4f} | — | {t['fscore_0.1']['mean']:.4f} | — | {t['emd_256']['mean']:.4f} | — |") continue d = deltas[c] f = lambda k: f"{d[k]['delta']:+.4f} [{d[k]['ci95_subject'][0]:+.4f}, {d[k]['ci95_subject'][1]:+.4f}]" L.append(f"| {c} | {t['chamfer_l2']['mean']:.4f} | {f('chamfer_l2')} | {t['fscore_0.1']['mean']:.4f} | " f"{f('fscore_0.1')} | {t['emd_256']['mean']:.4f} | {f('emd_256')} |") L += ["\n## Pass checks (Chamfer-L2, CI must exclude 0)\n", "| check | Δ [95% CI] | pass |", "|---|---|---|"] for c in checks: L.append(f"| {c['check']} (`{c['input']}` − `{c['reference']}`) | {c['delta']:+.4f} " f"[{c['ci95_subject'][0]:+.4f}, {c['ci95_subject'][1]:+.4f}] | {'yes' if c['pass'] else 'no'} |") (B / "summary.md").write_text("\n".join(L) + "\n") print("\n".join(L)) if __name__ == "__main__": main()