File size: 3,861 Bytes
42afafb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Score the 2x2 ablation arms for the B_07 cloth case, 4DCodeBench-style.

Metrics (all computed against the baked ground-truth cloth trajectory):
  chamfer_t    mean per-frame symmetric chamfer between sim and GT cloth point
               clouds, subsampled, averaged over frames (meters, lower better)
  dtw_com      DTW between the cloth center-of-mass trajectories (meters)
  bbox_iou_t   mean 3D IoU of the axis-aligned cloth bounding box per frame
  final_cham   chamfer at the last frame (did it end in the same place?)

Usage:
  python score_ablation.py --world work/B_07/world --runs work/B_07/ablation \
      --out work/B_07/ablation/metrics.json [--csv work/B_07/ablation/metrics.csv]
"""
import argparse
import csv
import json
from pathlib import Path

import numpy as np


def chamfer(a, b, n=2000, seed=0):
    rng = np.random.default_rng(seed)
    ai = rng.choice(len(a), min(n, len(a)), replace=False)
    bi = rng.choice(len(b), min(n, len(b)), replace=False)
    A, B = a[ai].astype(np.float64), b[bi].astype(np.float64)
    d_ab = ((A[:, None, :] - B[None, :, :]) ** 2).sum(-1)
    d1 = np.sqrt(d_ab.min(1))
    d2 = np.sqrt(((B[:, None, :] - A[None, :, :]) ** 2).sum(-1)).min(1)
    return float(0.5 * (d1.mean() + d2.mean()))


def dtw(a, b):
    n, m = len(a), len(b)
    D = np.full((n + 1, m + 1), np.inf)
    D[0, 0] = 0.0
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            c = float(np.linalg.norm(a[i - 1] - b[j - 1]))
            D[i, j] = c + min(D[i - 1, j - 1], D[i, j - 1], D[i - 1, j])
    return float(D[n, m] / (n + m))


def bbox_iou(a, b):
    amin, amax = a.min(0), a.max(0)
    bmin, bmax = b.min(0), b.max(0)
    inter_min = np.maximum(amin, bmin)
    inter_max = np.minimum(amax, bmax)
    inter = np.clip(inter_max - inter_min, 0, None).prod()
    va = (amax - amin).prod()
    vb = (bmax - bmin).prod()
    union = va + vb - inter
    return float(inter / union) if union > 0 else 0.0


def score(world_dir, traj_dir, frame_stride=3):
    gt = np.load(Path(world_dir) / "dyn" / "Cloth.npz")["pos"].astype(np.float32)
    sim = np.load(Path(traj_dir) / "clothtraj.npz")["pos"].astype(np.float32)
    assert sim.shape == gt.shape, f"shape mismatch {sim.shape} vs {gt.shape}"
    F = gt.shape[0]
    frames = list(range(0, F, frame_stride))
    if frames[-1] != F - 1:
        frames.append(F - 1)
    ch = [chamfer(sim[i], gt[i], seed=i) for i in frames]
    gt_com = gt.mean(1)
    sim_com = sim.mean(1)
    iou = [bbox_iou(sim[i], gt[i]) for i in frames]
    return {
        "chamfer_t_m": round(float(np.mean(ch)), 4),
        "final_chamfer_m": round(ch[-1], 4),
        "dtw_com_m": round(dtw(sim_com, gt_com), 4),
        "bbox_iou_t": round(float(np.mean(iou)), 4),
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--world", required=True)
    ap.add_argument("--runs", required=True, nargs="+")
    ap.add_argument("--names", required=True, nargs="+")
    ap.add_argument("--out", required=True)
    ap.add_argument("--csv", default=None)
    args = ap.parse_args()

    report = {}
    for name, run in zip(args.names, args.runs):
        try:
            report[name] = score(args.world, run)
        except Exception as e:
            report[name] = {"error": str(e)}
        print(name, json.dumps(report[name]))

    Path(args.out).write_text(json.dumps(report, indent=1))
    print(f"wrote {args.out}")

    if args.csv:
        keys = ["chamfer_t_m", "final_chamfer_m", "dtw_com_m", "bbox_iou_t"]
        with open(args.csv, "w", newline="") as f:
            w = csv.writer(f)
            w.writerow(["arm"] + keys)
            for name in args.names:
                r = report[name]
                w.writerow([name] + [r.get(k, "") for k in keys])
        print(f"wrote {args.csv}")


if __name__ == "__main__":
    main()