File size: 7,519 Bytes
d04bc2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
"""926/D — one-view qualitative grid: chair, guitar, helicopter, elephant x
{ground truth, paired EEG, same-category swap, target-category mean, wrong-category mean}.

Protocol of the existing Fig. 3 columns: sub01, 200k checkpoint, 200 denoising
steps, figure seed 20260716, the same six-object batch, seed reset before every
condition (so all columns share their initial noise); wrong = (c + 1) mod 72.
One view per cell (elev 25, azim 35, the front view of the existing figure),
white background, no shadow / second point layer. All six generated objects are
saved; the four figure rows are fixed in advance (no selection).
"""
import argparse
import json
import sys
from pathlib import Path

import numpy as np

REFS = Path("/home/hubin/workspace/July/brain3d_refs")
BATCH = ["01_airplane_08", "15_chair_08", "27_guitar_08", "29_helicopter_08", "21_elephant_08", "14_cat_08"]
ROWS = ["15_chair_08", "27_guitar_08", "29_helicopter_08", "21_elephant_08"]
CONDS = [("real", "paired EEG", (0.12, 0.35, 0.70)), ("same_category_swap", "same-cat swap", (0.20, 0.55, 0.30)),
         ("category_mean", "target-cat mean", (0.55, 0.25, 0.65)),
         ("wrong_category_mean", "wrong-cat mean", (0.88, 0.48, 0.00))]
ELEV, AZIM = 25, 35


def generate(out, subject, steps, seed):
    import torch
    sys.path.insert(0, str(REFS / "third_party" / "neuro-3D"))
    sys.path.insert(0, str(REFS / "scripts"))
    import evaluate_shape_diffusion_controls as ev
    ev.ROOT, ev.REPO, ev.DATA = REFS, REFS / "third_party" / "neuro-3D", REFS / "data" / "EEG-3D"
    data = ev.DATA
    device = torch.device("cuda")
    ckpt = data / "model/point_generate/shape" / subject / "resumable_200000steps/checkpoint-200000.pth"
    model = ev.EEGTo3DDiffusionModel(
        beta_start=1e-5, beta_end=8e-3, beta_schedule="linear", sub=subject, generate_type="shape",
        retri_pretrain_model=f"{data}/model/retraival/{subject}/{ev.encoder_name(int(subject[3:]))}/",
        point_cloud_model_embed_dim=64, in_channels=1027, out_channels=3)
    model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=False)["model"])
    model.eval().to(device)
    test = ev.AllDataFeatureTwoEEG(f"{data}/", sub_list=[subject], train=False, test_mean=True, aug_data=False,
                                   load_point_cloud=True)
    train = ev.AllDataFeatureTwoEEG(f"{data}/", sub_list=[subject], train=True, aug_data=False, load_point_cloud=False)
    items = [test[i] for i in range(len(test))]
    by_name = {str(it["name"]): it for it in items}
    mdyn = torch.from_numpy(train.eeg_data[0].mean(axis=(1, 2))).float()
    msta = torch.from_numpy(train.eeg_data2[0].mean(axis=(1, 2))).float()
    all_pf = test.color_point_features[:, 0].float().to(device)
    all_vf = test.color_video_features[:, 0].float().to(device)
    sel = [by_name[n] for n in BATCH]
    out.mkdir(parents=True, exist_ok=True)
    for cond, _, _ in CONDS:
        cb = ev.condition_batch(sel, cond, items, mdyn, msta)
        torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
        feats = {"point_features": cb["color_point_fea"].float().to(device),
                 "video_features": cb["color_video_fea"].float().to(device),
                 "point_features_all": all_pf, "video_features_all": all_vf}
        with torch.inference_mode():
            pred, _ = model(cb["point_cloud"].float()[:, :, :3].to(device), cb["eeg_data"].float().to(device),
                            cb["eeg_data2"].float().to(device), mode="sample", shape_c=None, fea_list=feats,
                            labels=cb["cls_label"].to(device), return_sample_every_n_steps=-1,
                            num_inference_steps=steps, disable_tqdm=True)
        pred = pred.float().cpu().numpy()
        for i, n in enumerate(BATCH):
            np.save(out / f"{n}__{cond}.npy", pred[i])
        print(f"D render generated {cond}", flush=True)
    for n in BATCH:
        np.save(out / f"{n}__gt.npy", np.asarray(by_name[n]["point_cloud"])[:, :3])


