"""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()