File size: 75,558 Bytes
8ca7ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
"""Compare the droid-normals dataset ("theirs", /home/wujiayir/public_datasets/droid-normals) against our v2
renders ("ours") on the same SAM3 ground-truth robot masks.

Sub-commands (all outputs under out/compare_dn/):
  overlap                      -> overlap.json, overlap_cams.csv   (their 1226 cams vs our selection / GT / v2 calib)
  bench [--workers N]          -> metrics_benchmark.csv (+ bench_masks/)   36-episode benchmark GT (out/diag/gtmask)
  scale --chunk i --nchunks N  -> scale_chunks/chunk_i.csv            at-scale GT (out/gt, 16 steps / camera)
  aggregate                    -> metrics_scale.csv, summary.json, summary.md, grid_benchmark.jpg,
                                  worst_theirs.jpg, worst_ours.jpg, clips/clip_{static,fast,closed}.mp4

Methods: theirs (droid-normals mask.mkv), ours_v2 / ours_default (fresh EpisodeSession render; label = calibration used) and
ours_old (OLD-geometry renders: benchmark -> out/diag/gtmask/<step>_rend.png, re-scored, + out/diag/residual/metrics.csv joined
as old_iou_csv / old_r2g_csv; at scale -> out/<uuid>/<serial>/mask.mp4 frame k == step k, threshold 128, only for episodes with
out/<uuid>/.done and no .done_v2).  Motion analysis per frame: EE image-motion direction (h5 cartesian_position projected with our
camera), best rigid shift (FFT, half res) and centroid offset of each mask vs GT projected on that direction -> signed 'lead' in px
and ms (positive = mask displaced along the motion = robot state later than the frame).

Metrics per frame (1280x720 px, same code as scripts/benchmark_align.py): IoU, r2g (mean distance from the
render-silhouette edge pixels to the nearest GT edge pixel), g2r (GT edge -> nearest render edge), area ratio,
and the same three restricted to a gripper ROI = dilate(our pybullet gripper segmentation  U  (their mask within
40 px of it), 41x41).  Theirs: mask.mkv frame k == h5 step k (verified: n_video_frames == traj_len-1 for all
1226 cams).  Ours: EpisodeSession(ep_dir) -> calib_refined_v2.json when present ('v2'), else default ('default').

Run everything on compute nodes (sbatch, see out/compare_dn/jobs/).  Do not run on the 1-CPU login node.
"""
import argparse
import csv
import hashlib
import json
import os
import sys
import time
from collections import Counter, OrderedDict, defaultdict
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))
cv2.setNumThreads(1)

DN = Path("/home/wujiayir/public_datasets/droid-normals")
OUT = ROOT / "out/compare_dn"
BENCH_ROOT = ROOT / "out/diag/gtmask"
SAMPLE = ROOT / "out/diag/sample.json"
GT_ROOT = ROOT / "out/gt"
USABLE = ("ok", "single", "low_conf")
USABLE_EXT = USABLE + ("render_far_off", "render_missing_robot")
MIN_GT_PX = 3000
K3 = np.ones((3, 3), np.uint8)
K41 = np.ones((41, 41), np.uint8)
K81 = np.ones((81, 81), np.uint8)
MOVING_MPS = 0.1
CLOSED_G = 0.45
METRIC_KEYS = ("area", "iou", "area_ratio", "r2g", "r2g_p90", "g2r", "grip_iou", "grip_r2g", "grip_g2r")
PY = sys.executable


def log(msg):
    print(f"[compare_dn {time.strftime('%H:%M:%S')}] {msg}", flush=True)


def fnum(v):
    try:
        x = float(v)
        return x if np.isfinite(x) else None
    except (TypeError, ValueError):
        return None


def pct(a, q=(10, 50, 90)):
    a = np.asarray([x for x in a if x is not None and np.isfinite(x)], dtype=float)
    if a.size == 0:
        return [None] * len(q), 0
    return [round(float(np.percentile(a, p)), 4) for p in q], int(a.size)


def md5_file(p):
    try:
        return hashlib.md5(open(p, "rb").read()).hexdigest()
    except OSError:
        return None


# ----------------------------------------------------------------------------- inputs

_MODEL_MAP = None


def lab_of(uuid):
    global _MODEL_MAP
    if _MODEL_MAP is None:
        _MODEL_MAP = json.load(open(ROOT / "data/robot_model_map.json"))["episodes"]
    lab = (_MODEL_MAP.get(uuid) or {}).get("lab") or uuid.split("+")[0]
    return "TRI" if lab.lower() == "tri" else lab


def load_manifest():
    rows = list(csv.DictReader(open(DN / "manifest.csv")))
    for r in rows:
        r["cam_serial"] = str(r["cam_serial"])
        r["per_cam_loss"] = float(r["per_cam_loss"])
        r["frames"] = int(r["frames"])
    return rows


def load_selection():
    return OrderedDict((r["uuid"], r) for r in csv.DictReader(open(ROOT / "data/task_selection.tsv"), delimiter="\t"))


def ext_serials_of(uuid):
    md = json.load(open(ROOT / "data" / uuid / "metadata.json"))
    return [str(md[k]) for k in ("ext1_cam_serial", "ext2_cam_serial") if md.get(k)]


def ee_speed_and_gripper(ep_dir, full=False):
    """Per-step end-effector speed (m/s, central difference of cartesian_position over robot timestamps) and gripper_position."""
    import h5py
    with h5py.File(Path(ep_dir) / "trajectory.h5", "r") as f:
        pos = f["observation/robot_state/cartesian_position"][:, :3].astype(np.float64)
        g = f["observation/robot_state/gripper_position"][:].astype(np.float64)
        t = f["observation/timestamp/robot_state/robot_timestamp_nanos"][:].astype(np.float64) * 1e-9
    n = len(pos)
    sp = np.zeros(n)
    vel = np.zeros((n, 3))
    if n >= 2:
        i0 = np.clip(np.arange(n) - 1, 0, n - 1)
        i1 = np.clip(np.arange(n) + 1, 0, n - 1)
        dt = t[i1] - t[i0]
        dt[dt <= 0] = np.nan
        vel = np.nan_to_num((pos[i1] - pos[i0]) / dt[:, None], nan=0.0)
        sp = np.linalg.norm(vel, axis=1)
    if full:
        return sp, g, pos, vel
    return sp, g


class TheirMasks:
    """mask.mkv of one camera folder.  Frame k <-> h5 step k.  Indexed read (FFV1 is intra-only) when the container
    frame count matches meta.json; otherwise sequential read of the needed frames."""

    def __init__(self, folder, needed=None):
        self.folder = Path(folder)
        self.meta = json.load(open(self.folder / "meta.json"))
        self.n_meta = int(self.meta["frames"])
        self.cap = cv2.VideoCapture(str(self.folder / "mask.mkv"))
        self.n_cap = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        self.count_ok = self.n_cap == self.n_meta
        self.needed = set(int(k) for k in needed) if needed is not None else None
        self.seq = None
        self.n_fallback = 0

    def _read_seq(self):
        self.seq = {}
        cap = cv2.VideoCapture(str(self.folder / "mask.mkv"))
        k = 0
        while True:
            ok, f = cap.read()
            if not ok:
                break
            if self.needed is None or k in self.needed:
                self.seq[k] = f[..., 0] > 127
            k += 1
        self.n_seq = k
        cap.release()

    def get(self, k):
        k = int(k)
        if k < 0 or k >= self.n_meta:
            return None
        if self.count_ok and self.seq is None:
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, k)
            ok, f = self.cap.read()
            if ok and f is not None:
                return f[..., 0] > 127
            self.count_ok = False
            self.n_fallback += 1
        if self.seq is None:
            self._read_seq()
        return self.seq.get(k)

    def verify_indexed(self, steps):
        """Sequential re-read; returns (#compared, #mismatching frames) for the given steps."""
        old_needed = self.needed
        self.needed = set(int(s) for s in steps)
        self.seq = None
        self._read_seq()
        bad = 0
        cmp = 0
        for s in sorted(self.needed):
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, int(s))
            ok, f = self.cap.read()
            if not ok or s not in self.seq:
                bad += 1
                continue
            cmp += 1
            bad += int(not np.array_equal(f[..., 0] > 127, self.seq[s]))
        self.needed = old_needed
        self.seq = None
        return cmp, bad


class OldMasks:
    """out/<uuid>/<serial>/mask.mp4 of the OLD pipeline (H.264, 15 fps, frame k == step k); sequential decode of the needed frames."""

    def __init__(self, path, needed):
        self.path = Path(path)
        self.needed = set(int(k) for k in needed)
        self.seq = {}
        self.n = 0
        cap = cv2.VideoCapture(str(self.path))
        self.wh = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
        self.n_cap = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        k = 0
        last = max(self.needed) if self.needed else -1
        while k <= last:
            ok, f = cap.read()
            if not ok:
                break
            if k in self.needed:
                self.seq[k] = f[..., 0] > 128
            k += 1
        self.n_read = k
        self.n = self.n_cap
        cap.release()

    def get(self, k):
        return self.seq.get(int(k))