def norm(x):
    x = np.asarray(x, np.float64)[:, :3]
    x = x - x.mean(0)
    return x / max(np.linalg.norm(x, axis=1).max(), 1e-8)


def chamfer_l1(a, b):
    from scipy.spatial import cKDTree
    return float(cKDTree(b).query(a)[0].mean() + cKDTree(a).query(b)[0].mean())


def panel(ax, pts, rgb):
    phi, th = np.deg2rad(90 - ELEV), np.deg2rad(AZIM)
    cam = np.array([np.sin(phi) * np.cos(th), np.sin(phi) * np.sin(th), np.cos(phi)])
    p = pts[:, [0, 2, 1]]
    depth = p @ cam
    t = ((depth - depth.min()) / max(np.ptp(depth), 1e-8)) ** 0.85
    base = np.array(rgb)
    col = (base * 0.35)[None] * (1 - t[:, None]) + np.clip(base + (1 - base) * 0.55, 0, 1)[None] * t[:, None]
    o = np.argsort(depth)
    ax.scatter(p[o, 0], p[o, 1], p[o, 2], c=col[o], s=0.6, alpha=0.95, linewidths=0, depthshade=False)
    for f in (ax.set_xlim, ax.set_ylim, ax.set_zlim):
        f(-1.0, 1.0)
    ax.set_box_aspect((1, 1, 1)); ax.view_init(elev=ELEV, azim=AZIM); ax.set_axis_off(); ax.set_facecolor("white")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--subject", default="sub01")
    ap.add_argument("--steps", type=int, default=200)
    ap.add_argument("--seed", type=int, default=20260716)
    ap.add_argument("--out", default="/home/hubin/926/results/D")
    ap.add_argument("--skip-generate", action="store_true")
    a = ap.parse_args()
    out = Path(a.out); pcd = out / "qualitative_pointclouds"
    if not a.skip_generate:
        generate(pcd, a.subject, a.steps, a.seed)
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    cols = [("gt", "ground truth", (0.35, 0.35, 0.35))] + CONDS
    fig = plt.figure(figsize=(2.0 * len(cols), 2.0 * len(ROWS)), facecolor="white")
    check = {}
    gts = {n: norm(np.load(pcd / f"{n}__gt.npy")) for n in BATCH}
    for r, n in enumerate(ROWS):
        cat = n.split("_")[1]
        for c, (cond, label, rgb) in enumerate(cols):
            ax = fig.add_subplot(len(ROWS), len(cols), r * len(cols) + c + 1, projection="3d")
            pts = norm(np.load(pcd / f"{n}__{cond}.npy"))
            panel(ax, pts, rgb)
            if r == 0:
                ax.set_title(label, fontsize=9)
            if c == 0:
                ax.text2D(-0.08, 0.5, cat, transform=ax.transAxes, rotation=90, va="center", fontsize=9)
    plt.subplots_adjust(left=0.03, right=0.99, top=0.95, bottom=0.01, wspace=0.0, hspace=0.0)
    fig.savefig(out / "qualitative_oneview.png", dpi=220, facecolor="white")
    fig.savefig(out / "qualitative_oneview.pdf", facecolor="white")
    # non-visual check: distance of every generation to the target GT and to the wrong category's held-out objects
    for n in BATCH:
        c = int(n.split("_")[0]) - 1
        wrong = [k for k in gts if int(k.split("_")[0]) - 1 == (c + 1) % 72]
        check[n] = {}
        for cond, _, _ in CONDS:
            pts = norm(np.load(pcd / f"{n}__{cond}.npy"))
            check[n][cond] = {"to_target_gt": chamfer_l1(pts, gts[n]),
                              "to_paired_generation": chamfer_l1(pts, norm(np.load(pcd / f"{n}__real.npy")))}
    json.dump({"rows": ROWS, "batch": BATCH, "subject": a.subject, "steps": a.steps, "seed": a.seed,
               "view": {"elev": ELEV, "azim": AZIM}, "check_chamfer_l1_pcnorm": check},
              open(out / "qualitative_check.json", "w"), indent=1)
    print(json.dumps({n: {k: round(v["to_target_gt"], 3) for k, v in check[n].items()} for n in ROWS}), flush=True)


if __name__ == "__main__":
    main()