"""926/A — target geometry of fixed-budget hypothesis sets. Members are train category medoids (results/p0_category_geometry, objects 00-07), never new samples. Geometry follows the existing category-anchor evaluation (scripts/p0_prepare_anchor_errors.py): 512 points by linspace, centred, unit sphere, Chamfer-L2 = sum of mean squared nearest distances. Fill geometry is the existing train-medoid matrix results/geometry_risk/category_medoid_chamfer.npy. Per object and set S we report recall true category in S train_medoid min_{s in S} D[true, s] (medoid-to-medoid, the quantity the fill optimises) target_* best-of-set Chamfer-L2 / F@0.1 / EMD-256 of the held-out target vs the set medoids proto_* same, but each set member is represented by a held-out geometry prototype: the medoid of the other 7 train objects of that category (never the fill medoid) Main endpoint: per-subject mean target Chamfer of FL 8+2 minus 10+0 (top-10), 95% CI by resampling subjects. """ import argparse import csv import json import os import sys from pathlib import Path import numpy as np import torch from scipy.optimize import linear_sum_assignment from scipy.spatial import distance_matrix REFS = Path("/home/hubin/workspace/July/brain3d_refs") CACHE = Path("/home/hubin/workspace/code/cache") sys.path.insert(0, str(REFS)) sys.path.insert(0, str(REFS / "scripts")) from gaussian_mvp.catalog import point_cloud_stem # noqa: E402 PC = REFS / "data" / "EEG-3D" / "point_cloud_simple" N_POINTS = 512 KS = [int(k) for k in os.environ["A_KS"].split(",")] if os.environ.get("A_KS") else [1, 3, 5, 10, 20] M_DEP = ["fl", "random", "kcenter", "farthest", "dpp", "fl_calibrated", "learned_fl"] # ----------------------------------------------------------------------------- geometry def normalize(p): p = p - p.mean(0, keepdims=True) return p / max(float(np.linalg.norm(p, axis=1).max()), 1e-8) def load_obj(name, n=N_POINTS): p = np.load(PC / f"{point_cloud_stem(name)}.npy")[:, :3] return normalize(p[np.linspace(0, len(p) - 1, n).round().astype(np.int64)].astype(np.float32)) def chamfer_matrix(A, B): """A [n, P, 3], B [m, P, 3] -> Chamfer-L2 [n, m] (anchor convention), F@0.1 [n, m].""" A, B = torch.from_numpy(np.asarray(A)), torch.from_numpy(np.asarray(B)) ch, fs = np.zeros((len(A), len(B))), np.zeros((len(A), len(B))) for i in range(len(A)): d = torch.cdist(A[i].unsqueeze(0).expand(len(B), -1, -1), B) # [m, P, P]; A rows = target t2p, p2t = d.min(2).values, d.min(1).values ch[i] = (t2p.square().mean(1) + p2t.square().mean(1)).numpy() prec, rec = (p2t < 0.1).float().mean(1), (t2p < 0.1).float().mean(1) fs[i] = torch.where(prec + rec > 0, 2 * prec * rec / (prec + rec + 1e-12), torch.zeros_like(prec)).numpy() return ch, fs def emd_matrix(A, B): ia, ib = np.linspace(0, A.shape[1] - 1, 256).astype(int), np.linspace(0, B.shape[1] - 1, 256).astype(int) out = np.zeros((len(A), len(B))) for i in range(len(A)): for j in range(len(B)): c = distance_matrix(B[j][ib], A[i][ia]) r, cc = linear_sum_assignment(c) out[i, j] = c[r, cc].mean() return out def build_geometry(work): p = work / "geometry.npz" if p.exists(): z = np.load(p, allow_pickle=True) return {k: z[k] for k in z.files} anchor = torch.load(REFS / "results/p0_anchor_validation_safe/anchor_errors.pt", map_location="cpu", weights_only=False) names = list(anchor["test_names"]) target = np.stack([load_obj(n) for n in names]) med, proto, med05, info = [], [], [], {"medoid": [], "proto": [], "medoid05": []} for c in range(72): st = torch.load(REFS / f"results/p0_category_geometry/category_{c:02d}.pt", map_location="cpu", weights_only=False) m = st["medoid"].float().numpy() med.append(m[np.linspace(0, len(m) - 1, N_POINTS).round().astype(np.int64)]) tn, pw = list(st["train_names"]), st["pairwise"].double().numpy() k = tn.index(st["medoid_name"]) keep = [j for j in range(len(tn)) if j != k] pk = keep[int(pw[np.ix_(keep, keep)].sum(1).argmin())] proto.append(load_obj(tn[pk])) t05 = [n for n in tn if int(n.rsplit("_", 1)[1]) <= 5] pts = np.stack([load_obj(n) for n in t05]) ch05, _ = chamfer_matrix(pts, pts) k05 = int(ch05.sum(1).argmin()) med05.append(pts[k05]) info["medoid"].append(st["medoid_name"]); info["proto"].append(tn[pk]); info["medoid05"].append(t05[k05]) med, proto, med05 = np.stack(med), np.stack(proto), np.stack(med05) g = {"names": np.array(names), "true": anchor["true_category"].long().numpy()} for tag, M in (("target", med), ("proto", proto), ("m05", med05)): ch, fs = chamfer_matrix(target, M) g[f"{tag}_ch"], g[f"{tag}_f"] = ch, fs g[f"{tag}_emd"] = emd_matrix(target, M) print(f"A geometry {tag} done", flush=True) g["D05"] = chamfer_matrix(med05, med05)[0] np.fill_diagonal(g["D05"], 0.0) g["anchor_ch"] = anchor["category_errors"].double().numpy() g["info"] = np.array(json.dumps(info)) np.savez(p, **g) return g # ----------------------------------------------------------------------------- set constructions def topk(q, k): return list(np.argsort(-q)[:k]) def fill_fl(q, D, K, m, w=None): w = q if w is None else w S = topk(q, m) cur = D[:, S].min(1) if S else np.full(len(q), np.inf) while len(S) < K: cand = np.setdiff1d(np.arange(len(q)), S) risk = (w[:, None] * np.minimum(cur[:, None], D[:, cand])).sum(0) b = int(cand[np.argmin(risk)]) S.append(b); cur = np.minimum(cur, D[:, b]) return S def fill_kcenter(q, D, K, m): S = topk(q, m) cur = D[:, S].min(1) if S else np.full(len(q), np.inf) while len(S) < K: cand = np.setdiff1d(np.arange(len(q)), S) risk = (q[:, None] * np.minimum(cur[:, None], D[:, cand])).max(0) b = int(cand[np.argmin(risk)]) S.append(b); cur = np.minimum(cur, D[:, b]) return S def fill_farthest(q, D, K, m): S = topk(q, max(m, 1)) if K else [] S = S[:K] while len(S) < K: cand = np.setdiff1d(np.arange(len(q)), S) b = int(cand[np.argmax(D[np.ix_(cand, S)].min(1))]) S.append(b) return S def fill_random(q, K, m, rng): S = topk(q, m) return S + list(rng.choice(np.setdiff1d(np.arange(len(q)), S), K - m, replace=False)) def fill_dpp(q, Ssim, K, m): """Greedy MAP of L = diag(sqrt q) Ssim diag(sqrt q), with the top-m categories forced first.""" n = len(q) qq = np.sqrt(q) L = qq[:, None] * Ssim * qq[None, :] forced = topk(q, m) cis, d2 = np.zeros((K, n)), np.diag(L).copy() S = [] for t in range(K): if t < len(forced): j = forced[t] else: s = d2.copy(); s[S] = -np.inf j = int(np.argmax(s)) if s[j] <= 1e-12: rest = [c for c in np.argsort(-q) if c not in S] S += rest[:K - len(S)] return S S.append(j) if t == K - 1: break if d2[j] <= 1e-12: continue dj = np.sqrt(d2[j]) e = (L[j] - cis[:t, j] @ cis[:t]) / dj cis[t] = e d2 = d2 - e ** 2 return S def fit_temperature(p, y): lp = np.log(np.clip(p, 1e-12, 1)) best, bt = np.inf, 1.0 for T in np.exp(np.linspace(np.log(0.05), np.log(20), 400)): z = lp / T; z -= z.max(1, keepdims=True) nll = -(z[np.arange(len(y)), y] - np.log(np.exp(z).sum(1))).mean() if nll < best: best, bt = nll, T return bt def temper(p, T): z = np.log(np.clip(p, 1e-12, 1)) / T z -= z.max(-1, keepdims=True) e = np.exp(z) return e / e.sum(-1, keepdims=True) def learned_features(Q, D): """Per (object, candidate) features from the posterior only.""" lq = np.log(np.clip(Q, 1e-12, 1)) rank = np.argsort(np.argsort(-Q, 1), 1) exp_d = Q @ D # expected train-medoid distance of c under q return np.stack([lq - lq.mean(1, keepdims=True), np.log1p(rank), exp_d - exp_d.mean(1, keepdims=True)], -1) def fit_learned(Qc, yc, D): from sklearn.linear_model import LogisticRegression X = learned_features(Qc, D).reshape(-1, 3) Y = (np.arange(72)[None, :] == yc[:, None]).reshape(-1) return LogisticRegression(C=1.0, max_iter=2000, class_weight="balanced").fit(X, Y) # ----------------------------------------------------------------------------- evaluation def evaluate(sets, g, D, true): """sets: list (per object) of index lists -> dict of per-object arrays.""" r = {"recall": np.array([t in s for s, t in zip(sets, true)], float), "size": np.array([len(s) for s in sets], float), "train_medoid": np.array([D[t, s].min() for s, t in zip(sets, true)])} for tag in ("target", "proto"): ch, f, e = g[f"{tag}_ch"], g[f"{tag}_f"], g[f"{tag}_emd"] r[f"{tag}_chamfer"] = np.array([ch[i, s].min() for i, s in enumerate(sets)]) r[f"{tag}_f01"] = np.array([f[i, s].max() for i, s in enumerate(sets)]) r[f"{tag}_emd"] = np.array([e[i, s].min() for i, s in enumerate(sets)]) return r def subject_ci(x, n_boot, rng): """x [n_subjects] -> mean and 95% CI by resampling subjects.""" idx = rng.integers(0, len(x), (n_boot, len(x))) d = x[idx].mean(1) return float(x.mean()), [float(np.quantile(d, 0.025)), float(np.quantile(d, 0.975))] def reproduce_existing(g, D, out_dir): """Re-run the existing collective sweep and compare with results/geometry_risk_sweep_v2_validation_safe_full.""" ens = json.load(open(REFS / "results/p0_anchor_validation_safe/ensemble12.json")) Q = np.array([r["category_probabilities"] for r in ens["per_sample"]], float) true = np.array([r["true_category"] for r in ens["per_sample"]]) E = g["anchor_ch"] rows, worst = [], 0.0 for f in sorted((REFS / "results/geometry_risk_sweep_v2_validation_safe_full").glob("K*_M*.json")): ref = json.load(open(f)) K, M = ref["set_size"], ref["mandatory_probability_top"] P = [topk(q, K) for q in Q] R = [fill_fl(q, D, K, M) for q in Q] mine = {"topk_recall": np.mean([t in s for s, t in zip(P, true)]), "topk_chamfer": np.mean([E[i, s].min() for i, s in enumerate(P)]), "set_recall": np.mean([t in s for s, t in zip(R, true)]), "set_chamfer": np.mean([E[i, s].min() for i, s in enumerate(R)])} theirs = {"topk_recall": ref["probability_topk"]["category_recall"], "topk_chamfer": ref["probability_topk"]["mean_chamfer"], "set_recall": ref["geometry_risk_set"]["category_recall"], "set_chamfer": ref["geometry_risk_set"]["mean_chamfer"]} diff = max(abs(mine[k] - theirs[k]) for k in mine) same_sets = all(sorted(a) == sorted(b) for a, b in zip(R, ref["geometry_risk_sets"])) worst = max(worst, diff) rows.append({"K": K, "M": M, **{f"mine_{k}": v for k, v in mine.items()}, **{f"existing_{k}": v for k, v in theirs.items()}, "max_abs_diff": diff, "same_sets": same_sets}) anchor_diff = float(np.abs(g["target_ch"] - g["anchor_ch"]).max()) rep = {"cells": rows, "max_abs_diff": worst, "all_sets_identical": all(r["same_sets"] for r in rows), "target_matrix_vs_anchor_errors_max_abs_diff": anchor_diff, "ok": bool(worst < 1e-5 and all(r["same_sets"] for r in rows) and anchor_diff < 1e-4)} json.dump(rep, open(out_dir / "reproduction.json", "w"), indent=1, default=float) return rep def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default="/home/hubin/926/results/A") ap.add_argument("--seed", type=int, default=20260722) ap.add_argument("--posterior-seed", type=int, default=0) ap.add_argument("--random-draws", type=int, default=50) ap.add_argument("--bootstrap", type=int, default=10000) a = ap.parse_args() out = Path(a.out); out.mkdir(parents=True, exist_ok=True) work = Path("/home/hubin/926/cache"); work.mkdir(parents=True, exist_ok=True) g = build_geometry(work) D = np.load(REFS / "results/geometry_risk/category_medoid_chamfer.npy").astype(np.float64) rep = reproduce_existing(g, D, out) print(f"A reproduction: max diff {rep['max_abs_diff']:.2e}, sets identical {rep['all_sets_identical']}, " f"target-vs-anchor {rep['target_matrix_vs_anchor_errors_max_abs_diff']:.2e} -> ok={rep['ok']}", flush=True) if not rep["ok"]: (out / "BLOCKED.md").write_text( "# A blocked\n\nThe re-implemented train-medoid set scores do not match the existing sweep " "(`results/geometry_risk_sweep_v2_validation_safe_full`). See `reproduction.json`.\n") raise SystemExit("A blocked: reproduction failed") z = np.load(CACHE / f"posteriors_seed{a.posterior_seed}.npz") Qt, Qc, yt, yc = z["test"].astype(np.float64), z["calib"].astype(np.float64), z["test_target"], z["calib_target"] true = g["true"] assert np.array_equal(yt, true), "posterior test order differs from anchor order" rng = np.random.default_rng(a.seed) Ssim = np.exp(-D / np.median(D[np.triu_indices(72, 1)])) w_, v_ = np.linalg.eigh(Ssim) Ssim = (v_ * np.clip(w_, 0, None)) @ v_.T + 1e-6 * np.eye(72) learned = fit_learned(Qc.reshape(-1, 72), np.tile(yc, 12), D) uniform = np.full(72, 1.0 / 72) import pickle pkl = work / f"a_per_obj_seed{a.posterior_seed}_K{'-'.join(map(str, KS))}_r{a.random_draws}.pkl" per_obj = pickle.load(open(pkl, "rb")) if pkl.exists() else {} # (method, K, m) -> {metric: [12, 144]} def add(key, sets_per_subject): ev = [evaluate(s, g, D, true) for s in sets_per_subject] per_obj[key] = {k: np.stack([e[k] for e in ev]) for k in ev[0]} for K in ([] if per_obj else KS): for m in range(K + 1): add(("fl", K, m), [[fill_fl(q, D, K, m) for q in Qt[s]] for s in range(12)]) add(("kcenter", K, m), [[fill_kcenter(q, D, K, m) for q in Qt[s]] for s in range(12)]) add(("farthest", K, m), [[fill_farthest(q, D, K, m) for q in Qt[s]] for s in range(12)]) add(("dpp", K, m), [[fill_dpp(q, Ssim, K, m) for q in Qt[s]] for s in range(12)]) draws = [[[fill_random(q, K, m, rng) for q in Qt[s]] for s in range(12)] for _ in range(a.random_draws)] evs = [[evaluate(d[s], g, D, true) for s in range(12)] for d in draws] per_obj[("random", K, m)] = {k: np.mean([np.stack([e[s][k] for s in range(12)]) for e in evs], 0) for k in evs[0][0]} print(f"A K={K} base constructions done", flush=True) temps = [fit_temperature(Qc[s], yc) for s in range(12)] Qcal = np.stack([temper(Qt[s], temps[s]) for s in range(12)]) for m in range(K + 1): add(("fl_calibrated", K, m), [[fill_fl(q, D, K, m) for q in Qcal[s]] for s in range(12)]) F = learned_features(Qt.reshape(-1, 72), D).reshape(12, 144, 72, 3) score = learned.decision_function(F.reshape(-1, 3)).reshape(12, 144, 72) for m in range(K + 1): add(("learned_fl", K, m), [[fill_fl(sc, D, K, m, w=q) for sc, q in zip(score[s], Qt[s])] for s in range(12)]) # entropy-driven slot allocation: more geometry slots for flatter posteriors, mean r ~ 0.2 K H = -(Qt * np.log(np.clip(Qt, 1e-12, 1))).sum(-1) rbar = max(1, round(0.2 * K)) if K > 1 else 0 sets = [] for s in range(12): pct = np.argsort(np.argsort(H[s])) / (len(H[s]) - 1) r = np.clip(np.round(pct * 2 * rbar), 0, K - 1 if K > 1 else 0).astype(int) sets.append([fill_fl(q, D, K, K - ri) for q, ri in zip(Qt[s], r)]) add(("entropy_alloc", K, -1), sets) add(("oracle_category_fl", K, -1), [[[int(t)] + [c for c in fill_fl(np.where(np.arange(72) == t, 1.0, q), D, K, 1) if c != t][:K - 1] for q, t in zip(Qt[s], true)] for s in range(12)]) add(("global_prior", K, -1), [[fill_fl(uniform, D, K, 0)] * 144 for _ in range(12)]) # split-conformal (LAC) on the calibration objects, alpha chosen so the mean calibration size ~ K sets, alphas = [], [] for s in range(12): sc_cal = 1 - Qc[s][np.arange(144), yc] best = None for alpha in np.linspace(0.01, 0.99, 197): qh = np.quantile(sc_cal, min(1.0, np.ceil((145) * (1 - alpha)) / 144), method="higher") size = ((1 - Qc[s]) <= qh).sum(1).mean() if best is None or abs(size - K) < abs(best[1] - K): best = (alpha, size, qh) alphas.append(float(best[0])) sets.append([list(np.flatnonzero((1 - q) <= best[2])) or topk(q, 1) for q in Qt[s]]) add(("conformal_size_matched", K, -1), sets) per_obj[("conformal_size_matched", K, -1)]["alpha"] = np.array(alphas) print(f"A K={K} all constructions done", flush=True) pickle.dump(per_obj, open(pkl, "wb")) # ------------------------------------------------------------------ tables metrics = ["recall", "size", "train_medoid", "target_chamfer", "target_f01", "target_emd", "proto_chamfer", "proto_f01", "proto_emd"] rows = [] for (meth, K, m), v in per_obj.items(): ref = per_obj[("fl", K, K)] row = {"method": meth, "K": K, "m": m if m >= 0 else "", "slots_geometry": K - m if m >= 0 else ""} for k in metrics: row[k] = float(v[k].mean()) for k in ("target_chamfer", "target_f01", "target_emd", "recall"): d = v[k].mean(1) - ref[k].mean(1) mu, ci = subject_ci(d, a.bootstrap, rng) row[f"delta_{k}_vs_topK"], row[f"delta_{k}_ci_lo"], row[f"delta_{k}_ci_hi"] = mu, ci[0], ci[1] rows.append(row) with open(out / "sweep.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows) main_new, main_ref = per_obj[("fl", 10, 8)], per_obj[("fl", 10, 10)] ps = [] for s in range(12): ps.append({"subject": f"sub{s + 1:02d}", **{f"top10_{k}": float(main_ref[k][s].mean()) for k in metrics}, **{f"fl8p2_{k}": float(main_new[k][s].mean()) for k in metrics}}) with open(out / "per_subject.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=list(ps[0])); w.writeheader(); w.writerows(ps) pc = [] for c in range(72): sel = true == c pc.append({"category": c, "name": str(g["names"][sel][0]).rsplit("_", 1)[0], **{f"top10_{k}": float(main_ref[k][:, sel].mean()) for k in metrics}, **{f"fl8p2_{k}": float(main_new[k][:, sel].mean()) for k in metrics}}) with open(out / "per_category.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=list(pc[0])); w.writeheader(); w.writerows(pc) with open(out / "per_object.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["subject", "object", "category", "set", *metrics]) for s in range(12): for i in range(144): for tag, v in (("top10", main_ref), ("fl8p2", main_new)): w.writerow([f"sub{s + 1:02d}", str(g["names"][i]), int(true[i]), tag, *[float(v[k][s, i]) for k in metrics]]) def contrast(new, ref): o = {} for k in metrics: d = new[k].mean(1) - ref[k].mean(1) mu, ci = subject_ci(d, a.bootstrap, rng) o[k] = {"new": float(new[k].mean()), "ref": float(ref[k].mean()), "delta": mu, "ci95_subject": ci, "subjects_improved": int((d < 0).sum() if k not in ("recall", "target_f01", "proto_f01") else (d > 0).sum())} return o primary = contrast(main_new, main_ref) side = {} for K in (3, 5): for m in range(K): c = contrast(per_obj[("fl", K, m)], per_obj[("fl", K, K)]) side[f"K={K},{m}+{K - m}"] = c side_ok = [k for k, c in side.items() if c["target_chamfer"]["delta"] < 0 and c["target_chamfer"]["ci95_subject"][1] < 0 and c["recall"]["delta"] >= -0.01] # robustness: medoids from objects 00-05 only (fill and evaluation) g05 = dict(g); g05["target_ch"], g05["target_f"], g05["target_emd"] = g["m05_ch"], g["m05_f"], g["m05_emd"] r05 = {} for K, m in ((10, 10), (10, 8)): ev = [evaluate([fill_fl(q, g["D05"], K, m) for q in Qt[s]], g05, g["D05"], true) for s in range(12)] r05[f"{m}+{K - m}"] = {k: np.stack([e[k] for e in ev]) for k in ev[0]} robust05 = contrast(r05["8+2"], r05["10+0"]) p = primary passed = bool(p["target_chamfer"]["delta"] < 0 and p["target_chamfer"]["ci95_subject"][1] < 0 and p["recall"]["delta"] >= 0 and p["target_f01"]["delta"] > 0 and p["target_emd"]["delta"] < 0 and len(side_ok) > 0) res = {"experiment": "926_A_target_geometry_sets", "posterior": f"validation-safe per-subject encoders, seed " f"{a.posterior_seed} (code/cache/posteriors_seed{a.posterior_seed}.npz); 12 subjects x 144 held-out objects", "reproduction": {k: v for k, v in rep.items() if k != "cells"}, "primary_endpoint": {"contrast": "FL 8+2 minus top-10 (10+0), best-of-set vs held-out target", "statistics_unit": "subject (bootstrap over 12 subjects, 10000)", **p}, "secondary_K3_K5_cells_same_direction_significant_recall_drop_le_1pp": side_ok, "secondary_K3_K5": side, "robustness_medoids_objects_00_05": robust05, "decision": "keep" if passed else "drop", "geometry": {"points": N_POINTS, "normalization": "centred, unit sphere", "chamfer": "Chamfer-L2 (squared)", "f_threshold": 0.1, "emd_points": 256, "medoids": "results/p0_category_geometry (train objects 00-07)", "prototype": "medoid of the other 7 train objects of the category", "fill_distance": "results/geometry_risk/category_medoid_chamfer.npy"}, "random_draws": a.random_draws, "bootstrap": a.bootstrap, "seed": a.seed, "conformal_alpha_per_K": {str(K): per_obj[("conformal_size_matched", K, -1)]["alpha"].tolist() for K in KS}} json.dump(res, open(out / "results.json", "w"), indent=1, default=float) print(json.dumps({"decision": res["decision"], "primary": {k: p[k] for k in ("recall", "target_chamfer", "target_f01", "target_emd")}}, default=float), flush=True) if __name__ == "__main__": main()