File size: 1,778 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
#!/usr/bin/env python
"""DTW score: re-simulated trajectories vs baked ground truth, per active object.

Usage:
  python score_dtw.py --world work/B_03/world --sims work/B_03/out_p1 work/B_03/out_p2
"""
import argparse
import json
from pathlib import Path

import numpy as np


def dtw(a, b):
    """Mean-per-step DTW cost between two (F,3) trajectories."""
    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 D[n, m] / (n + m)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--world", required=True)
    ap.add_argument("--sims", nargs="+", required=True)
    ap.add_argument("--out", default=None, help="write JSON here too")
    args = ap.parse_args()

    world = Path(args.world)
    names = [p.stem for p in (world / "dyn").glob("*.npz")]
    report = {}
    for sim in args.sims:
        traj = np.load(Path(sim) / "simtraj.npz")
        sim_names = [k for k in traj.files if k in names and k != "Ball"]  # Ball = kinematic replay == truth
        per = {}
        for n in sorted(sim_names):
            truth = np.load(world / "dyn" / f"{n}.npz")["pos"].astype(np.float64).mean(axis=1)
            sim_t = traj[n].astype(np.float64)
            per[n] = round(dtw(truth, sim_t), 5)
        report[sim] = {
            "per_object": per,
            "mean": round(float(np.mean(list(per.values()))) if per else None, 5),
        }
        print(json.dumps({sim: report[sim]}, indent=1))

    if args.out:
        Path(args.out).write_text(json.dumps(report, indent=1))


if __name__ == "__main__":
    main()