926 / code /d_stats.py
jamie33's picture
Restore root files
d04bc2d verified
Raw History Blame Contribute Delete
9.33 kB
"""926/D — statistics on existing data (no new subjects).
primary A main endpoint: FL 8+2 minus 10+0 best-of-set Chamfer-L2 to the held-out target,
crossed random effects (subject, object), tested once.
swap TOST equivalence of same-category swap vs paired EEG, bound +-0.0043 Chamfer-L2 (pre-set),
subject as unit. Primary swap source: the existing 3-seed Gaussian-head benchmark
(results/benchmark_causal_3seed_summary.json); secondary: ToDo2/E1 Gaussian head, 926/B diffusion.
power one-sample t (two-sided, alpha 0.05) and TOST power at n = 12, 24, 48 from the observed
between-subject SD of the swap deltas.
All B / C tests listed here are secondary.
"""
import json
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import stats
REFS = Path("/home/hubin/workspace/July/brain3d_refs")
OUT = Path("/home/hubin/926/results/D")
BOUND = 0.0043
NS = [12, 24, 48]
def tost(x, bound, alpha=0.05):
n, m, sd = len(x), float(np.mean(x)), float(np.std(x, ddof=1))
se = sd / np.sqrt(n)
t_lo, t_hi = (m + bound) / se, (m - bound) / se
p_lo, p_hi = 1 - stats.t.cdf(t_lo, n - 1), stats.t.cdf(t_hi, n - 1)
ci90 = [m - stats.t.ppf(1 - alpha, n - 1) * se, m + stats.t.ppf(1 - alpha, n - 1) * se]
return {"n": n, "mean": m, "sd": sd, "se": se, "p_lower": float(p_lo), "p_upper": float(p_hi),
"p_tost": float(max(p_lo, p_hi)), "ci90": ci90, "equivalent": bool(max(p_lo, p_hi) < alpha),
"t_test_p_two_sided": float(2 * stats.t.sf(abs(m / se), n - 1)),
"smallest_bound_equivalent": float(max(abs(ci90[0]), abs(ci90[1])))}
def power_t(delta, sd, n, alpha=0.05):
df, nc = n - 1, delta / (sd / np.sqrt(n))
tc = stats.t.ppf(1 - alpha / 2, df)
return float(stats.nct.sf(tc, df, nc) + stats.nct.cdf(-tc, df, nc))
def power_tost(delta, sd, n, bound, alpha=0.05, sims=20000, seed=0):
rng = np.random.default_rng(seed)
x = rng.normal(delta, sd, (sims, n))
m, se = x.mean(1), x.std(1, ddof=1) / np.sqrt(n)
tc = stats.t.ppf(1 - alpha, n - 1)
return float(((m - tc * se > -bound) & (m + tc * se < bound)).mean())
def mixed(df, value):
import statsmodels.formula.api as smf
scale = 1000.0 # fit on milli-units; raw Chamfer deltas (~1e-3) leave the optimiser on the boundary
df = df.assign(g=1, _y=df[value] * scale)
md = smf.mixedlm("_y ~ 1", df, groups="g",
vc_formula={"subject": "0 + C(subject)", "object": "0 + C(object)"}).fit(reml=True, method="lbfgs")
est, se = float(md.fe_params["Intercept"]) / scale, float(md.bse_fe["Intercept"]) / scale
vc = dict(zip(md.model.exog_vc.names, [float(v) / scale ** 2 for v in md.vcomp]))
return {"estimate": est, "se": se, "ci95": [est - 1.96 * se, est + 1.96 * se],
"p": float(2 * stats.norm.sf(abs(est / se))), "variance_components": vc,
"residual_variance": float(md.scale) / scale ** 2, "n_obs": int(len(df)), "converged": bool(md.converged)}
def subject_boot(x, n=10000, seed=0):
rng = np.random.default_rng(seed)
d = x[rng.integers(0, len(x), (n, len(x)))].mean(1)
return [float(np.quantile(d, 0.025)), float(np.quantile(d, 0.975))]
def main():
OUT.mkdir(parents=True, exist_ok=True)
res = {"primary": {}, "swap_tost": {}, "power": {}, "secondary": {}}
# ---------------- primary (A)
po = pd.read_csv("/home/hubin/926/results/A/per_object.csv")
wide = po.pivot_table(index=["subject", "object"], columns="set", values="target_chamfer").reset_index()
wide["delta"] = wide["fl8p2"] - wide["top10"]
subj = wide.groupby("subject")["delta"].mean()
res["primary"] = {"contrast": "A: FL 8+2 minus 10+0, best-of-set Chamfer-L2 to held-out target",
"subject_mean": float(subj.mean()), "subject_ci95_bootstrap": subject_boot(subj.values),
"subjects_improved": int((subj < 0).sum()), "n_subjects": int(len(subj)),
"mixed_effects_crossed_subject_object": mixed(wide, "delta"),
"per_subject_delta": subj.to_dict()}
# ---------------- swap TOST
bench = json.load(open(REFS / "results/benchmark_causal_3seed_summary.json"))["paired_delta"]
sw = bench["within_category_swap"]
subs = sorted(sw)
per_sub = np.array([np.mean([np.mean(sw[s][k]) for k in sw[s]]) for s in subs])
res["swap_tost"]["gaussian_head_v3_3seed (primary swap source)"] = {**tost(per_sub, BOUND),
"per_subject": dict(zip(subs, per_sub.tolist()))}
rows = [{"subject": s, "object": i, "seed": k, "delta": v} for s in subs for k in sw[s] for i, v in enumerate(sw[s][k])]
res["swap_tost"]["gaussian_head_v3_3seed (primary swap source)"]["mixed_effects"] = mixed(
pd.DataFrame(rows).groupby(["subject", "object"], as_index=False)["delta"].mean(), "delta")
e1 = json.load(open("/home/hubin/JAMIETSENG/ToDo2/results/E1_cross_generator/results.json"))["per_object_error"]
d_e1 = (np.array(e1["same_cat_swap"]) - np.array(e1["paired"])).mean(1)
res["swap_tost"]["gaussian_head_v3_E1 (secondary)"] = tost(d_e1, BOUND)
bdir = Path("/home/hubin/926/results/B/per_subject")
bfiles = sorted(bdir.glob("sub*.json"))
if bfiles:
brows = pd.DataFrame([r for f in bfiles for r in json.load(open(f))["rows"]])
piv = brows.pivot_table(index=["subject", "name"], columns="condition", values="chamfer_l2")
if {"paired_4avg", "same_category_swap"} <= set(piv.columns):
d = (piv["same_category_swap"] - piv["paired_4avg"]).dropna().groupby("subject").mean()
if len(d) >= 3:
res["swap_tost"][f"diffusion_200k_926B (secondary, {len(d)} subjects)"] = tost(d.values, BOUND)
# ---------------- power
sd = res["swap_tost"]["gaussian_head_v3_3seed (primary swap source)"]["sd"]
deltas = np.linspace(0, 0.012, 49)
curves = {str(n): [power_t(x, sd, n) for x in deltas] for n in NS}
mde = {}
for n in NS:
p = np.array(curves[str(n)])
mde[str(n)] = float(deltas[np.argmax(p >= 0.8)]) if (p >= 0.8).any() else None
res["power"] = {"between_subject_sd": sd, "source": "per-subject swap deltas, 3-seed Gaussian-head benchmark",
"deltas": deltas.tolist(), "power_t_two_sided": curves, "mde_80pct": mde,
"tost_power_at_true_delta_0": {str(n): power_tost(0.0, sd, n, BOUND) for n in NS},
"tost_power_at_observed_mean": {str(n): power_tost(float(per_sub.mean()), sd, n, BOUND) for n in NS}}
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 3.4))
for n in NS:
ax.plot(deltas, curves[str(n)], label=f"n = {n}")
ax.axhline(0.8, color="grey", lw=0.8, ls="--"); ax.axvline(BOUND, color="grey", lw=0.8, ls=":")
ax.set_xlabel("true swap effect (Chamfer-L2)"); ax.set_ylabel("power (two-sided t, α = 0.05)")
ax.set_title(f"subject SD = {sd:.4f}", fontsize=9); ax.legend(frameon=False, fontsize=8)
fig.tight_layout(); fig.savefig(OUT / "power_curve.png", dpi=200)
# ---------------- subject-level effect plot
effects = {"A 8+2 − 10+0 (target Chamfer)": subj.values}
effects["swap − paired (Gaussian head, 3 seeds)"] = per_sub
if bfiles and {"target_within", "wrong_within", "paired_4avg"} <= set(piv.columns):
for c, lab in (("same_category_swap", "swap − paired (diffusion)"), ("target_within", "target mean − paired (diffusion)"),
("wrong_within", "wrong mean − paired (diffusion)")):
if c in piv.columns:
effects[lab] = (piv[c] - piv["paired_4avg"]).dropna().groupby("subject").mean().values
fig, axes = plt.subplots(1, len(effects), figsize=(2.6 * len(effects), 3.2), sharey=False)
for ax, (lab, v) in zip(np.atleast_1d(axes), effects.items()):
ax.scatter(np.zeros(len(v)) + np.random.default_rng(0).uniform(-0.08, 0.08, len(v)), v, s=14, color="#1f4e99")
lo, hi = subject_boot(np.asarray(v))
ax.errorbar([0.3], [np.mean(v)], yerr=[[np.mean(v) - lo], [hi - np.mean(v)]], fmt="o", color="black", capsize=3)
ax.axhline(0, color="grey", lw=0.8); ax.set_xticks([]); ax.set_title(lab, fontsize=8)
fig.tight_layout(); fig.savefig(OUT / "subject_effects.png", dpi=200)
res["subject_effects"] = {k: {"per_subject": list(map(float, v)), "mean": float(np.mean(v)),
"ci95_subject": subject_boot(np.asarray(v))} for k, v in effects.items()}
res["secondary"]["note"] = ("All B (input controls) and C (decoders, readouts) tests are secondary; see "
"B/results.json and C/results.json. The primary endpoint is tested once, above.")
json.dump(res, open(OUT / "stats.json", "w"), indent=1, default=float)
print(json.dumps({"primary": {k: res["primary"][k] for k in ("subject_mean", "subject_ci95_bootstrap")},
"mixed": res["primary"]["mixed_effects_crossed_subject_object"]["ci95"],
"tost": {k: (v["mean"], v["p_tost"], v["equivalent"]) for k, v in res["swap_tost"].items()},
"mde": mde}, default=float))
if __name__ == "__main__":
main()