File size: 7,197 Bytes
9b789e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
"""926/D — fMRI-Shape: the same input controls, sets and power as for EEG.

Processed fMRI-Shape (npy_data, as in the repository), public subjects 1-4, the
leakage-safe learned L=128 category decoders (3 seeds, results/fmri_shape_bottleneck_leakage_safe).
No 3D generator exists for fMRI-Shape, so the decoder is classify -> train-only
category medoid, with ShapeNetCore.v2 PC15k point clouds and medoids exactly as in
9.24torun/T2 (1024 points, unit sphere, Chamfer-L2; 101/104 test objects with a point cloud).

Inputs (wrong = (c + 1) mod 13):
  paired              the object's own fMRI sample
  same_category_swap  the next test object of the same category (cyclic within the test list)
  target_mean         mean of the train-split samples of the target category (same subject)
  wrong_mean          same for the wrong category
Each input is normalised like the training data ((x - mean) / std per sample).
"""
import json
import sys
from pathlib import Path

import numpy as np
import torch

REFS = Path("/home/hubin/workspace/July/brain3d_refs")
sys.path.insert(0, str(REFS)); sys.path.insert(0, str(REFS / "scripts"))
import train_fmri_shape_bottleneck as tf  # noqa: E402

tf.ROOT, tf.DATA = REFS, REFS / "data" / "fMRI-Shape"
SUBJECTS = ["sub-0001", "sub-0002", "sub-0003", "sub-0004"]
GEOM = Path("/home/hubin/JAMIETSENG/9.24torun/results/T2_fmir_instance_chamfer/instance_geometry_p1024.npz")
OUT = Path("/home/hubin/926/results/D")
CONDS = ["paired", "same_category_swap", "target_mean", "wrong_mean"]


def load(subject, row):
    c, u = row.split("/", 1)
    v = np.load(tf.DATA / subject / "npy_data" / c / f"{u}.npy").astype(np.float32)
    return v


def norm(v):
    return (v - v.mean()) / max(float(v.std()), 1e-6)