def best_shift(rend, gt, max_shift=75):
    """Best integer translation of the render (half resolution) -> (iou_best, dx_full, dy_full, iou_at_zero).  == benchmark_align.best_shift."""
    from scipy.signal import fftconvolve
    h, w = gt.shape
    r = cv2.resize(rend.astype(np.uint8) * 255, (w // 2, h // 2), interpolation=cv2.INTER_AREA) >= 128
    g = cv2.resize(gt.astype(np.uint8) * 255, (w // 2, h // 2), interpolation=cv2.INTER_AREA) >= 128
    if r.sum() == 0 or g.sum() == 0:
        return float("nan"), float("nan"), float("nan"), float("nan")
    rf, gf = r.astype(np.float32), g.astype(np.float32)
    inter = fftconvolve(gf, rf[::-1, ::-1], mode="full")
    inter = np.clip(np.rint(inter), 0, None)
    union = rf.sum() + gf.sum() - inter
    m = np.where(union > 0, inter / np.maximum(union, 1), 0.0)
    cy, cx = r.shape[0] - 1, r.shape[1] - 1
    win = m[cy - max_shift:cy + max_shift + 1, cx - max_shift:cx + max_shift + 1]
    k = int(np.argmax(win))
    dy, dx = divmod(k, win.shape[1])
    # parabolic sub-pixel refinement of the IoU peak (separable), clamped to +-0.5 half-res px
    fx = fy = 0.0
    if 0 < dx < win.shape[1] - 1:
        l, c, rr_ = win[dy, dx - 1], win[dy, dx], win[dy, dx + 1]
        den = l - 2 * c + rr_
        fx = float(np.clip(0.5 * (l - rr_) / den, -0.5, 0.5)) if den < 0 else 0.0
    if 0 < dy < win.shape[0] - 1:
        u, c, d = win[dy - 1, dx], win[dy, dx], win[dy + 1, dx]
        den = u - 2 * c + d
        fy = float(np.clip(0.5 * (u - d) / den, -0.5, 0.5)) if den < 0 else 0.0
    return float(win[dy, dx]), float(2 * (dx - max_shift + fx)), float(2 * (dy - max_shift + fy)), float(m[cy, cx])


def centroid(m):
    ys, xs = np.nonzero(m)
    return (float(xs.mean()), float(ys.mean())) if len(xs) else (float("nan"), float("nan"))


def project(T, K, p):
    """base-frame point -> pixel (OpenCV convention: pixel = K [R|t] p)."""
    pc = T[:3, :3] @ np.asarray(p, float) + T[:3, 3]
    if pc[2] <= 1e-6:
        return np.array([np.nan, np.nan]), pc[2]
    return np.array([K[0, 0] * pc[0] / pc[2] + K[0, 2], K[1, 1] * pc[1] / pc[2] + K[1, 2]]), pc[2]


def motion_fields(T, K, pos, vel):
    """EE pixel, unit image-motion direction and image speed (px/s) of the EE at this step."""
    uv, z = project(T, K, pos)
    uv2, _ = project(T, K, pos + vel * 0.1)
    d = (uv2 - uv) * 10.0                    # px/s (linearised over 0.1 s)
    sp = float(np.hypot(*d)) if np.all(np.isfinite(d)) else float("nan")
    dirn = d / sp if sp and np.isfinite(sp) and sp > 1e-6 else np.array([np.nan, np.nan])
    return dict(ee_u=round(float(uv[0]), 1), ee_v=round(float(uv[1]), 1), ee_depth_m=round(float(z), 3), mv_dx=round(float(dirn[0]), 4), mv_dy=round(float(dirn[1]), 4),
                img_speed_pxps=round(sp, 1))


def motion_metrics(mask, gt, dirn, img_speed, c_gt, prefix):
    """Signed displacement of mask vs GT along the EE image-motion direction: centroid-based (_lead_c_px) and best-rigid-shift-based
    (_lead_s_px), converted to ms with the EE image speed (_lead_ms).  Positive = displaced along the motion (state later than frame)."""
    nan = float("nan")
    o = {prefix + k: nan for k in ("cdx", "cdy", "sdx", "sdy", "shift_iou_best", "shift_gain", "lead_c_px", "lead_s_px", "lead_ms")}
    if mask is None or not mask.any() or not gt.any():
        return o
    cx, cy = centroid(mask)
    o[prefix + "cdx"], o[prefix + "cdy"] = cx - c_gt[0], cy - c_gt[1]
    ib, dx, dy, i0 = best_shift(mask, gt)
    # best_shift returns the shift of the RENDER that maximises IoU; the mask is displaced by the opposite vector
    o[prefix + "sdx"], o[prefix + "sdy"] = -dx, -dy
    o[prefix + "shift_iou_best"], o[prefix + "shift_gain"] = ib, (ib - i0 if np.isfinite(ib) else nan)
    if dirn is not None and np.all(np.isfinite(dirn)):
        o[prefix + "lead_c_px"] = float(o[prefix + "cdx"] * dirn[0] + o[prefix + "cdy"] * dirn[1])
        o[prefix + "lead_s_px"] = float(o[prefix + "sdx"] * dirn[0] + o[prefix + "sdy"] * dirn[1])
        if img_speed and np.isfinite(img_speed) and img_speed >= 30.0:
            o[prefix + "lead_ms"] = 1000.0 * o[prefix + "lead_s_px"] / img_speed
    return o


# ----------------------------------------------------------------------------- metrics

def edge(m):
    return cv2.morphologyEx(m.astype(np.uint8), cv2.MORPH_GRADIENT, K3) > 0


def dt_to(e):
    return cv2.distanceTransform((~e).astype(np.uint8), cv2.DIST_L2, 5)


def iou_of(a, b):
    u = int((a | b).sum())
    return float((a & b).sum() / u) if u > 0 else float("nan")


def gt_cache_of(gt):
    e_g = edge(gt)
    return e_g, dt_to(e_g)


def metrics(rend, gt, gt_cache, roi=None, prefix=""):
    nan = float("nan")
    o = {k: nan for k in METRIC_KEYS}
    if rend is None:
        return {prefix + k: v for k, v in o.items()}
    o["area"] = int(rend.sum())
    a_gt = int(gt.sum())
    o["iou"] = iou_of(rend, gt)
    o["area_ratio"] = o["area"] / a_gt if a_gt > 0 else nan
    if o["area"] == 0 or a_gt == 0:
        return {prefix + k: v for k, v in o.items()}
    e_g, dt_g = gt_cache
    e_r = edge(rend)
    dt_r = dt_to(e_r)
    d_rg, d_gr = dt_g[e_r], dt_r[e_g]
    o["r2g"], o["r2g_p90"] = float(d_rg.mean()), float(np.percentile(d_rg, 90))
    o["g2r"] = float(d_gr.mean())
    if roi is not None and roi.any():
        o["grip_iou"] = iou_of(rend & roi, gt & roi)
        er, eg = e_r & roi, e_g & roi
        if er.sum() > 20:
            o["grip_r2g"] = float(dt_g[er].mean())
        if eg.sum() > 20:
            o["grip_g2r"] = float(dt_r[eg].mean())
    return {prefix + k: v for k, v in o.items()}


def gripper_roi(our_grip, theirs):
    """ROI = dilate( our gripper seg  U  their mask within 40 px of it , 41x41 ); None if our gripper is (nearly) invisible."""
    if our_grip is None or our_grip.sum() < 200:
        return None
    g8 = our_grip.astype(np.uint8)
    region = our_grip.copy()
    if theirs is not None:
        region |= theirs & (cv2.dilate(g8, K81) > 0)
    return cv2.dilate(region.astype(np.uint8), K41) > 0


# ----------------------------------------------------------------------------- worker

def _fit(m, shape):
    if m is None or m.shape == shape:
        return m
    return cv2.resize(m.astype(np.uint8) * 255, (shape[1], shape[0]), interpolation=cv2.INTER_NEAREST) > 128


def process_episode(task):
    """task = dict(uuid, lab, cams=[dict(serial, path, loss, steps=[dict(step, status, gt)])], save_dir, verify)
    -> (rows, info).  Renders OUR mask fresh for every frame and decodes THEIR mask at the same step."""
    os.environ.setdefault("OMP_NUM_THREADS", "1")
    cv2.setNumThreads(1)
    import render_episode as RE
    RE.VERBOSE = False
    uuid = task["uuid"]
    ep_dir = ROOT / "data" / uuid
    t0 = time.time()
    info = dict(uuid=uuid, lab=task["lab"], error=None, skipped=[], their_verify=[])
    try:
        sess = RE.EpisodeSession(str(ep_dir), wrist=False)
    except Exception as e:  # noqa: BLE001
        info["error"] = f"EpisodeSession: {e!r}"
        return [], info
    calib = "v2" if sess.calib_version == 2 else "default"
    v2p = ep_dir / "calib_refined_v2.json"
    info.update(calib=calib, calib_version=sess.calib_version, dt_ms=float(sess.dt_ms), arm=sess.arm_type,
                ext_base_source=dict(getattr(sess, "ext_base_source", {}) or {}),
                calib_v2_md5=md5_file(v2p) if (calib == "v2" and v2p.exists()) else None,
                calib_v2_mtime=(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(v2p.stat().st_mtime)) if v2p.exists() else None))
    speed, gs, pos, vel = ee_speed_and_gripper(ep_dir, full=True)
    old_root = ROOT / "out" / uuid
    has_old_mp4 = (old_root / ".done").exists() and not (old_root / ".done_v2").exists()
    info["old_source"] = "mask.mp4" if has_old_mp4 else None
    rows = []
    save_dir = Path(task["save_dir"]) if task.get("save_dir") else None
    for cam in task["cams"]:
        serial = str(cam["serial"])
        if serial not in sess.cap_ts or serial not in sess.K_mp4 or serial not in sess.T_ext:
            info["skipped"].append(f"{serial}: no cap_ts / K / T_ext")
            continue
        wh = tuple(sess.mp4_wh.get(serial, tuple(sess.wh[serial])))
        K = sess.K_mp4[serial]
        steps = [int(s["step"]) for s in cam["steps"]]
        tm = TheirMasks(DN / cam["path"], needed=steps)
        if task.get("verify"):
            cmpd, bad = tm.verify_indexed(steps)
            info["their_verify"].append(dict(serial=serial, n_cap=tm.n_cap, n_meta=tm.n_meta, compared=cmpd, mismatch=bad))
        v2q = ((sess.calib or {}).get("quality") or {}).get(serial) if calib == "v2" else None
        old = None
        old_src = None
        if task.get("bench"):
            old_src = "bench_rend_png"
        elif has_old_mp4 and (old_root / serial / "mask.mp4").exists():
            old = OldMasks(old_root / serial / "mask.mp4", steps)
            old_src = "mask.mp4"
            info.setdefault("old_mp4", []).append(dict(serial=serial, n_frames=old.n, wh=old.wh, n_steps=int(sess.n)))
        T_cam = sess.T_ext[serial]
        for s in cam["steps"]:
            step = int(s["step"])
            if step >= sess.n - 1:
                continue
            gt = cv2.imread(str(s["gt"]), cv2.IMREAD_GRAYSCALE)
            if gt is None:
                continue
            gt = gt > 128
            gt_px = int(gt.sum())
            theirs = _fit(tm.get(step), gt.shape)
            T = sess.set_step(serial, step, interp=True)
            _, _, seg = sess.rr.render_raw(T, K, wh)
            valid = seg >= 0
            body = np.where(valid, seg & ((1 << 24) - 1), -1)
            ours = _fit(valid, gt.shape)
            grip = _fit(body == sess.rr.gripper, gt.shape)
            roi = gripper_roi(grip, theirs)
            if old_src == "bench_rend_png":
                op = BENCH_ROOT / uuid / serial / f"{step:04d}_rend.png"
                om = cv2.imread(str(op), cv2.IMREAD_GRAYSCALE) if op.exists() else None
                oldm = _fit(om > 128, gt.shape) if om is not None else None
            elif old is not None:
                oldm = _fit(old.get(step), gt.shape)
            else:
                oldm = None
            mf = motion_fields(T_cam, K, pos[step], vel[step])
            dirn = np.array([mf["mv_dx"], mf["mv_dy"]])
            row = dict(uuid=uuid, lab=task["lab"], serial=serial, step=step, status=s.get("status"), gt_px=gt_px,
                       res=f"{gt.shape[1]}x{gt.shape[0]}", render_res=f"{wh[0]}x{wh[1]}",
                       usable=bool(s.get("status") in USABLE and gt_px >= MIN_GT_PX),
                       usable_ext=bool(s.get("status") in USABLE_EXT and gt_px >= MIN_GT_PX),
                       calib=calib, dt_ms=round(float(sess.dt_ms), 2), ext_source=info["ext_base_source"].get(serial),
                       v2_status=(v2q or {}).get("status"), their_loss=cam.get("loss"),
                       ee_speed=round(float(speed[step]), 4), moving=bool(speed[step] >= MOVING_MPS),
                       g=round(float(gs[step]), 4), closed=bool(gs[step] > CLOSED_G),
                       their_ok=bool(theirs is not None), their_count_ok=bool(tm.count_ok),
                       old_ok=bool(oldm is not None), old_src=old_src if oldm is not None else None,
                       roi_px=int(roi.sum()) if roi is not None else 0, our_grip_px=int(grip.sum()),
                       their_state_minus_frame_ms=round(float(sess.t_state[step] - (sess.cap_ts[serial][step] + sess.dt_ms)), 2))
            row.update(mf)
            if gt_px > 0:
                gc = gt_cache_of(gt)
                row.update(metrics(theirs, gt, gc, roi, "th_"))
                row.update(metrics(ours, gt, gc, roi, "our_"))
                row.update(metrics(oldm, gt, gc, roi, "old_"))
                c_gt = centroid(gt)
                row.update(motion_metrics(theirs, gt, dirn, mf["img_speed_pxps"], c_gt, "th_"))
                row.update(motion_metrics(ours, gt, dirn, mf["img_speed_pxps"], c_gt, "our_"))
                row.update(motion_metrics(oldm, gt, dirn, mf["img_speed_pxps"], c_gt, "old_"))
            else:
                row.update(metrics(None, gt, None, None, "th_"))
                row.update(metrics(None, gt, None, None, "our_"))
                row.update(metrics(None, gt, None, None, "old_"))
            if save_dir is not None:
                d = save_dir / uuid / serial
                d.mkdir(parents=True, exist_ok=True)
                cv2.imwrite(str(d / f"{step:04d}_ours.png"), ours.astype(np.uint8) * 255)
                if theirs is not None:
                    cv2.imwrite(str(d / f"{step:04d}_theirs.png"), theirs.astype(np.uint8) * 255)
                if oldm is not None:
                    cv2.imwrite(str(d / f"{step:04d}_old.png"), oldm.astype(np.uint8) * 255)
            rows.append(row)
    info["secs"] = round(time.time() - t0, 1)
    info["n_rows"] = len(rows)
    try:
        sess.rr.close()
    except Exception:  # noqa: BLE001
        pass
    return rows, info


def run_tasks(tasks, workers):
    results = []
    if workers <= 1:
        for t in tasks:
            results.append(process_episode(t))
            log(f"{t['uuid']}: {results[-1][1].get('n_rows')} rows {results[-1][1].get('secs')} s err={results[-1][1].get('error')}")
    else:
        import multiprocessing as mp
        with mp.get_context("spawn").Pool(workers) as pool:
            for rows, info in pool.imap_unordered(process_episode, tasks):
                results.append((rows, info))
                log(f"{info['uuid']}: {info.get('n_rows')} rows {info.get('secs')} s err={info.get('error')}")
    return results


def write_csv(path, rows):
    if not rows:
        return
    keys = []
    for r in rows:
        for k in r:
            if k not in keys:
                keys.append(k)
    with open(path, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=keys)
        w.writeheader()
        for r in rows:
            w.writerow({k: (f"{v:.6g}" if isinstance(v, float) else v) for k, v in r.items()})


# ----------------------------------------------------------------------------- overlap

def cmd_overlap(args):
    OUT.mkdir(parents=True, exist_ok=True)
    man = load_manifest()
    sel = load_selection()
    bench = {e["uuid"]: e for e in json.load(open(SAMPLE))["episodes"]}
    their = {(r["uuid"], r["cam_serial"]): r for r in man}
    cams = []
    for u in sel:
        exts = ext_serials_of(u)
        has_v2 = (ROOT / "data" / u / "calib_refined_v2.json").exists()
        gt_done = (GT_ROOT / u / ".gt_done").exists()
        st = json.load(open(GT_ROOT / u / "status.json")) if (GT_ROOT / u / "status.json").exists() else {}
        for s in exts:
            r = their.get((u, s))
            n_gt_usable = sum(v in USABLE for v in (st.get(s) or {}).values())
            cams.append(dict(uuid=u, serial=s, lab=lab_of(u), in_theirs=r is not None, their_loss=(r["per_cam_loss"] if r else None),
                             has_v2=has_v2, in_bench=(u in bench and s in [str(x) for x in bench[u]["serials"]["ext"]]),
                             gt_done=gt_done, n_gt_usable=n_gt_usable))
    their_not_ours = [k for k in their if k[0] not in sel or k[1] not in ext_serials_of(k[0])]
    by_lab = defaultdict(lambda: Counter())
    for c in cams:
        by_lab[c["lab"]]["selected_cams"] += 1
        by_lab[c["lab"]]["in_theirs"] += int(c["in_theirs"])
        by_lab[c["lab"]]["dropped_by_them"] += int(not c["in_theirs"])
        by_lab[c["lab"]]["their_with_bench_gt"] += int(c["in_theirs"] and c["in_bench"])
        by_lab[c["lab"]]["their_with_scale_gt"] += int(c["in_theirs"] and c["n_gt_usable"] > 0)
        by_lab[c["lab"]]["their_with_v2"] += int(c["in_theirs"] and c["has_v2"])
    eps_their = set(r["uuid"] for r in man)
    eps_lab = defaultdict(lambda: Counter())
    for u in sel:
        eps_lab[lab_of(u)]["selected_eps"] += 1
        eps_lab[lab_of(u)]["eps_in_theirs"] += int(u in eps_their)
    summary = dict(
        their_rows=len(man), their_uuids=len(eps_their), their_uuids_in_selection=len(eps_their & set(sel)),
        their_pairs_not_matching_our_ext_cams=len(their_not_ours),
        selected_eps=len(sel), selected_ext_cams=len(cams),
        selected_cams_in_theirs=sum(c["in_theirs"] for c in cams), selected_cams_dropped_by_them=sum(not c["in_theirs"] for c in cams),
        selected_eps_with_no_cam_in_theirs=len(set(sel) - eps_their),
        their_cams_with_bench_gt=sum(c["in_theirs"] and c["in_bench"] for c in cams),
        their_eps_with_bench_gt=len(set(c["uuid"] for c in cams if c["in_theirs"] and c["in_bench"])),
        bench_eps_total=len(bench), bench_cams_total=sum(len(e["serials"]["ext"]) for e in bench.values()),
        their_cams_with_scale_gt=sum(c["in_theirs"] and c["n_gt_usable"] > 0 for c in cams),
        their_cams_with_v2_calib=sum(c["in_theirs"] and c["has_v2"] for c in cams),
        their_eps_with_v2_calib=len(set(c["uuid"] for c in cams if c["in_theirs"] and c["has_v2"])),
        eps_with_v2_calib_total=sum((ROOT / "data" / u / "calib_refined_v2.json").exists() for u in sel),
        their_loss_pcts=dict(zip(("p10", "p50", "p90", "max"), pct([r["per_cam_loss"] for r in man], (10, 50, 90, 100))[0])),
        by_lab={l: dict(by_lab[l], **eps_lab[l]) for l in sorted(by_lab)},
        dropped_per_episode=Counter(sum(not c["in_theirs"] for c in cams if c["uuid"] == u) for u in sel),
    )
    summary["dropped_per_episode"] = {str(k): v for k, v in sorted(summary["dropped_per_episode"].items())}
    json.dump(summary, open(OUT / "overlap.json", "w"), indent=1)
    write_csv(OUT / "overlap_cams.csv", cams)
    log(json.dumps(summary, indent=1))


# ----------------------------------------------------------------------------- bench / scale task building

def their_index():
    return {(r["uuid"], r["cam_serial"]): r for r in load_manifest()}


def bench_tasks(their, episodes=None, max_frames=0):
    sample = json.load(open(SAMPLE))["episodes"]
    tasks = []
    for ep in sample:
        u = ep["uuid"]
        if episodes and u not in episodes:
            continue
        cams = []
        for serial in [str(s) for s in ep["serials"]["ext"]]:
            r = their.get((u, serial))
            if r is None:
                continue
            steps = []
            for step in [int(f) for f in ep["frames"]][: max_frames or None]:
                gp = BENCH_ROOT / u / serial / f"{step:04d}_gt.png"
                if not gp.exists():
                    continue
                status = None
                pj = BENCH_ROOT / u / serial / f"{step:04d}_prompt.json"
                if pj.exists():
                    try:
                        status = json.load(open(pj)).get("status")
                    except (OSError, ValueError):
                        status = None
                steps.append(dict(step=step, status=status, gt=str(gp)))
            if steps:
                cams.append(dict(serial=serial, path=r["path"], loss=r["per_cam_loss"], steps=steps))
        if cams:
            tasks.append(dict(uuid=u, lab=lab_of(u), cams=cams, save_dir=str(OUT / "bench_masks"), verify=True, bench=True))
    return tasks


def scale_tasks(their, episodes=None):
    by_ep = OrderedDict()
    for (u, s), r in their.items():
        by_ep.setdefault(u, []).append((s, r))
    tasks = []
    for u, lst in by_ep.items():
        if episodes and u not in episodes:
            continue
        sp = GT_ROOT / u / "status.json"
        if not sp.exists():
            continue
        st_all = json.load(open(sp))
        cams = []
        for s, r in lst:
            st = st_all.get(s) or {}
            steps = []
            for k, status in st.items():
                if status in ("robot_not_visible", "no_frame", "error"):
                    continue
                step = int(k)
                gp = GT_ROOT / u / s / f"{step:04d}.png"
                if gp.exists():
                    steps.append(dict(step=step, status=status, gt=str(gp)))
            if steps:
                cams.append(dict(serial=s, path=r["path"], loss=r["per_cam_loss"], steps=sorted(steps, key=lambda d: d["step"])))
        if cams:
            tasks.append(dict(uuid=u, lab=lab_of(u), cams=cams, save_dir=None, verify=False, bench=False))
    return tasks


def cmd_bench(args):
    OUT.mkdir(parents=True, exist_ok=True)
    their = their_index()
    tasks = bench_tasks(their, set(args.episodes) if args.episodes else None, args.max_frames)
    log(f"benchmark: {len(tasks)} episodes, {sum(len(t['cams']) for t in tasks)} cams, "
        f"{sum(len(c['steps']) for t in tasks for c in t['cams'])} frames, {args.workers} workers")
    res = run_tasks(tasks, args.workers)
    rows = [r for rs, _ in res for r in rs]
    infos = [i for _, i in res]
    # join the old-pipeline numbers of out/diag/residual/metrics.csv (same frames; verified to reproduce from the _rend.png)
    old_csv = {}
    rp = ROOT / "out/diag/residual/metrics.csv"
    if rp.exists():
        for r in csv.DictReader(open(rp)):
            old_csv[(r["uuid"], str(r["serial"]), int(r["step"]))] = r
    for r in rows:
        o = old_csv.get((r["uuid"], r["serial"], int(r["step"])))
        r["old_iou_csv"] = fnum(o["iou"]) if o else None
        r["old_r2g_csv"] = fnum(o["ch_r2g_mean"]) if o else None
        r["old_dt_ms_csv"] = fnum(o["dt_ms"]) if o else None
    out_csv = OUT / ("metrics_benchmark.csv" if not args.out_suffix else f"metrics_benchmark{args.out_suffix}.csv")
    write_csv(out_csv, rows)
    json.dump(infos, open(OUT / f"bench_infos{args.out_suffix}.json", "w"), indent=1, default=str)
    ver = [v for i in infos for v in i.get("their_verify", [])]
    log(f"wrote {out_csv} ({len(rows)} rows); their mask indexed-vs-sequential: compared {sum(v['compared'] for v in ver)} "
        f"frames, mismatches {sum(v['mismatch'] for v in ver)}, count_ok {sum(v['n_cap'] == v['n_meta'] for v in ver)}/{len(ver)}")


def cmd_scale(args):
    (OUT / "scale_chunks").mkdir(parents=True, exist_ok=True)
    their = their_index()
    tasks = scale_tasks(their, set(args.episodes) if args.episodes else None)
    tasks = tasks[args.chunk::args.nchunks]
    log(f"scale chunk {args.chunk}/{args.nchunks}: {len(tasks)} episodes, {sum(len(t['cams']) for t in tasks)} cams, "
        f"{sum(len(c['steps']) for t in tasks for c in t['cams'])} frames, {args.workers} workers")
    res = run_tasks(tasks, args.workers)
    rows = [r for rs, _ in res for r in rs]
    infos = [i for _, i in res]
    write_csv(OUT / "scale_chunks" / f"chunk_{args.chunk:03d}.csv", rows)
    json.dump(infos, open(OUT / "scale_chunks" / f"chunk_{args.chunk:03d}_infos.json", "w"), indent=1, default=str)
    log(f"chunk {args.chunk}: {len(rows)} rows, {sum(1 for i in infos if i.get('error'))} episode errors")


# ----------------------------------------------------------------------------- aggregation

STR_COLS = ("uuid", "lab", "serial", "status", "res", "render_res", "calib", "ext_source", "v2_status", "old_src")
INT_COLS = ("step", "gt_px", "roi_px", "our_grip_px")


def read_rows(path):
    rows = []
    with open(path) as f:
        for r in csv.DictReader(f):
            for k, v in list(r.items()):
                if v in ("True", "False"):
                    r[k] = v == "True"
                elif k in INT_COLS:
                    r[k] = int(v) if v else 0
                elif k not in STR_COLS:
                    r[k] = fnum(v)
            rows.append(r)
    return rows


METHODS = (("th", "theirs"), ("our", "ours"), ("old", "ours_old"))


def method_stats(rows, who):
    rr = [r for r in rows if r.get(f"{who}_iou") is not None]
    o = dict(n=len(rr))
    for m in ("iou", "r2g", "g2r", "grip_iou", "grip_r2g", "grip_g2r"):
        v = [r.get(f"{who}_{m}") for r in rr]
        o[f"{m}_p10_p50_p90"], o[f"n_{m}"] = pct(v)
    v = [r[f"{who}_iou"] for r in rr]
    if v:
        o["iou_mean"] = round(float(np.mean(v)), 4)
        o["frac_iou_lt_0.5"] = round(float(np.mean([x < 0.5 for x in v])), 4)
        o["frac_iou_ge_0.8"] = round(float(np.mean([x >= 0.8 for x in v])), 4)
    v = [r.get(f"{who}_r2g") for r in rr if r.get(f"{who}_r2g") is not None]
    if v:
        o["frac_r2g_gt_10px"] = round(float(np.mean([x > 10 for x in v])), 4)
        o["frac_r2g_gt_20px"] = round(float(np.mean([x > 20 for x in v])), 4)
    return o


def pair_stats(rows, a, b):
    """d = b - a on frames where both exist; win_b = fraction where b is better."""
    rr = [r for r in rows if r.get(f"{a}_iou") is not None and r.get(f"{b}_iou") is not None]
    o = dict(n=len(rr), a=a, b=b)
    for m in ("iou", "r2g", "g2r", "grip_iou", "grip_r2g"):
        pairs = [(r[f"{a}_{m}"], r[f"{b}_{m}"]) for r in rr if r.get(f"{a}_{m}") is not None and r.get(f"{b}_{m}") is not None]
        o[f"d_{m}_p10_p50_p90"], o[f"n_{m}"] = pct([y - x for x, y in pairs])
        if pairs:
            if m in ("iou", "grip_iou"):
                o[f"win_{m}_{b}"] = round(float(np.mean([y > x for x, y in pairs])), 4)
                o[f"win_{m}_{a}"] = round(float(np.mean([y < x for x, y in pairs])), 4)
                o[f"tie_{m}_abs_le_0.01"] = round(float(np.mean([abs(y - x) <= 0.01 for x, y in pairs])), 4)
                o[f"{b}_better_by_ge_0.05_{m}"] = round(float(np.mean([y - x >= 0.05 for x, y in pairs])), 4)
                o[f"{a}_better_by_ge_0.05_{m}"] = round(float(np.mean([x - y >= 0.05 for x, y in pairs])), 4)
            else:
                o[f"win_{m}_{b}"] = round(float(np.mean([y < x for x, y in pairs])), 4)
                o[f"win_{m}_{a}"] = round(float(np.mean([y > x for x, y in pairs])), 4)
            o[f"{a}_{m}_p50_same_frames"] = round(float(np.median([x for x, _ in pairs])), 4)
            o[f"{b}_{m}_p50_same_frames"] = round(float(np.median([y for _, y in pairs])), 4)
    return o


def md_table(header, lines):
    out = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
    for ln in lines:
        out.append("| " + " | ".join(str(x) for x in ln) + " |")
    return "\n".join(out)


def fmt3(v, nd=3):
    if v is None:
        return "-"
    if isinstance(v, (list, tuple)):
        return "/".join(fmt3(x, nd) for x in v)
    if isinstance(v, float):
        return f"{v:.{nd}f}" if not np.isnan(v) else "-"
    return str(v)


M_HDR = ["subset", "method", "n", "IoU p10/p50/p90", "IoU mean", "r2g px p10/p50/p90", "g2r px p10/p50/p90", "IoU<0.5", "IoU>=0.8", "r2g>10px", "r2g>20px"]
P_HDR = ["subset", "comparison (B vs A)", "n pairs", "A IoU p50", "B IoU p50", "dIoU=B-A p10/p50/p90", "A r2g p50", "B r2g p50", "dr2g=B-A p10/p50/p90",
         "win IoU B", "win IoU A", "tie |dIoU|<=0.01", "B better >=0.05", "A better >=0.05", "win r2g B", "win g2r B"]
G_HDR = ["subset", "method", "n", "ROI IoU p10/p50/p90", "ROI r2g p10/p50/p90", "ROI g2r p10/p50/p90"]
GP_HDR = ["subset", "comparison (B vs A)", "n pairs", "A ROI IoU p50", "B ROI IoU p50", "dROI IoU=B-A p10/p50/p90", "A ROI r2g p50", "B ROI r2g p50", "dROI r2g p10/p50/p90", "win ROI IoU B", "win ROI r2g B"]


def m_line(subset, name, st):
    return [subset, name, st["n"], fmt3(st.get("iou_p10_p50_p90")), fmt3(st.get("iou_mean")), fmt3(st.get("r2g_p10_p50_p90"), 1), fmt3(st.get("g2r_p10_p50_p90"), 1),
            fmt3(st.get("frac_iou_lt_0.5")), fmt3(st.get("frac_iou_ge_0.8")), fmt3(st.get("frac_r2g_gt_10px")), fmt3(st.get("frac_r2g_gt_20px"))]


def p_line(subset, name, ps):
    a, b = ps["a"], ps["b"]
    return [subset, name, ps["n"], fmt3(ps.get(f"{a}_iou_p50_same_frames")), fmt3(ps.get(f"{b}_iou_p50_same_frames")), fmt3(ps.get("d_iou_p10_p50_p90")),
            fmt3(ps.get(f"{a}_r2g_p50_same_frames"), 1), fmt3(ps.get(f"{b}_r2g_p50_same_frames"), 1), fmt3(ps.get("d_r2g_p10_p50_p90"), 1),
            fmt3(ps.get(f"win_iou_{b}")), fmt3(ps.get(f"win_iou_{a}")), fmt3(ps.get("tie_iou_abs_le_0.01")), fmt3(ps.get(f"{b}_better_by_ge_0.05_iou")),
            fmt3(ps.get(f"{a}_better_by_ge_0.05_iou")), fmt3(ps.get(f"win_r2g_{b}")), fmt3(ps.get(f"win_g2r_{b}"))]


def g_line(subset, name, st):
    return [subset, name, st.get("n_grip_iou"), fmt3(st.get("grip_iou_p10_p50_p90")), fmt3(st.get("grip_r2g_p10_p50_p90"), 1), fmt3(st.get("grip_g2r_p10_p50_p90"), 1)]


def gp_line(subset, name, ps):
    a, b = ps["a"], ps["b"]
    return [subset, name, ps.get("n_grip_iou"), fmt3(ps.get(f"{a}_grip_iou_p50_same_frames")), fmt3(ps.get(f"{b}_grip_iou_p50_same_frames")), fmt3(ps.get("d_grip_iou_p10_p50_p90")),
            fmt3(ps.get(f"{a}_grip_r2g_p50_same_frames"), 1), fmt3(ps.get(f"{b}_grip_r2g_p50_same_frames"), 1), fmt3(ps.get("d_grip_r2g_p10_p50_p90"), 1),
            fmt3(ps.get(f"win_grip_iou_{b}")), fmt3(ps.get(f"win_grip_r2g_{b}"))]


def method_groups(rows, split_calib):
    """[(method label, 'who' prefix, rows)] -- ours is split by the calibration label when split_calib."""
    g = [("theirs", "th", rows)]
    if split_calib:
        g += [("ours_v2", "our", [r for r in rows if r["calib"] == "v2"]), ("ours_default", "our", [r for r in rows if r["calib"] == "default"])]
    else:
        g += [("ours_v2", "our", rows)]
    g += [("ours_old", "old", [r for r in rows if r.get("old_iou") is not None])]
    return g


def subsets(rows):
    return [("all", rows),
            ("moving (ee>=0.1 m/s)", [r for r in rows if r["moving"]]), ("static (ee<0.1 m/s)", [r for r in rows if not r["moving"]]),
            ("fast (ee>=0.25 m/s)", [r for r in rows if (r.get("ee_speed") or 0) >= 0.25]),
            ("gripper closed (g>0.45)", [r for r in rows if r["closed"]]), ("gripper open (g<=0.45)", [r for r in rows if not r["closed"]])]


def summarize_set(rows, title, split_calib=False):
    md, js = [f"### {title}", ""], {}
    m_lines, p_lines = [], []
    for sname, srows in subsets(rows):
        for label, who, grows in method_groups(srows, split_calib):
            st = method_stats(grows, who)
            js[f"{sname} | {label}"] = st
            m_lines.append(m_line(sname, label + (" (theirs on same frames)" if False else ""), st))
            if label != "theirs" and st["n"]:
                ps = pair_stats(grows, "th", who)
                js[f"{sname} | {label} vs theirs"] = ps
                p_lines.append(p_line(sname, f"{label} vs theirs", ps))
        # old vs ours on the same frames (old frames are default-calib episodes at scale, v2 on the benchmark)
        orows = [r for r in srows if r.get("old_iou") is not None]
        if orows:
            ps = pair_stats(orows, "old", "our")
            js[f"{sname} | ours vs ours_old"] = ps
            p_lines.append(p_line(sname, "ours(" + "/".join(sorted(set(r["calib"] for r in orows))) + ") vs ours_old", ps))
    md += ["Per-method distributions (each method on the frames where it exists; ours_* subsets differ -> compare via the paired table):", "",
           md_table(M_HDR, m_lines), "", "Paired on identical frames (d = B - A):", "", md_table(P_HDR, p_lines), ""]
    # per lab
    l_lines, lp_lines = [], []
    for lab in sorted(set(r["lab"] for r in rows)):
        lr = [r for r in rows if r["lab"] == lab]
        for label, who, grows in method_groups(lr, split_calib):
            st = method_stats(grows, who)
            js[f"lab {lab} | {label}"] = st
            if st["n"]:
                l_lines.append(m_line(lab, label, st))
            if label != "theirs" and st["n"]:
                ps = pair_stats(grows, "th", who)
                js[f"lab {lab} | {label} vs theirs"] = ps
                lp_lines.append(p_line(lab, f"{label} vs theirs", ps))
    md += ["Per lab:", "", md_table(M_HDR, l_lines), "", "Per lab, paired:", "", md_table(P_HDR, lp_lines), ""]
    # gripper ROI
    g_lines, gp_lines = [], []
    for sname, srows in (("all", rows), ("closed (g>0.45)", [r for r in rows if r["closed"]]), ("open (g<=0.45)", [r for r in rows if not r["closed"]]),
                         ("closed & static", [r for r in rows if r["closed"] and not r["moving"]]), ("open & static", [r for r in rows if (not r["closed"]) and not r["moving"]])):
        srows = [r for r in srows if (r.get("roi_px") or 0) > 0]
        for label, who, grows in method_groups(srows, split_calib):
            st = method_stats(grows, who)
            js[f"grip {sname} | {label}"] = st
            if st.get("n_grip_iou"):
                g_lines.append(g_line(sname, label, st))
            if label != "theirs" and st.get("n_grip_iou"):
                ps = pair_stats(grows, "th", who)
                js[f"grip {sname} | {label} vs theirs"] = ps
                gp_lines.append(gp_line(sname, f"{label} vs theirs", ps))
    md += ["Gripper ROI = dilate(our gripper segmentation U their mask within 40 px of it, 41x41); frames with >= 200 px of our gripper and >20 edge px in the ROI:", "",
           md_table(G_HDR, g_lines), "", md_table(GP_HDR, gp_lines), ""]
    return "\n".join(md), js


LEAD_HDR = ["subset", "method", "n", "lead_ms (shift) p10/p50/p90", "lead_ms mean", "frac lead>0", "lead_px (shift) p10/p50/p90", "lead_px (centroid) p10/p50/p90",
            "|shift| px p50", "shift gain IoU p50", "perp_px (shift) p10/p50/p90"]


def lead_stats(rows, who):
    rr = [r for r in rows if r.get(f"{who}_lead_ms") is not None]
    o = dict(n=len(rr))
    if not rr:
        return o
    lm = [r[f"{who}_lead_ms"] for r in rr]
    o["lead_ms_p10_p50_p90"], _ = pct(lm)
    o["lead_ms_mean"] = round(float(np.mean(lm)), 2)
    o["frac_lead_pos"] = round(float(np.mean([x > 0 for x in lm])), 4)
    o["lead_s_px_p10_p50_p90"], _ = pct([r[f"{who}_lead_s_px"] for r in rr])
    o["lead_c_px_p10_p50_p90"], _ = pct([r[f"{who}_lead_c_px"] for r in rr if r.get(f"{who}_lead_c_px") is not None])
    o["shift_abs_px_p50"] = round(float(np.median([np.hypot(r[f"{who}_sdx"], r[f"{who}_sdy"]) for r in rr])), 2)
    o["shift_gain_p50"] = round(float(np.median([r[f"{who}_shift_gain"] for r in rr if r.get(f"{who}_shift_gain") is not None])), 4)
    perp = [r[f"{who}_sdx"] * (-r["mv_dy"]) + r[f"{who}_sdy"] * r["mv_dx"] for r in rr]
    o["perp_px_p10_p50_p90"], _ = pct(perp)
    o["abs_perp_px_p50"] = round(float(np.median(np.abs(perp))), 2)
    return o


def lead_line(subset, name, st):
    return [subset, name, st["n"], fmt3(st.get("lead_ms_p10_p50_p90"), 1), fmt3(st.get("lead_ms_mean"), 1), fmt3(st.get("frac_lead_pos")),
            fmt3(st.get("lead_s_px_p10_p50_p90"), 1), fmt3(st.get("lead_c_px_p10_p50_p90"), 1), fmt3(st.get("shift_abs_px_p50"), 1), fmt3(st.get("shift_gain_p50")),
            fmt3(st.get("perp_px_p10_p50_p90"), 1)]


def motion_section(rows, title, split_calib):
    """Residual along the EE image-motion direction on moving frames (EE image speed >= 30 px/s)."""
    mv = [r for r in rows if r["moving"] and (r.get("img_speed_pxps") or 0) >= 30]
    md = [f"### {title}", "",
          f"{len(mv)} usable moving frames (EE >= 0.1 m/s and EE image speed >= 30 px/s).  lead = signed displacement of the mask relative to GT along the EE image-motion "
          "direction (best rigid shift at half res with parabolic sub-pixel refinement, +-150 px window; centroid variant also given); lead_ms = lead_px / EE image speed.  Positive = mask ahead of the image "
          "= rendered robot state LATER than the frame; negative = state earlier.  perp = displacement perpendicular to the motion (calibration/geometry, not timing).  "
          f"their_state_minus_frame_ms = h5 robot_state time of step k minus our capture time (estimated_capture + dt_ms) of frame k.", ""]
    js = {}
    lines = []
    bins = [("all moving", lambda r: True), ("0.1-0.2 m/s", lambda r: r["ee_speed"] < 0.2), ("0.2-0.3 m/s", lambda r: 0.2 <= r["ee_speed"] < 0.3),
            (">=0.3 m/s", lambda r: r["ee_speed"] >= 0.3), ("img speed 30-100 px/s", lambda r: r["img_speed_pxps"] < 100),
            ("img speed 100-200 px/s", lambda r: 100 <= r["img_speed_pxps"] < 200), ("img speed >=200 px/s", lambda r: r["img_speed_pxps"] >= 200)]
    for bname, pred in bins:
        br = [r for r in mv if pred(r)]
        for label, who, grows in method_groups(br, split_calib):
            st = lead_stats(grows, who)
            js[f"{bname} | {label}"] = st
            if st["n"]:
                lines.append(lead_line(bname, label, st))
    md += [md_table(LEAD_HDR, lines), ""]
    # per lab theirs
    ll = []
    for lab in sorted(set(r["lab"] for r in mv)):
        lr = [r for r in mv if r["lab"] == lab]
        for label, who, grows in method_groups(lr, split_calib):
            st = lead_stats(grows, who)
            js[f"lab {lab} | {label}"] = st
            if st["n"] >= 5:
                ll.append(lead_line(lab, label, st))
    md += ["Per lab (n >= 5):", "", md_table(LEAD_HDR, ll), ""]
    sm = [r["their_state_minus_frame_ms"] for r in mv if r.get("their_state_minus_frame_ms") is not None]
    js["their_state_minus_frame_ms_p10_p50_p90"], _ = pct(sm)
    js["their_state_minus_frame_ms_mean"] = round(float(np.mean(sm)), 2) if sm else None
    sm_all = [r["their_state_minus_frame_ms"] for r in rows if r.get("their_state_minus_frame_ms") is not None]
    js["their_state_minus_frame_ms_all_frames_p10_p50_p90"], _ = pct(sm_all)
    # correlation lead_ms vs state gap and lead_px vs img speed (theirs)
    try:
        from scipy.stats import spearmanr, pearsonr
        tr = [r for r in mv if r.get("th_lead_s_px") is not None]
        if len(tr) > 10:
            rho, _ = spearmanr([r["img_speed_pxps"] for r in tr], [r["th_lead_s_px"] for r in tr])
            js["spearman_theirs_lead_px_vs_img_speed"] = round(float(rho), 4)
            orr = [r for r in mv if r.get("our_lead_s_px") is not None]
            rho2, _ = spearmanr([r["img_speed_pxps"] for r in orr], [r["our_lead_s_px"] for r in orr])
            js["spearman_ours_lead_px_vs_img_speed"] = round(float(rho2), 4)
            # linear fit lead_px = a * img_speed (s) -> slope = effective time offset in s
            x = np.array([r["img_speed_pxps"] for r in tr]); y = np.array([r["th_lead_s_px"] for r in tr])
            js["theirs_fit_lead_px_per_pxps_slope_ms"] = round(float(1000 * (x @ y) / (x @ x)), 2)
            x2 = np.array([r["img_speed_pxps"] for r in orr]); y2 = np.array([r["our_lead_s_px"] for r in orr])
            js["ours_fit_lead_px_per_pxps_slope_ms"] = round(float(1000 * (x2 @ y2) / (x2 @ x2)), 2)
    except Exception as e:  # noqa: BLE001
        js["corr_error"] = repr(e)
    md += [f"their_state_minus_frame_ms on these moving frames p10/p50/p90 = {fmt3(js['their_state_minus_frame_ms_p10_p50_p90'], 1)} (mean {js['their_state_minus_frame_ms_mean']}); "
           f"all usable frames: {fmt3(js['their_state_minus_frame_ms_all_frames_p10_p50_p90'], 1)}.  Spearman(lead_px, img_speed): theirs {js.get('spearman_theirs_lead_px_vs_img_speed')}, "
           f"ours {js.get('spearman_ours_lead_px_vs_img_speed')}.  Zero-intercept slope lead_px / img_speed -> effective time offset: theirs {js.get('theirs_fit_lead_px_per_pxps_slope_ms')} ms, "
           f"ours {js.get('ours_fit_lead_px_per_pxps_slope_ms')} ms.", ""]
    return "\n".join(md), js


def per_cam(rows, key="th_iou", agg=np.median):
    d = defaultdict(list)
    for r in rows:
        if r.get(key) is not None:
            d[(r["uuid"], r["serial"])].append(r[key])
    return {k: float(agg(v)) for k, v in d.items()}


def _group(d, lab_of_key):
    g = defaultdict(list)
    for k, v in d.items():
        g[lab_of_key[k]].append(v)
    return g


def cmd_aggregate(args):
    OUT.mkdir(parents=True, exist_ok=True)
    bench = read_rows(OUT / "metrics_benchmark.csv")
    chunk_files = sorted((OUT / "scale_chunks").glob("chunk_*.csv"))
    scale = [r for p in chunk_files for r in read_rows(p)]
    write_csv(OUT / "metrics_scale.csv", scale)
    log(f"bench rows {len(bench)}, scale rows {len(scale)} from {len(chunk_files)} chunks")
    overlap = json.load(open(OUT / "overlap.json")) if (OUT / "overlap.json").exists() else {}
    infos = [i for p in sorted((OUT / "scale_chunks").glob("chunk_*_infos.json")) for i in json.load(open(p))]
    errs = [i for i in infos if i.get("error")]
    skipped = [s for i in infos for s in i.get("skipped", [])]
    old_mp4 = [o for i in infos for o in i.get("old_mp4", [])]
    bench_infos = json.load(open(OUT / "bench_infos.json")) if (OUT / "bench_infos.json").exists() else []
    ver = [v for i in bench_infos for v in i.get("their_verify", [])]

    bu = [r for r in bench if r["usable"] and r["their_ok"]]
    su = [r for r in scale if r["usable"] and r["their_ok"]]
    su_ext = [r for r in scale if r["usable_ext"] and r["their_ok"]]
    md_b, js_b = summarize_set(bu, "Benchmark (out/diag/gtmask; 10 held-out frames per camera; ours_v2 on all episodes; ours_old = old pipeline _rend.png)")
    md_s, js_s = summarize_set(su, "At scale (out/gt; up to 16 steps per camera; GT status ok/single/low_conf, GT >= 3000 px)", split_calib=True)
    md_se, js_se = summarize_set(su_ext, "At scale, extended status filter (+ render_far_off / render_missing_robot)", split_calib=True)
    md_mb, js_mb = motion_section(bu, "Motion-direction residual, benchmark", False)
    md_ms, js_ms = motion_section(su, "Motion-direction residual, at scale", True)

    # old-csv cross-check on the benchmark
    xc = [(r["old_iou"], r["old_iou_csv"], r["old_r2g"], r["old_r2g_csv"]) for r in bu if r.get("old_iou") is not None and r.get("old_iou_csv") is not None]
    old_xcheck = dict(n=len(xc), max_abs_d_iou=round(max(abs(a - b) for a, b, _, _ in xc), 5) if xc else None,
                      max_abs_d_r2g=round(max(abs(c - d) for _, _, c, d in xc), 4) if xc else None)

    # per-camera distribution (theirs) over the whole overlap
    cam_th = per_cam(su, "th_iou")
    cam_our = per_cam(su, "our_iou")
    cam_old = per_cam(su, "old_iou")
    cam_th_r2g = per_cam(su, "th_r2g")
    cam_calib = {(r["uuid"], r["serial"]): r["calib"] for r in su}
    cam_loss = {(r["uuid"], r["serial"]): r["their_loss"] for r in su}
    cam_lab = {(r["uuid"], r["serial"]): r["lab"] for r in su}
    dist = dict(n_cams=len(cam_th), th_cam_median_iou_p10_p50_p90=pct(list(cam_th.values()))[0],
                th_cam_median_r2g_p10_p50_p90=pct(list(cam_th_r2g.values()))[0],
                th_cams_median_iou_lt_0_5=sum(v < 0.5 for v in cam_th.values()), th_cams_median_iou_lt_0_7=sum(v < 0.7 for v in cam_th.values()),
                th_cams_median_iou_ge_0_85=sum(v >= 0.85 for v in cam_th.values()),
                our_v2_cams=dict(n=sum(1 for k in cam_our if cam_calib[k] == "v2"),
                                 median_iou_p10_p50_p90=pct([v for k, v in cam_our.items() if cam_calib[k] == "v2"])[0],
                                 theirs_same_cams_p10_p50_p90=pct([cam_th[k] for k in cam_our if cam_calib[k] == "v2"])[0],
                                 cams_ours_better=sum(cam_our[k] > cam_th[k] for k in cam_our if cam_calib[k] == "v2"),
                                 cams_theirs_better=sum(cam_our[k] < cam_th[k] for k in cam_our if cam_calib[k] == "v2")),
                our_default_cams=dict(n=sum(1 for k in cam_our if cam_calib[k] == "default"),
                                      median_iou_p10_p50_p90=pct([v for k, v in cam_our.items() if cam_calib[k] == "default"])[0],
                                      theirs_same_cams_p10_p50_p90=pct([cam_th[k] for k in cam_our if cam_calib[k] == "default"])[0],
                                      cams_ours_better=sum(cam_our[k] > cam_th[k] for k in cam_our if cam_calib[k] == "default"),
                                      cams_theirs_better=sum(cam_our[k] < cam_th[k] for k in cam_our if cam_calib[k] == "default")),
                our_old_cams=dict(n=len(cam_old), median_iou_p10_p50_p90=pct(list(cam_old.values()))[0],
                                  theirs_same_cams_p10_p50_p90=pct([cam_th[k] for k in cam_old])[0],
                                  ours_default_same_cams_p10_p50_p90=pct([cam_our[k] for k in cam_old if k in cam_our])[0],
                                  cams_old_better_than_theirs=sum(cam_old[k] > cam_th[k] for k in cam_old), cams_theirs_better_than_old=sum(cam_old[k] < cam_th[k] for k in cam_old)),
                per_lab_th_cam_median_iou={lab: dict(n=len(v), p10_p50_p90=pct(v)[0], lt_0_5=sum(x < 0.5 for x in v))
                                           for lab, v in sorted(_group(cam_th, cam_lab).items())})
    try:
        from scipy.stats import spearmanr
        ks = [k for k in cam_th if cam_loss.get(k) is not None]
        rho, pv = spearmanr([cam_loss[k] for k in ks], [cam_th[k] for k in ks])
        dist["spearman_their_loss_vs_their_cam_median_iou"] = dict(rho=round(float(rho), 4), p=float(pv), n=len(ks))
        lo = [cam_th[k] for k in ks if cam_loss[k] <= 0.05]
        mid = [cam_th[k] for k in ks if 0.05 < cam_loss[k] <= 0.07]
        hi = [cam_th[k] for k in ks if cam_loss[k] > 0.07]
        dist["th_cam_median_iou_by_loss"] = {"loss<=0.05": dict(n=len(lo), p10_p50_p90=pct(lo)[0]), "0.05<loss<=0.07": dict(n=len(mid), p10_p50_p90=pct(mid)[0]),
                                             "loss>0.07": dict(n=len(hi), p10_p50_p90=pct(hi)[0])}
    except Exception as e:  # noqa: BLE001
        dist["spearman_error"] = repr(e)
    dist["worst10_their_cams_by_median_iou"] = [dict(uuid=k[0], serial=k[1], lab=cam_lab[k], th_med_iou=round(v, 3), our_med_iou=round(cam_our.get(k, float("nan")), 3),
                                                     calib=cam_calib[k], their_loss=round(cam_loss[k], 4) if cam_loss.get(k) is not None else None)
                                                for k, v in sorted(cam_th.items(), key=lambda kv: kv[1])[:10]]
    dist["worst10_our_cams_by_median_iou"] = [dict(uuid=k[0], serial=k[1], lab=cam_lab[k], our_med_iou=round(v, 3), th_med_iou=round(cam_th.get(k, float("nan")), 3),
                                                   calib=cam_calib[k]) for k, v in sorted(cam_our.items(), key=lambda kv: kv[1])[:10]]
    status_counts = Counter(r["status"] for r in scale)
    summary = dict(generated=time.strftime("%Y-%m-%d %H:%M:%S"), overlap=overlap,
                   frame_mapping=dict(theirs="mask.mkv / rgb.mp4 frame k == h5 step k (n_video_frames == traj_len - 1 for all 1226 cameras in meta.json; traj_len == our h5 step count); "
                                             "mask.mkv container frame count == meta.json frames and indexed decode == sequential decode on all verified frames",
                                      ours="MP4 frame k == h5 step k, last step has no frame (README); robot state interpolated at estimated_capture[k] + time_offset_ms",
                                      ours_old="out/<uuid>/<serial>/mask.mp4 frame k == step k, 15 fps H.264, threshold 128; frame counts in scale infos old_mp4"),
                   bench=dict(n_rows=len(bench), n_usable_with_theirs=len(bu), n_cams=len(set((r["uuid"], r["serial"]) for r in bu)),
                              n_eps=len(set(r["uuid"] for r in bu)), status_counts=dict(Counter(r["status"] for r in bench)),
                              n_with_old=sum(1 for r in bu if r.get("old_iou") is not None), old_csv_crosscheck=old_xcheck,
                              their_mask_verify=dict(cams=len(ver), compared=sum(v["compared"] for v in ver), mismatch=sum(v["mismatch"] for v in ver),
                                                     count_ok=sum(v["n_cap"] == v["n_meta"] for v in ver)),
                              calib_v2_md5={i["uuid"]: i.get("calib_v2_md5") for i in bench_infos}, blocks=js_b, motion=js_mb),
                   scale=dict(n_rows=len(scale), n_usable_with_theirs=len(su), n_usable_ext=len(su_ext), status_counts=dict(status_counts),
                              n_cams=len(set((r["uuid"], r["serial"]) for r in su)), n_eps=len(set(r["uuid"] for r in su)),
                              n_cams_v2=len(set((r["uuid"], r["serial"]) for r in su if r["calib"] == "v2")),
                              n_cams_old=len(set((r["uuid"], r["serial"]) for r in su if r.get("old_iou") is not None)),
                              n_eps_old=len(set(r["uuid"] for r in su if r.get("old_iou") is not None)), n_frames_old=sum(1 for r in su if r.get("old_iou") is not None),
                              old_mp4_frame_count_eq_steps_minus_1=sum(1 for o in old_mp4 if o["n_frames"] == o["n_steps"] - 1), old_mp4_cams=len(old_mp4),
                              old_mp4_other_counts=[o for o in old_mp4 if o["n_frames"] != o["n_steps"] - 1][:20],
                              n_their_frames_missing=sum(1 for r in scale if not r["their_ok"]),
                              n_their_count_mismatch_cams=len(set((r["uuid"], r["serial"]) for r in scale if not r["their_count_ok"])),
                              episode_errors=errs, skipped_cams=skipped, blocks=js_s, blocks_ext=js_se, per_camera=dist, motion=js_ms))
    json.dump(summary, open(OUT / "summary.json", "w"), indent=1, default=str)

    md = ["# droid-normals (theirs) vs our renders (ours_v2 / ours_default / ours_old), scored on SAM3 GT robot masks", "",
          f"Generated {summary['generated']}.  Files: metrics_benchmark.csv, metrics_scale.csv, summary.json, overlap.json, overlap_cams.csv, "
          "grid_benchmark.jpg, worst_theirs.jpg, worst_ours.jpg, clips/.", "",
          "Conventions: px at 1280x720.  IoU = mask IoU vs GT.  r2g = mean distance render-edge -> nearest GT edge (px); g2r = GT edge -> nearest render edge.  "
          "Frames: GT status in ok/single/low_conf and GT >= 3000 px, their mask present.  'moving' = EE speed >= 0.1 m/s (central difference of h5 cartesian_position over "
          "robot_timestamp_nanos); 'closed' = gripper_position > 0.45.  Methods: theirs = droid-normals mask.mkv; ours_v2 = fresh render with calib_refined_v2.json; "
          "ours_default = fresh render with the default calibration (official superset extrinsics + 37 ms latency), i.e. episodes without a v2 file; "
          "ours_old = OLD-geometry pipeline renders (benchmark: out/diag/gtmask _rend.png; at scale: out/<uuid>/<serial>/mask.mp4 of the 220 episodes with .done and no .done_v2).", "",
          "## 0. Frame <-> step mapping (verified)", "",
          f"- theirs: {summary['frame_mapping']['theirs']}.", f"- ours: {summary['frame_mapping']['ours']}.",
          f"- ours_old: {summary['frame_mapping']['ours_old']}; at scale {summary['scale']['old_mp4_frame_count_eq_steps_minus_1']}/{summary['scale']['old_mp4_cams']} old mask.mp4 have frames == steps-1"
          + (f" (others: {summary['scale']['old_mp4_other_counts']})" if summary['scale']['old_mp4_other_counts'] else "") + ".", "",
          "## 1. Overlap", ""]
    if overlap:
        md += [f"- their manifest: {overlap['their_rows']} cameras / {overlap['their_uuids']} episodes; all {overlap['their_uuids_in_selection']} episodes are in our 999 selection; "
               f"{overlap['their_pairs_not_matching_our_ext_cams']} of their cameras are not one of our exterior cameras.",
               f"- our selection: {overlap['selected_eps']} episodes / {overlap['selected_ext_cams']} exterior cameras; in theirs {overlap['selected_cams_in_theirs']}, "
               f"not in theirs {overlap['selected_cams_dropped_by_them']}; {overlap['selected_eps_with_no_cam_in_theirs']} episodes have no camera in theirs "
               f"(episodes with 0/1/2 cameras missing: {overlap['dropped_per_episode']}).",
               f"- their cameras with (a) benchmark GT: {overlap['their_cams_with_bench_gt']} cameras in {overlap['their_eps_with_bench_gt']} of the {overlap['bench_eps_total']} benchmark episodes "
               f"(benchmark has {overlap['bench_cams_total']} exterior cameras); (b) at-scale GT: {overlap['their_cams_with_scale_gt']} cameras.",
               f"- their cameras in episodes with calib_refined_v2.json: {overlap['their_cams_with_v2_calib']} cameras / {overlap['their_eps_with_v2_calib']} episodes "
               f"(we have v2 for {overlap['eps_with_v2_calib_total']} episodes in total).",
               f"- their per_cam_loss p10/p50/p90/max: {overlap['their_loss_pcts']}.", "",
               md_table(["lab", "selected eps", "eps in theirs", "selected ext cams", "in theirs", "not in theirs", "not in theirs %", "their cams w/ bench GT", "their cams w/ scale GT", "their cams w/ v2"],
                        [[l, d["selected_eps"], d["eps_in_theirs"], d["selected_cams"], d["in_theirs"], d["dropped_by_them"], f"{100 * d['dropped_by_them'] / max(d['selected_cams'], 1):.0f}",
                          d["their_with_bench_gt"], d["their_with_scale_gt"], d["their_with_v2"]] for l, d in overlap["by_lab"].items()]), ""]
    md += ["## 2. Benchmark", "",
           f"{summary['bench']['n_usable_with_theirs']} usable frames, {summary['bench']['n_cams']} cameras, {summary['bench']['n_eps']} episodes; benchmark GT status counts {summary['bench']['status_counts']}; "
           f"ours_old available on {summary['bench']['n_with_old']} of them (re-scored _rend.png vs out/diag/residual/metrics.csv: n={old_xcheck['n']}, max |dIoU| {old_xcheck['max_abs_d_iou']}, max |dr2g| {old_xcheck['max_abs_d_r2g']}).  "
           f"Their mask.mkv indexed decode == sequential decode on {summary['bench']['their_mask_verify']['compared']} frames ({summary['bench']['their_mask_verify']['mismatch']} mismatches); "
           f"container frame count == meta.json frames for {summary['bench']['their_mask_verify']['count_ok']}/{summary['bench']['their_mask_verify']['cams']} cameras.", "",
           md_b, md_mb,
           "## 3. At scale", "",
           f"{summary['scale']['n_rows']} GT frames in their cameras, {summary['scale']['n_usable_with_theirs']} usable ({summary['scale']['n_usable_ext']} with the extended filter), "
           f"{summary['scale']['n_cams']} cameras ({summary['scale']['n_cams_v2']} with v2 calib, {summary['scale']['n_cams_old']} with old renders in {summary['scale']['n_eps_old']} episodes / {summary['scale']['n_frames_old']} frames) "
           f"in {summary['scale']['n_eps']} episodes; GT status counts {summary['scale']['status_counts']}; their frames missing {summary['scale']['n_their_frames_missing']}; "
           f"episode errors {len(errs)}; skipped cams {len(skipped)}.", "",
           md_s, md_se, md_ms,
           "### Per-camera distribution (median over the usable frames of each camera)", "", "```", json.dumps(dist, indent=1, default=str), "```", ""]
    notes = Path(args.notes) if args.notes else None
    if notes and notes.exists():
        md += ["", open(notes).read()]
    open(OUT / "summary.md", "w").write("\n".join(md))
    log("wrote summary.md / summary.json")
    if not args.no_images:
        make_visuals(bu, su, args)



# ----------------------------------------------------------------------------- visuals

def real_frame(uuid, serial, step, wh=None):
    p = BENCH_ROOT / uuid / serial / f"{step:04d}_real.png"
    im = cv2.imread(str(p), cv2.IMREAD_COLOR) if p.exists() else None
    if im is None:
        cap = cv2.VideoCapture(str(ROOT / "data" / uuid / "recordings/MP4" / f"{serial}.mp4"))
        cap.set(cv2.CAP_PROP_POS_FRAMES, int(step))
        ok, im = cap.read()
        cap.release()
        if not ok:
            im = np.zeros((720, 1280, 3), np.uint8)
    if wh is not None and (im.shape[1], im.shape[0]) != tuple(wh):
        im = cv2.resize(im, tuple(wh), interpolation=cv2.INTER_AREA)
    return im


def draw_contours(img, mask, color, thick=1):
    if mask is None or not mask.any():
        return img
    cs, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
    cv2.drawContours(img, cs, -1, color, thick)
    return img


def tile(real, gt, theirs, ours, text, size=(640, 360)):
    im = cv2.resize(real, size, interpolation=cv2.INTER_AREA)
    rs = lambda m: None if m is None else (cv2.resize(m.astype(np.uint8) * 255, size, interpolation=cv2.INTER_AREA) >= 128)  # noqa: E731
    draw_contours(im, rs(gt), (0, 220, 0), 1)       # GT green
    draw_contours(im, rs(theirs), (0, 0, 255), 1)   # theirs red (BGR)
    draw_contours(im, rs(ours), (255, 128, 0), 1)   # ours blue
    put_lines(im, text)
    return im


def put_lines(im, lines, scale=0.42, dy=15):
    """White text on a darkened band (OpenCV 5 renders thick and thin strokes with different glyph advances, so no outline trick)."""
    if not lines:
        return im
    h = 6 + dy * len(lines)
    im[:h] = (im[:h].astype(np.float32) * 0.35).astype(np.uint8)
    y = dy - 2
    for line in lines:
        cv2.putText(im, line, (5, y), cv2.FONT_HERSHEY_SIMPLEX, scale, (255, 255, 255), 1, cv2.LINE_AA)
        y += dy
    return im


class FrameRenderer:
    """Fresh masks (ours + theirs + GT + real) for arbitrary (uuid, serial, step); one EpisodeSession per episode."""

    def __init__(self):
        import render_episode as RE
        RE.VERBOSE = False
        self.RE = RE
        self.sess = None
        self.uuid = None
        self.their = their_index()

    def session(self, uuid):
        if self.uuid != uuid:
            if self.sess is not None:
                try:
                    self.sess.rr.close()
                except Exception:  # noqa: BLE001
                    pass
            self.sess = self.RE.EpisodeSession(str(ROOT / "data" / uuid), wrist=False)
            self.uuid = uuid
        return self.sess

    def ours(self, uuid, serial, step):
        s = self.session(uuid)
        wh = tuple(s.mp4_wh.get(serial, tuple(s.wh[serial])))
        T = s.set_step(serial, step, interp=True)
        _, _, seg = s.rr.render_raw(T, s.K_mp4[serial], wh)
        return seg >= 0

    def theirs(self, uuid, serial, steps):
        r = self.their.get((uuid, serial))
        if r is None:
            return {}
        tm = TheirMasks(DN / r["path"], needed=steps)
        return {k: tm.get(k) for k in steps}

    def gt(self, uuid, serial, step, bench=False):
        p = (BENCH_ROOT / uuid / serial / f"{step:04d}_gt.png") if bench else (GT_ROOT / uuid / serial / f"{step:04d}.png")
        m = cv2.imread(str(p), cv2.IMREAD_GRAYSCALE)
        return None if m is None else m > 128


def row_text(r):
    t = [f"{r['uuid'][:40]} {r['serial']} step {r['step']}",
         f"[{r['status']}] {r['lab']} v={r.get('ee_speed', 0):.2f} m/s g={r.get('g', 0):.2f} calib {r['calib']} dt {r.get('dt_ms')} ms their_loss {fmt3(r.get('their_loss'))}",
         f"THEIRS red: IoU {fmt3(r.get('th_iou'))} r2g {fmt3(r.get('th_r2g'), 1)} px | OURS blue: IoU {fmt3(r.get('our_iou'))} r2g {fmt3(r.get('our_r2g'), 1)} px | GT green"]
    if r.get("old_iou") is not None:
        t.append(f"ours_old (not drawn): IoU {fmt3(r.get('old_iou'))} r2g {fmt3(r.get('old_r2g'), 1)} px")
    return t


def sheet(rows, fr, out_path, title, bench):
    tiles = []
    by_uuid = defaultdict(list)
    for r in rows:
        by_uuid[r["uuid"]].append(r)
    for uuid, rr in by_uuid.items():
        for r in rr:
            th = fr.theirs(uuid, r["serial"], [r["step"]]).get(r["step"])
            ou = fr.ours(uuid, r["serial"], r["step"])
            gt = fr.gt(uuid, r["serial"], r["step"], bench=bench)
            real = real_frame(uuid, r["serial"], r["step"], wh=(gt.shape[1], gt.shape[0]) if gt is not None else None)
            r["_tile"] = tile(real, gt, th, ou, row_text(r))
    tiles = [r["_tile"] for r in rows if "_tile" in r]
    while len(tiles) % 3:
        tiles.append(np.zeros_like(tiles[0]))
    grid = np.vstack([np.hstack(tiles[i:i + 3]) for i in range(0, len(tiles), 3)])
    head = np.full((28, grid.shape[1], 3), 30, np.uint8)
    cv2.putText(head, title, (8, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1, cv2.LINE_AA)
    cv2.imwrite(str(out_path), np.vstack([head, grid]), [cv2.IMWRITE_JPEG_QUALITY, 90])
    log(f"wrote {out_path}")


def pick_diverse(rows, n=12):
    """Diverse benchmark frames: one per lab (median their-IoU frame), then closed-gripper, fast, static frames."""
    chosen, seen = [], set()
    by_lab = defaultdict(list)
    for r in rows:
        by_lab[r["lab"]].append(r)
    for lab in sorted(by_lab):
        rr = sorted(by_lab[lab], key=lambda r: r.get("th_iou") or 0)
        r = rr[len(rr) // 2]
        chosen.append(r)
        seen.add((r["uuid"], r["serial"], r["step"]))
    pools = [[r for r in rows if r["closed"]], [r for r in rows if (r.get("ee_speed") or 0) >= 0.25], [r for r in rows if not r["moving"]],
             [r for r in rows if (r.get("th_iou") or 1) < 0.6], [r for r in rows if (r.get("our_iou") or 1) < 0.6]]
    i = 0
    while len(chosen) < n and any(pools):
        pool = pools[i % len(pools)]
        i += 1
        pool.sort(key=lambda r: r.get("th_iou") or 0)
        for r in pool[len(pool) // 2:] + pool[: len(pool) // 2]:
            k = (r["uuid"], r["serial"], r["step"])
            if k not in seen and sum(1 for c in chosen if c["uuid"] == r["uuid"]) < 2:
                chosen.append(r)
                seen.add(k)
                break
    return chosen[:n]


def make_clip(fr, uuid, serial, start, n, out_path, label):
    import imageio
    sess = fr.session(uuid)
    speed, gs = ee_speed_and_gripper(ROOT / "data" / uuid)
    th = fr.theirs(uuid, serial, list(range(start, start + n)))
    cap = cv2.VideoCapture(str(ROOT / "data" / uuid / "recordings/MP4" / f"{serial}.mp4"))
    for _ in range(start):
        if not cap.grab():
            break
    w = imageio.get_writer(str(out_path), fps=15, codec="libx264", quality=7, macro_block_size=1, pixelformat="yuv420p",
                           ffmpeg_params=["-movflags", "+faststart"])
    size = (640, 360)

    def overlay(real, m, color):
        im = real.copy()
        if m is not None:
            ms = cv2.resize(m.astype(np.uint8) * 255, size, interpolation=cv2.INTER_AREA) >= 128
            im[ms] = (0.55 * im[ms] + 0.45 * np.array(color, np.float32)).astype(np.uint8)
            draw_contours(im, ms, color, 1)
        return im

    for k in range(n):
        step = start + k
        ok, real = cap.read()
        if not ok or step >= sess.n - 1:
            break
        real = cv2.resize(real, size, interpolation=cv2.INTER_AREA)
        ou = fr.ours(uuid, serial, step)
        a, b, c = real.copy(), overlay(real, th.get(step), (0, 0, 255)), overlay(real, ou, (255, 128, 0))
        for im, t in ((a, f"{label}: {uuid[:30]} {serial} step {step} v={speed[step]:.2f} m/s g={gs[step]:.2f}"), (b, "THEIRS (droid-normals mask.mkv)"),
                      (c, f"OURS ({'v2' if sess.calib_version == 2 else 'default'} calib, dt {sess.dt_ms:+.0f} ms)")):
            put_lines(im, [t])
        w.append_data(cv2.cvtColor(np.hstack([a, b, c]), cv2.COLOR_BGR2RGB))
    w.close()
    cap.release()
    log(f"wrote {out_path}")


def choose_clip(su, kind, fr, n=45):
    """Representative camera (their median IoU closest to the overall median among cams with >= 3 frames of the kind) + best window."""
    if kind == "static":
        pred = lambda r: not r["moving"]  # noqa: E731
    elif kind == "fast":
        pred = lambda r: (r.get("ee_speed") or 0) >= 0.25  # noqa: E731
    else:
        pred = lambda r: r["closed"]  # noqa: E731
    cams = defaultdict(list)
    for r in su:
        cams[(r["uuid"], r["serial"])].append(r)
    med_all = float(np.median([r["th_iou"] for r in su if r.get("th_iou") is not None]))
    cands = []
    for k, rr in cams.items():
        kk = [r for r in rr if pred(r)]
        if len(kk) >= 3 and all(r.get("th_iou") is not None and r.get("our_iou") is not None for r in kk):
            cands.append((abs(float(np.median([r["th_iou"] for r in kk])) - med_all), k, kk))
    if not cands:
        return None
    cands.sort(key=lambda c: c[0])
    _, (uuid, serial), kk = cands[0]
    speed, gs = ee_speed_and_gripper(ROOT / "data" / uuid)
    sess = fr.session(uuid)
    N = sess.n - 1
    n = min(n, N)
    if kind == "static":
        score = (speed < 0.05).astype(float)
    elif kind == "fast":
        score = speed
    else:
        score = (gs > CLOSED_G).astype(float)
    # prefer windows around the usable GT steps of that kind (robot in view there)
    steps = np.array([r["step"] for r in kk])
    inview = np.zeros(len(speed))
    for s in steps:
        inview[max(0, s - 30):s + 30] = 1
    best, best_s = -1, 0
    for s in range(0, N - n + 1):
        v = float((score[s:s + n] * (0.5 + inview[s:s + n])).sum())
        if v > best:
            best, best_s = v, s
    return uuid, serial, best_s, n


def make_visuals(bu, su, args):
    fr = FrameRenderer()
    if bu:
        sheet(pick_diverse(bu, 12), fr, OUT / "grid_benchmark.jpg", "benchmark frames: GT green | theirs (droid-normals) red | ours (v2) blue", bench=True)
    pool = [r for r in su if r.get("th_iou") is not None and r.get("our_iou") is not None]
    worst_th = sorted(pool, key=lambda r: r["th_iou"])[:12]
    worst_ou = sorted(pool, key=lambda r: r["our_iou"])[:12]
    sheet(worst_th, fr, OUT / "worst_theirs.jpg", "12 worst THEIR frames by IoU (at-scale GT): GT green | theirs red | ours blue", bench=False)
    sheet(worst_ou, fr, OUT / "worst_ours.jpg", "12 worst OUR frames by IoU (at-scale GT): GT green | theirs red | ours blue", bench=False)
    (OUT / "clips").mkdir(exist_ok=True)
    picks = {}
    for kind in ("static", "fast", "closed"):
        c = choose_clip(su, kind, fr)
        if c is None:
            continue
        uuid, serial, start, n = c
        picks[kind] = dict(uuid=uuid, serial=serial, start=start, n=n)
        make_clip(fr, uuid, serial, start, n, OUT / "clips" / f"clip_{kind}.mp4", kind)
    json.dump(picks, open(OUT / "clips" / "picks.json", "w"), indent=1)


# ----------------------------------------------------------------------------- main

def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("overlap")
    b = sub.add_parser("bench")
    b.add_argument("--workers", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", 4)))
    b.add_argument("--episodes", nargs="*", default=None)
    b.add_argument("--max-frames", type=int, default=0)
    b.add_argument("--out-suffix", default="")
    s = sub.add_parser("scale")
    s.add_argument("--chunk", type=int, required=True)
    s.add_argument("--nchunks", type=int, default=40)
    s.add_argument("--workers", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", 4)))
    s.add_argument("--episodes", nargs="*", default=None)
    a = sub.add_parser("aggregate")
    a.add_argument("--no-images", action="store_true")
    a.add_argument("--notes", default=None)
    args = ap.parse_args(argv)
    {"overlap": cmd_overlap, "bench": cmd_bench, "scale": cmd_scale, "aggregate": cmd_aggregate}[args.cmd](args)


if __name__ == "__main__":
    main()