File size: 4,728 Bytes
7c61ee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Identification metric: is generated shape i closer (Chamfer, best of the 16 eval orientations) to its own GT than
to the GT of another test object? Pooled over ordered pairs, so any output that is a pure function of the category
scores exactly 50% on the within-category variant."""
import os
import sys
import glob
import json
import argparse
from multiprocessing import Pool

import numpy as np
import torch
import trimesh

from eval_shape import N_POINTS, pc_norm, CANDIDATES

GT_ROOT = "/home/hubin/data/ShapeNetCore.v2.PC15k/ShapeNetCore.v2.PC15k"
O = "/home/hubin/trellis_work/outputs"


def sample(args):
    path, seed = args
    mesh = trimesh.load(path, force="mesh")
    return pc_norm(trimesh.sample.sample_surface(mesh, N_POINTS, seed=seed)[0].astype(np.float64)).astype(np.float32)


@torch.no_grad()
def cd_matrix(gen, gt):
    """D[i, j] = min over orientations of Chamfer(gen_i rotated, gt_j)."""
    rots = torch.tensor(np.stack([R for _, _, R in CANDIDATES]), dtype=torch.float32, device="cuda")
    gen = torch.from_numpy(gen).cuda()
    gt = torch.from_numpy(gt).cuda()
    out = torch.empty(len(gen), len(gt), device="cuda")
    for i in range(len(gen)):
        g = torch.einsum("pc,rdc->rpd", gen[i], rots)
        for j in range(len(gt)):
            d = torch.cdist(g, gt[j][None].expand(len(rots), -1, -1)).square()
            out[i, j] = (d.min(2).values.mean(1) + d.min(1).values.mean(1)).min()
    return out.cpu().numpy()


def pairwise_acc(D, mask):
    diag = np.diag(D)[:, None]
    win = (diag < D).astype(np.float64) + 0.5 * (diag == D)
    return float(win[mask].mean()), [float(win[i][mask[i]].mean()) if mask[i].any() else float("nan")
                                     for i in range(len(D))]


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--methods", nargs="*", help="name=mesh_dir pairs; default: all pack_hf VARIANTS")
    p.add_argument("--test_list", default="/home/hubin/data/fMRI-Shape/annotations/core_test_list.txt")
    p.add_argument("--out_dir", default=f"{O}/ident")
    p.add_argument("--seed", type=int, default=0)
    args = p.parse_args()

    if args.methods:
        methods = [m.split("=", 1) for m in args.methods]
    else:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "mapper"))
        from pack_hf import VARIANTS
        methods = [(n, f"{O}/{src}/meshes") for n, src, *_ in VARIANTS]
    gt_paths = {os.path.basename(q)[:-4]: q for q in glob.glob(f"{GT_ROOT}/*/_/*/*.npy")}
    ids = [l.strip() for l in open(args.test_list) if l.strip() and l.strip().split("/")[1] in gt_paths]
    gt = []
    for obj in ids:
        rng = np.random.default_rng(args.seed)
        g = np.load(gt_paths[obj.split("/")[1]])
        gt.append(pc_norm(g[rng.choice(len(g), N_POINTS, replace=False)].astype(np.float64)).astype(np.float32))
    gt = np.stack(gt)
    cats = np.array([o.split("/")[0] for o in ids])
    same = (cats[:, None] == cats[None]) & ~np.eye(len(ids), dtype=bool)
    other = ~np.eye(len(ids), dtype=bool)
    os.makedirs(args.out_dir, exist_ok=True)
    summary_path = f"{args.out_dir}/summary.json"
    summary = json.load(open(summary_path)) if os.path.exists(summary_path) else {}
    for name, mesh_dir in methods:
        out = f"{args.out_dir}/{name}.json"
        if os.path.exists(out):
            summary[name] = json.load(open(out))["summary"]
            continue
        paths = [[q for q in glob.glob(f"{mesh_dir}/{o.replace('/', '_')}.*") if q.endswith((".ply", ".obj"))]
                 for o in ids]
        if not all(paths):
            print(f"skip {name}: {sum(map(bool, paths))}/{len(ids)} meshes", flush=True)
            continue
        with Pool(16) as pool:
            gen = np.stack(pool.map(sample, [(q[0], args.seed) for q in paths]))
        D = cd_matrix(gen, gt)
        acc_same, per_same = pairwise_acc(D, same)
        acc_all, _ = pairwise_acc(D, other)
        s = {"n": len(ids), "n_same_pairs": int(same.sum()), "within_cat_2way": acc_same, "all_2way": acc_all,
             "top1_retrieval": float((D.argmin(1) == np.arange(len(ids))).mean()),
             "rank_of_own_gt_within_cat": float(np.mean([(D[i][same[i]] < D[i, i]).sum() / max(same[i].sum(), 1)
                                                         for i in range(len(ids))]))}
        json.dump({"summary": s, "ids": ids, "per_object_within_cat": per_same, "cd_matrix_x1e3": (D * 1e3).tolist()},
                  open(out, "w"))
        summary[name] = s
        print(f"{name:45s} within-cat 2-way {acc_same:.3f}  all 2-way {acc_all:.3f}  top1 {s['top1_retrieval']:.3f}",
              flush=True)
    json.dump(summary, open(summary_path, "w"), indent=1)


if __name__ == "__main__":
    main()