def main():
    from scipy import stats
    z = np.load(GEOM, allow_pickle=True)
    err, valid = z["errors"], z["valid"]
    dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    res = {"per_subject": {}, "conditions": CONDS}
    rows_all = []
    for subj in SUBJECTS:
        test = tf.FMRIShapeDataset(subj, "test")
        train = tf.FMRIShapeDataset(subj, "train")
        cats = test.categories
        y = np.array([test.category_index[r.split("/", 1)[0]] for r in test.rows])
        X = np.stack([norm(load(subj, r)) for r in test.rows])
        means = {}
        for k, c in enumerate(cats):
            rs = [r for r in train.rows if r.startswith(c + "/")]
            means[k] = norm(np.mean([norm(load(subj, r)) for r in rs], 0))
        partner = []
        for i in range(len(y)):
            same = [j for j in range(len(y)) if y[j] == y[i]]
            partner.append(same[(same.index(i) + 1) % len(same)])
        inp = {"paired": X, "same_category_swap": X[partner],
               "target_mean": np.stack([means[int(c)] for c in y]),
               "wrong_mean": np.stack([means[int((c + 1) % len(cats))] for c in y])}
        per_seed = {}
        for seed in (0, 1, 2):
            ck = torch.load(REFS / f"results/fmri_shape_bottleneck_leakage_safe/{subj}_learned_L128_s{seed}/model.pt",
                            map_location="cpu", weights_only=False)
            model = tf.FMRIBottleneck(128, len(cats), "learned").to(dev)
            model.load_state_dict(ck["model"]); model.eval()
            per_seed[seed] = {}
            for cond in CONDS:
                with torch.inference_mode():
                    P = torch.cat([model(torch.from_numpy(inp[cond][i:i + 32]).to(dev)).softmax(-1).cpu()
                                   for i in range(0, len(y), 32)]).double().numpy()
                rank = (P > P[np.arange(len(y)), y][:, None]).sum(1)
                pick = P.argmax(1)
                ch = np.where(valid, err[np.arange(len(y)), pick], np.nan)
                oracle = np.where(valid, err[np.arange(len(y)), y], np.nan)
                per_seed[seed][cond] = {"top1": float((rank < 1).mean()), "top3": float((rank < 3).mean()),
                                        "top5": float((rank < 5).mean()),
                                        "classify_medoid_chamfer": float(np.nanmean(ch)),
                                        "oracle_medoid_chamfer": float(np.nanmean(oracle))}
                for i in range(len(y)):
                    rows_all.append({"subject": subj, "seed": seed, "condition": cond, "object": test.rows[i],
                                     "category": int(y[i]), "decoded": int(pick[i]), "rank": int(rank[i]),
                                     "chamfer_l2": None if not valid[i] else float(ch[i])})
        res["per_subject"][subj] = {c: {k: float(np.mean([per_seed[s][c][k] for s in per_seed])) for k in per_seed[0][c]}
                                    for c in CONDS}
        print(f"fMRI {subj}: " + " | ".join(f"{c} top1={res['per_subject'][subj][c]['top1']:.3f} "
                                              f"ch={res['per_subject'][subj][c]['classify_medoid_chamfer']:.4f}"
                                              for c in CONDS), flush=True)

    deltas = {}
    for cond in CONDS[1:]:
        deltas[cond] = {}
        for k in ("classify_medoid_chamfer", "top1", "top5"):
            d = np.array([res["per_subject"][s][cond][k] - res["per_subject"][s]["paired"][k] for s in SUBJECTS])
            n, m, sd = len(d), float(d.mean()), float(d.std(ddof=1))
            half = stats.t.ppf(0.975, n - 1) * sd / np.sqrt(n)
            deltas[cond][k] = {"delta": m, "sd_subject": sd, "ci95_t": [m - half, m + half],
                               "per_subject": d.tolist(),
                               "worse_subjects": int((d > 0).sum() if k.endswith("chamfer") else (d < 0).sum())}
    res["delta_vs_paired"] = deltas
    sd = deltas["same_category_swap"]["classify_medoid_chamfer"]["sd_subject"]
    grid = np.linspace(0, max(0.02, 6 * sd), 61)

    def power(delta, n):
        df, nc = n - 1, delta / (sd / np.sqrt(n))
        tc = stats.t.ppf(0.975, df)
        return float(stats.nct.sf(tc, df, nc) + stats.nct.cdf(-tc, df, nc))
    res["power_swap"] = {"between_subject_sd": sd, "deltas": grid.tolist(),
                         "power": {str(n): [power(x, n) for x in grid] for n in (4, 8, 16)},
                         "mde_80pct": {str(n): next((float(x) for x in grid if power(x, n) >= 0.8), None) for n in (4, 8, 16)}}
    t2 = json.load(open("/home/hubin/JAMIETSENG/9.24torun/results/T2_fmir_instance_chamfer/results.json"))
    res["sets_from_T2"] = {"K=10": t2["allocations"]["K=10"], "note": "set recall / instance Chamfer of the fMRI set "
                           "decoder (collective posterior, 3 seeds) from 9.24torun/T2"}
    res["n_subjects"] = len(SUBJECTS)
    res["unit"] = "subject (n = 4 public subjects); per-subject values are means over 3 decoder seeds"
    OUT.mkdir(parents=True, exist_ok=True)
    json.dump(res, open(OUT / "fmri.json", "w"), indent=1, default=float)
    import csv
    with open(OUT / "fmri_per_object.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows_all[0])); w.writeheader(); w.writerows(rows_all)
    print(json.dumps({c: {k: round(v["delta"], 4) for k, v in deltas[c].items()} for c in deltas}), flush=True)


if __name__ == "__main__":
    main()