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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
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
"""
I-BADAS Dataset Statistics and Visualization Script
====================================================
Generates a comprehensive suite of academic-quality figures describing the
I-BADAS (Intralogistics Bin Anomaly Detection And Segmentation) dataset.

All category names are discovered dynamically from every annotations.coco.json
found under the dataset root; the sample file is NOT treated as definitive.

Usage:
    python ibadas_stats.py --root /path/to/test --out figures/
    python ibadas_stats.py --root /path/to/test --train_root /path/to/train --out figures/

Dependencies:
    pip install numpy matplotlib scipy pycocotools tqdm Pillow
"""

import argparse
import json
import os
import sys
from collections import defaultdict
from pathlib import Path

#matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np

from matplotlib.offsetbox import OffsetImage, AnnotationBbox

from mpl_toolkits.mplot3d import proj3d
from scipy.spatial import ConvexHull, QhullError

from matplotlib.patches import Patch
from scipy.spatial import ConvexHull
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from matplotlib.lines import Line2D
from scipy.spatial.transform import Rotation
try:
    from PIL import Image as PILImage
except ImportError:
    PILImage = None

try:
    from pycocotools import mask as coco_mask_utils
    HAS_PYCOCOTOOLS = True
except ImportError:
    HAS_PYCOCOTOOLS = False

# ---------------------------------------------------------------------------
# Style constants
# ---------------------------------------------------------------------------
VIRIDIS = plt.cm.viridis
VIRIDIS_R = plt.cm.viridis_r
CLASS_ORDER = ["empty_clean", "empty_dirty", "non_empty"]
FONT_TITLE = {"fontsize": 13, "fontweight": "bold", "color": "#1a1a2e"}
FONT_LABEL = {"fontsize": 11, "color": "#1a1a2e"}
FONT_TICK  = {"fontsize": 9}
SPINE_COLOR = "#cccccc"
BG_AXES    = "#f9f9f9"

def style_ax(ax, title="", xlabel="", ylabel=""):
    ax.set_facecolor(BG_AXES)
    for spine in ax.spines.values():
        spine.set_edgecolor(SPINE_COLOR)
    ax.tick_params(colors="#444444", labelsize=9)
    ax.set_title(title, **FONT_TITLE, pad=10)
    if xlabel:
        ax.set_xlabel(xlabel, **FONT_LABEL)
    if ylabel:
        ax.set_ylabel(ylabel, **FONT_LABEL)
    ax.grid(True, linestyle="--", linewidth=0.5, alpha=0.6, color="#cccccc")
    ax.set_axisbelow(True)

def viridis_palette(n):
    return [VIRIDIS(i / max(n - 1, 1)) for i in range(n)]

def save(fig, path, dpi=180):
    fig.savefig(path, dpi=dpi, bbox_inches="tight",
                facecolor=fig.get_facecolor())
    plt.close(fig)
    print(f"  Saved: {path}")

# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------

def load_all_scenes(root: Path):
    """
    Walk the dataset root and load every annotations.coco.json.
    Returns a list of scene dicts:
      {
        'scene_id': str,
        'coco': dict,          # raw COCO JSON
        'cat_map': {id: name},
        'supercategory_map': {id: supercategory},
      }
    Also builds a global category registry across all files.
    """
    scene_dirs = sorted(root.iterdir()) if root.is_dir() else []
    scenes = []
    global_cats = {}  # name -> id (canonical, scene-independent)

    for sd in scene_dirs:
        ann_file = sd / "annotations.coco.json"
        if not ann_file.exists():
            continue
        with open(ann_file) as f:
            coco = json.load(f)

        cat_map = {}
        supercat_map = {}
        for c in coco.get("categories", []):
            cat_map[c["id"]] = c["name"]
            supercat_map[c["id"]] = c.get("supercategory", "unknown")
            global_cats[c["name"]] = c.get("supercategory", "unknown")

        scenes.append({
            "scene_id": sd.name,
            "coco": coco,
            "cat_map": cat_map,
            "supercat_map": supercat_map,
            "root": sd,
        })

    if not scenes:
        sys.exit(f"[ERROR] No annotations.coco.json files found under {root}")

    print(f"Loaded {len(scenes)} scenes.")
    print(f"Global categories discovered: {sorted(global_cats.keys())}")
    return scenes, global_cats

def aggregate(scenes):
    """
    Build flat lists and dicts for all aggregated statistics.
    """
    records = []    # one dict per image
    ann_records = []  # one dict per annotation

    for s in scenes:
        coco = s["coco"]
        cat_map = s["cat_map"]
        supercat_map = s["supercat_map"]
        img_map = {img["id"]: img for img in coco.get("images", [])}

        ann_by_img = defaultdict(list)
        for ann in coco.get("annotations", []):
            ann_by_img[ann["image_id"]].append(ann)

        for img in coco.get("images", []):
            rec = {
                "scene_id": s["scene_id"],
                "image_id": img["id"],
                "file_name": img["file_name"],
                "classification": img.get("classification", "unknown"),
                "box_type": img.get("box_type", "unknown"),
                "camera": img.get("camera", "unknown"),
                "robot": img.get("robot", False),
                "split": "good" if img["file_name"].startswith("good/") else "anomaly",
                "annotations": ann_by_img[img["id"]],
                "n_annotations": len(ann_by_img[img["id"]]),
            }
            records.append(rec)
            for ann in ann_by_img[img["id"]]:
                cat_name = cat_map.get(ann["category_id"], "unknown")
                ann_records.append({
                    "scene_id": s["scene_id"],
                    "image_id": img["id"],
                    "classification": rec["classification"],
                    "cat_name": cat_name,
                    "supercat": supercat_map.get(ann["category_id"], "unknown"),
                    "area": ann.get("area", 0),
                    "bbox": ann.get("bbox", [0, 0, 0, 0]),
                })

    return records, ann_records


def load_poses(scenes):
    """
    Load poses.json from each scene where available.
    Supports:

    1. [{"R": ..., "t": ...}, ...]
    2. {"id": {"R": ..., "t": ...}, ...}
    3. {"image.npy": [{"R": ..., "t": ...}], ...}
    """

    pose_records = []

    for s in scenes:
        poses_file = s["root"] / "poses.json"

        if not poses_file.exists():
            continue

        with open(poses_file) as f:
            poses = json.load(f)

        if isinstance(poses, list):
            iterable = []
            for idx, p in enumerate(poses):
                iterable.append((idx, p))

        elif isinstance(poses, dict):
            iterable = []
            for key, value in poses.items():
                if isinstance(value, list):
                    for p in value:
                        iterable.append((key, p))
                elif isinstance(value, dict):
                    iterable.append((key, value))
        else:
            continue

        for image_key, p in iterable:
            if not isinstance(p, dict):
                continue

            t = p.get("cam_t_m2c") or p.get("t") or p.get("translation") or [0, 0, 0]
            
            # Extract the rotation matrix
            R = p.get("cam_R_m2c") or p.get("R") or p.get("rotation")

            record = {
                "scene_id": s["scene_id"],
                "tx": t[0],
                "ty": t[1],
                "tz": t[2],
                "image_id": image_key,
            }
            
            # Safely add R if it exists in the JSON
            if R is not None:
                record["R"] = R
                
            pose_records.append(record)

    return pose_records

# ---------------------------------------------------------------------------
# Train data loading (reference statistics for train-referenced deltas)
# ---------------------------------------------------------------------------

def _resolve_train_image_path(task_dir, file_name):
    """
    Resolve the absolute image path of a train image. Tries, in order:
    <task_dir>/<file_name>, <task_dir>/rgb/<file_name>, <task_dir>/rgb/<basename>.
    Falls back to the first candidate if none exists.
    """
    candidates = [
        task_dir / file_name,
        task_dir / "rgb" / file_name,
        task_dir / "rgb" / Path(file_name).name,
    ]
    for c in candidates:
        if c.is_file():
            return str(c)
    return str(candidates[0])


def load_train_data(train_root):
    """
    Load the train split. Expected layout:

        <train_root>/[real/]<scene>/<task>/{annotations.coco.json, poses.json, rgb/, ...}

    Tasks of the same scene are pooled, so the train scene_id is the scene folder
    name (e.g. "000001") and matches the test scene_id.

    Returns (train_records, train_pose_records). Records carry '_abs_path'.
    Returns ([], []) if train_root is None or nothing is found.
    """
    if train_root is None:
        return [], []

    train_root = Path(train_root)
    if not train_root.is_dir():
        print(f"  [WARN] Train root not found: {train_root}")
        return [], []

    if (train_root / "real").is_dir():
        train_root = train_root / "real"

    train_records = []
    train_pose_records = []
    n_task_dirs = 0

    for scene_dir in sorted(p for p in train_root.iterdir() if p.is_dir()):
        # Task directories: sub-folders holding annotations; fall back to the
        # scene folder itself if it holds annotations directly.
        task_dirs = sorted(
            p for p in scene_dir.iterdir()
            if p.is_dir() and (p / "annotations.coco.json").exists()
        )
        if not task_dirs and (scene_dir / "annotations.coco.json").exists():
            task_dirs = [scene_dir]

        for task_dir in task_dirs:
            with open(task_dir / "annotations.coco.json") as f:
                coco = json.load(f)

            cat_map = {}
            supercat_map = {}
            for c in coco.get("categories", []):
                cat_map[c["id"]] = c["name"]
                supercat_map[c["id"]] = c.get("supercategory", "unknown")

            s = {
                "scene_id": scene_dir.name,
                "coco": coco,
                "cat_map": cat_map,
                "supercat_map": supercat_map,
                "root": task_dir,
            }

            recs, _ = aggregate([s])
            for r in recs:
                r["_abs_path"] = _resolve_train_image_path(task_dir, r["file_name"])
                r["_root"] = str(task_dir)
                r["task"] = task_dir.name
            train_records.extend(recs)
            train_pose_records.extend(load_poses([s]))
            n_task_dirs += 1

    print(f"  Train: {len(train_records)} images, {len(train_pose_records)} poses "
          f"from {n_task_dirs} task folders under {train_root}")
    return train_records, train_pose_records


def _train_reference_stats(train_records, train_pose_records):
    """
    Compute the train reference values used for the train-referenced deltas:
    mean intensity, translation centroid and mean rotation, per scene and global.
    """
    refs = {
        "scene_intensity_mean": {},
        "global_intensity_mean": None,
        "scene_translation_centroid": {},
        "global_translation_centroid": None,
        "scene_rotation_mean": {},
        "global_rotation_mean": None,
    }

    # Illumination
    scene_intensities = defaultdict(list)
    all_intensities = []
    if PILImage is not None:
        for r in train_records:
            p = Path(r.get("_abs_path", ""))
            if not p.is_file():
                continue
            try:
                img = np.asarray(PILImage.open(p).convert("L"))
                m = float(np.mean(img))
            except Exception:
                continue
            scene_intensities[r["scene_id"]].append(m)
            all_intensities.append(m)

    refs["scene_intensity_mean"] = {
        sc: float(np.mean(v)) for sc, v in scene_intensities.items() if v
    }
    if all_intensities:
        refs["global_intensity_mean"] = float(np.mean(all_intensities))

    # Pose
    scene_t = defaultdict(list)
    scene_r = defaultdict(list)
    all_t = []
    all_r = []
    for pose in train_pose_records:
        sc = pose["scene_id"]
        t = _pose_translation(pose)
        rot = _pose_rotation(pose)
        if t is not None:
            scene_t[sc].append(t)
            all_t.append(t)
        if rot is not None:
            scene_r[sc].append(rot)
            all_r.append(rot)

    refs["scene_translation_centroid"] = {
        sc: np.mean(v, axis=0) for sc, v in scene_t.items() if v
    }
    if all_t:
        refs["global_translation_centroid"] = np.mean(all_t, axis=0)

    refs["scene_rotation_mean"] = {
        sc: Rotation.concatenate(v).mean() for sc, v in scene_r.items() if v
    }
    if all_r:
        refs["global_rotation_mean"] = Rotation.concatenate(all_r).mean()

    return refs

# ---------------------------------------------------------------------------
# Scene metadata
# ---------------------------------------------------------------------------
SCENE_CAMERA = {1: "RealSense", 2: "Zivid", 3: "RealSense",
                4: "Zivid",     5: "RealSense", 6: "Zivid"}

LOAD_CARRIER_GROUPS = [
    ("KLT4314", [1, 2]),
    ("KLT4315", [3, 4]),
    ("SetBox",  [5, 6]),
]

SCENE_LOAD_CARRIER = {
    1: "KLT4314", 2: "KLT4314",
    3: "KLT4315", 4: "KLT4315",
    5: "SetBox",  6: "SetBox",
}

CAMERA_COLORS = {
    "RealSense": "#7EB8D4",
    "Zivid":     "#D4A87E",
}

BINARY_MAP = {
    "empty_clean": "Anomaly-Free",
    "empty_dirty": "Anomalous",
    "non_empty":   "Anomalous",
}

BINARY_CLASSES  = ["Anomaly-Free", "Anomalous"]

TRINARY_CLASSES = CLASS_ORDER   # ["empty_clean", "empty_dirty", "non_empty"]

PASTEL_GREEN  = "#48c16e80"
PASTEL_PURPLE = "#48237480"
PASTEL_TEAL   = "#1e9c8980"
PASTEL_YELLOW = "#eae51a80"

BIN_COLORS = {"Anomaly-Free": PASTEL_GREEN, "Anomalous": PASTEL_PURPLE}
TRI_COLORS = {
    "empty_clean": PASTEL_GREEN,
    "empty_dirty": PASTEL_TEAL,
    "non_empty":   PASTEL_YELLOW,
}

# ---------------------------------------------------------------------------
# Figure 1: Class distribution per scene — binary & trinary tasks (stacked bars)
# ---------------------------------------------------------------------------

def fig_class_per_scene(records, out_dir):
    scenes_ids     = sorted(set(r["scene_id"] for r in records))
    scenes_ids_int = sorted(set(int(r["scene_id"]) for r in records))
    n_scenes       = len(scenes_ids)

    binary_counts  = defaultdict(lambda: defaultdict(int))
    trinary_counts = defaultdict(lambda: defaultdict(int))

    for r in records:
        cls = r["classification"]
        sid = r["scene_id"]
        binary_counts[sid][BINARY_MAP[cls]] += 1
        trinary_counts[sid][cls]           += 1

    bar_w     = 0.30
    task_gap  = 0.06
    scene_gap = 0.85

    task1_offsets = np.array([i * scene_gap - (bar_w / 2 + task_gap / 2)
                               for i in range(n_scenes)])
    task2_offsets = task1_offsets + bar_w + task_gap
    scene_centres = (task1_offsets + task2_offsets) / 2

    fig = plt.figure(figsize=(6.5, 6.0))
    fig.patch.set_facecolor("white")
    gs  = fig.add_gridspec(2, 1, height_ratios=[4, 1.5], hspace=-0.02)
    ax       = fig.add_subplot(gs[0])
    ax_table = fig.add_subplot(gs[1])
    ax_table.axis("off")

    fig.subplots_adjust(top=0.92, bottom=0.05)

    def draw_stacked(ax, x_positions, class_order, color_map, count_dict, scenes):
        bottoms = np.zeros(len(scenes))
        for cls in class_order:
            vals = np.array([count_dict[sc].get(cls, 0) for sc in scenes],
                            dtype=float)
            ax.bar(x_positions, vals, width=bar_w, bottom=bottoms,
                   color=color_map[cls], label=cls,
                   edgecolor="white", linewidth=0.5)
            for xp, v, bot in zip(x_positions, vals, bottoms):
                if v >= 1:
                    ax.text(xp, bot + v / 2, str(int(v)),
                            ha="center", va="center",
                            fontsize=8, color="#444444", fontweight="bold")
            bottoms += vals
        for xp, tot in zip(x_positions, bottoms):
            if tot > 0:
                ax.text(xp, tot + 0.8, str(int(tot)),
                        ha="center", va="bottom",
                        fontsize=8, color="#333333", fontweight="bold")

    draw_stacked(ax, task1_offsets, BINARY_CLASSES,  BIN_COLORS,
                 binary_counts,  scenes_ids)
    draw_stacked(ax, task2_offsets, TRINARY_CLASSES, TRI_COLORS,
                 trinary_counts, scenes_ids)

    margin = 0.25
    x_left  = task1_offsets[0] - margin
    x_right = task2_offsets[-1] + margin
    ax.set_xlim(x_left, x_right)

    ax.set_xticks(scene_centres)
    ax.set_xticklabels([])
    ax.tick_params(axis="x", length=0)

    for i in range(1, n_scenes):
        sep_x = (task2_offsets[i - 1] + task1_offsets[i]) / 2
        ax.axvline(sep_x, color=SPINE_COLOR, linewidth=0.7,
                   linestyle="dotted", alpha=0.5)

    ax.grid(False)

    blank = Patch(facecolor="none", edgecolor="none", label="")
    legend_elements = (
        [Patch(facecolor="none", edgecolor="none", label="Task 1:")] +
        [Patch(facecolor=BIN_COLORS[c], edgecolor="#aaaaaa",
               linewidth=0.5, label=c) for c in BINARY_CLASSES] +
        [blank] +
        [Patch(facecolor="none", edgecolor="none", label="Task 2:")] +
        [Patch(facecolor=TRI_COLORS[c], edgecolor="#aaaaaa",
               linewidth=0.5, label=c) for c in TRINARY_CLASSES]
    )
    ax.legend(handles=legend_elements,
              title="Anomaly Detection Task",
              fontsize=8, title_fontsize=10,
              framealpha=0.9, edgecolor=SPINE_COLOR,
              bbox_to_anchor=(1.0, 1.0),
              loc="upper right",
              ncol=2,
              borderpad=0.6, labelspacing=0.3)

    style_ax(ax, xlabel="", ylabel="Number of Images")

    row_labels  = ["Task", "Camera", "Load Carrier", "Scene"]

    task_row    = []
    cam_row     = []
    lc_row      = []
    scene_row   = []
    row_labels  = ["Task", "Camera", "Load Carrier", "Scene"]

    # Store the values separately for manual centering later
    cam_values   = []
    lc_values    = []
    scene_values = []

    for sid in scenes_ids_int:
        task_row += ["Task 1", "Task 2"]

        cam = SCENE_CAMERA.get(sid, "Unknown")
        lc  = SCENE_LOAD_CARRIER.get(sid, "")

        cam_values.append(cam)
        lc_values.append(lc)
        scene_values.append(f"Scene {sid}")

        # leave cells empty, we'll draw centered text manually
        cam_row   += ["", ""]
        lc_row    += ["", ""]
        scene_row += ["", ""]

    cell_text = [task_row, cam_row, lc_row, scene_row]

    boundaries = [x_left]
    for i in range(n_scenes):
        boundaries.append((task1_offsets[i] + task2_offsets[i]) / 2)
        if i < n_scenes - 1:
            boundaries.append((task2_offsets[i] + task1_offsets[i+1]) / 2)
        else:
            boundaries.append(x_right)

    col_widths_data = [
        boundaries[k+1] - boundaries[k]
        for k in range(len(boundaries)-1)
    ]
    total_w = sum(col_widths_data)
    col_widths = [w / total_w for w in col_widths_data]

    #ax_table.set_title(
    #    "Image Distribution Across Scenes and Classification Tasks",
    #    fontsize=9,
    #    pad=2
    #)

    tbl = ax_table.table(
        cellText   = cell_text,
        rowLabels  = row_labels,
        colLabels  = None,
        cellLoc    = "center",
        loc        = "center",
        colWidths  = col_widths,
    )

    tbl.auto_set_font_size(False)
    tbl.set_fontsize(8)
    tbl.scale(1, 1.6)

    for (row, col), cell in tbl.get_celld().items():
        cell.set_edgecolor("#9C9C9C")
        cell.set_linewidth(0.5)
        cell.set_facecolor("#FFFFFF")

        if col == -1:
            cell.set_text_props(
                #fontstyle="italic",
                #fontweigth="bold",
                #color="#818181",
                fontweight="bold",
                fontsize=8
            )
            cell.visible_edges = "closed"
        elif row == 0:
            cell.visible_edges = "closed"

    # Visually merge T1/T2 pairs
    for row in [1, 2, 3]:
        for i in range(n_scenes):
            col_t1 = i * 2
            col_t2 = i * 2 + 1

            cell_t1 = tbl[row, col_t1]
            cell_t2 = tbl[row, col_t2]

            cell_t1.visible_edges = "LBT"
            cell_t2.visible_edges = "RBT"

    # Force layout update so cell coordinates are correct
    fig.canvas.draw()

    # Draw centered labels spanning both T1/T2 columns
    for row, values in zip(
        [1, 2, 3],
        [cam_values, lc_values, scene_values]
    ):
        for i, text in enumerate(values):

            c1 = tbl[row, i * 2]
            c2 = tbl[row, i * 2 + 1]

            x = c1.get_x()
            y = c1.get_y()

            w = c1.get_width() + c2.get_width()
            h = c1.get_height()

            ax_table.text(
                x + w / 2,
                y + h / 2,
                text,
                ha="center",
                va="center",
                fontsize=8,
                transform=ax_table.transAxes,
            )

    save(fig, out_dir / "image_dist_per_classification_and_scene.pdf")

# ---------------------------------------------------------------------------
# Figure 7.2: Mask area violin plots per category 
# ---------------------------------------------------------------------------

def fig_mask_area_violin(ann_records, out_dir, tick_fs=10, label_fs=12):

    cats = sorted(set(r["cat_name"] for r in ann_records))

    data = {
        c: np.log1p([r["area"] for r in ann_records
                     if r["cat_name"] == c and r["area"] > 0])
        for c in cats
    }

    cats = [c for c in cats if len(data[c]) > 1]
    colors = viridis_palette(len(cats))

    x = np.arange(len(cats))

    fig, ax = plt.subplots(figsize=(max(4, len(cats) * 0.5 + 1), 5))
    fig.patch.set_facecolor("white")

    parts = ax.violinplot(
        [data[c] for c in cats],
        positions=x,
        showmedians=True,
        showextrema=True,
        widths=0.8
    )

    for pc, col in zip(parts["bodies"], colors):
        pc.set_facecolor(col)
        pc.set_alpha(0.8)

    parts["cmedians"].set_color("white")
    parts["cmins"].set_color("#555")
    parts["cmaxes"].set_color("#555")
    parts["cbars"].set_color("#555")

    ax.set_xticks(x)
    ax.set_xticklabels(cats, rotation=30, ha="right", fontsize=label_fs)

    style_ax(ax, xlabel="Segmentation Mask", ylabel="log(1 + Mask Area in pixels²)")

    ax.xaxis.label.set_fontweight("bold")
    ax.yaxis.label.set_fontweight("bold")
    ax.yaxis.label.set_fontsize(label_fs)
    ax.xaxis.label.set_fontsize(label_fs)
    ax.tick_params(axis="both", labelsize=label_fs)

    ax.set_xlim(-0.5, len(cats) - 0.5)

    fig.tight_layout()
    save(fig, out_dir / "segmentation_mask_area_violin.pdf")


# ---------------------------------------------------------------------------
# Figure 9.3: Light intensity histograms all scenes
# ---------------------------------------------------------------------------

def _accumulate_gray_histogram(records):
    """
    Accumulate the 256-bin grayscale histogram over all readable images of the
    given records. Returns (histogram, number_of_loaded_images).
    """
    hist_acc = np.zeros(256)
    n_loaded = 0

    for r in records:
        img_path = Path(r.get("_abs_path", ""))
        if not img_path.exists():
            continue

        try:
            img_pil = PILImage.open(img_path).convert("L")
            img = np.array(img_pil)
            h, _ = np.histogram(img, bins=256, range=(0, 256))
            hist_acc += h
            n_loaded += 1
        except Exception:
            continue

    return hist_acc, n_loaded


def fig_intensity_histogram_global(
    records, out_dir, image_meta=None, y_max=0.017, train_records=None
):
  if PILImage is None:
    print("  [SKIP] Pillow not available for intensity histograms.")
    return

  if image_meta is None:
    image_meta = {
        "Dark": ("./test/000006/anomaly/rgb/00027.png", "Scene 6\nImg Num: 27"),
        "Midtone": (
            "./test/000004/anomaly/rgb/00116.png",
            "Scene 4\nImg Num: 116",
        ),
        "Bright": (
            "./test/000001/anomaly/rgb/00235.png",
            "Scene 1\nImg Num: 235",
        ),
    }

  fig, ax = plt.subplots(1, 1, figsize=(6, 4.3))
  fig.patch.set_facecolor("white")

  global_hist_acc = np.zeros(256)
  global_n_loaded = 0

  for r in records:
    img_path = Path(r.get("_abs_path", ""))
    if not img_path.exists():
      continue

    try:
      img_pil = PILImage.open(img_path).convert("L")
      img = np.array(img_pil)
      h, _ = np.histogram(img, bins=256, range=(0, 256))
      global_hist_acc += h
      global_n_loaded += 1
    except Exception:
      continue

  if global_n_loaded > 0:
    from scipy.ndimage import gaussian_filter1d

    global_hist_acc = gaussian_filter1d(global_hist_acc, sigma=2)

    global_norm = global_hist_acc / global_hist_acc.sum()
    ax.plot(
        range(256),
        global_norm,
        color=plt.cm.viridis(0.2),
        alpha=1.0,
        linewidth=1.5,
        label="Test",
    )

    if train_records:
      train_hist, train_n_loaded = _accumulate_gray_histogram(train_records)
      if train_n_loaded > 0:
        train_hist = gaussian_filter1d(train_hist, sigma=2)
        train_norm = train_hist / train_hist.sum()
        ax.plot(
            range(256),
            train_norm,
            color=plt.cm.viridis(0.88),
            alpha=1.0,
            linewidth=1.5,
            linestyle="--",
            label="Train",
        )

    # Legend placed inside the plot area at the bottom
    ax.legend(
    loc="lower center",
    bbox_to_anchor=(0.42, 0.02),
    ncol=2,
    frameon=True,
    framealpha=0.5,
    fontsize=10,
    borderpad=0.4,
    facecolor="white",
    edgecolor="gray",
)

    if y_max is not None:
      ax.set_ylim(0, y_max)

    def add_sample_image(
        img_path, label_info, xybox, title, highlight_color, is_right
    ):
      if not img_path or not Path(img_path).exists():
        return
      try:
        img_obj = PILImage.open(img_path)
        orig_w, orig_h = img_obj.size
        zoom_factor = 100.0 / max(orig_w, orig_h)
        imagebox = OffsetImage(np.array(img_obj), zoom=zoom_factor)
        img_gray = np.array(img_obj.convert("L"))
        mean_val = np.mean(img_gray)
        x_idx = min(255, max(0, int(mean_val)))
        y_val = global_norm[x_idx]

        ab = AnnotationBbox(
            imagebox,
            (mean_val, y_val),
            xybox=xybox,
            xycoords="data",
            boxcoords="axes fraction",
            arrowprops=dict(arrowstyle="->", color=highlight_color, lw=1),
            bboxprops=dict(edgecolor=highlight_color),
        )
        ax.add_artist(ab)

        ax.text(
            xybox[0],
            xybox[1] + 0.21,
            title,
            transform=ax.transAxes,
            ha="center",
            fontsize=8,
            color=highlight_color,
            weight="bold",
        )

        text_x_offset = -0.065 if is_right else 0.035
        ax.text(
            xybox[0] + text_x_offset,
            xybox[1] - 0.23,
            label_info,
            transform=ax.transAxes,
            ha="center",
            va="center",
            fontsize=8,
            color="black",
        )
      except Exception:
        pass

    colors = [plt.cm.viridis(0.2), plt.cm.viridis(0.5), plt.cm.viridis(0.8)]
    # Shifted image box y coordinates up from 0.78 to 0.86
    positions = [(0.19, 0.80), (0.5, 0.80), (0.81, 0.80)]
    titles = ["Dark", "Midtone", "Bright"]

    for i, key in enumerate(titles):
      if key in image_meta:
        path, label = image_meta[key]
        is_right = i == 2
        add_sample_image(path, label, positions[i], key, colors[i], is_right)

  style_ax(
      ax, title="", xlabel="Pixel Intensity", ylabel="Normalized Pixel Frequency"
  )
  ax.set_facecolor("white")

  fig.tight_layout()
  save(fig, out_dir / "intensity_histogram_global.pdf")

# ---------------------------------------------------------------------------
# Figure 9.4: Light intensity statistics
# ---------------------------------------------------------------------------

def calc_intensity_statistics_global(records, label="Dataset"):
    if PILImage is None:
        print("  [SKIP] Pillow not available for intensity calculations.")
        return

    # Use int64 to prevent overflow when summing millions of pixels
    global_hist_acc = np.zeros(256, dtype=np.int64)
    global_n_loaded = 0

    for r in records:
        img_path = Path(r.get("_abs_path", ""))
        if not img_path.exists():
            continue
            
        try:
            img_pil = PILImage.open(img_path).convert("L")
            img = np.array(img_pil)
            h, _ = np.histogram(img, bins=256, range=(0, 256))
            global_hist_acc += h
            global_n_loaded += 1
        except Exception:
            continue

    if global_n_loaded == 0:
        print("No images were loaded successfully.")
        return

    total_pixels = global_hist_acc.sum()
    if total_pixels == 0:
        print("Total pixels is 0. Cannot compute statistics.")
        return

    intensities = np.arange(256)
    
    # Calculate Mean
    mean_intensity = np.sum(intensities * global_hist_acc) / total_pixels
    
    # Calculate Variance and Standard Deviation
    mean_sq_intensity = np.sum((intensities ** 2) * global_hist_acc) / total_pixels
    variance = mean_sq_intensity - (mean_intensity ** 2)
    std_intensity = np.sqrt(variance)
    
    # Calculate Min and Max
    non_zero_bins = np.where(global_hist_acc > 0)[0]
    min_val = non_zero_bins[0] if len(non_zero_bins) > 0 else 0
    max_val = non_zero_bins[-1] if len(non_zero_bins) > 0 else 0
    
    # Calculate Percentiles via Cumulative Distribution
    cum_hist = np.cumsum(global_hist_acc)
    cum_hist_norm = cum_hist / total_pixels
    
    p25 = np.searchsorted(cum_hist_norm, 0.25)
    median = np.searchsorted(cum_hist_norm, 0.50)
    p75 = np.searchsorted(cum_hist_norm, 0.75)

    print(f"{label} Intensity Statistics (Over {global_n_loaded} images):")
    print(f"  Total Pixels: {total_pixels:,}")
    print(f"  Mean:         {mean_intensity:.2f}")
    print(f"  Std Dev:      {std_intensity:.2f}")
    print(f"  Min:          {min_val}")
    print(f"  Max:          {max_val}")
    print(f"  25th Pct:     {p25}")
    print(f"  Median:       {median}")
    print(f"  75th Pct:     {p75}")

    return {
        "n_images": global_n_loaded,
        "total_pixels": total_pixels,
        "mean": mean_intensity,
        "std": std_intensity,
        "min": min_val,
        "max": max_val,
        "p25": p25,
        "median": median,
        "p75": p75
    }

# ---------------------------------------------------------------------------
# Figure 12.1: Pose translation 3D scatter 3D angle axis
# ---------------------------------------------------------------------------

def draw_working_frustum(ax, K, R, t, min_depth, actual_max_depth, draw_max_depth=None, color='magenta', label='Camera'):
    if draw_max_depth is None or draw_max_depth > actual_max_depth:
        draw_max_depth = actual_max_depth
        
    fx, fy = K[0, 0], K[1, 1]
    cx, cy = K[0, 2], K[1, 2]
    
    w = cx * 2
    h = cy * 2
    corners = np.array([[0,0], [w,0], [w,h], [0,h]])
    
    def get_pts_at_depth(depth):
        pts = np.zeros((4, 3))
        pts[:, 0] = (corners[:, 0] - cx) * depth / fx
        pts[:, 1] = (corners[:, 1] - cy) * depth / fy
        pts[:, 2] = depth
        return pts
        
    near_pts = get_pts_at_depth(min_depth)
    far_pts = get_pts_at_depth(draw_max_depth)
    
    origin = np.array([[0, 0, 0]])
    all_pts = np.vstack((origin, near_pts, far_pts))
    
    has_extension = actual_max_depth > draw_max_depth
    if has_extension:
        ext_pts = get_pts_at_depth(draw_max_depth + 150.0) 
        all_pts = np.vstack((all_pts, ext_pts))
        
    all_pts = (R.T @ (all_pts.T - t.reshape(3, 1))).T
    
    orig = all_pts[0]
    n = all_pts[1:5]
    f = all_pts[5:9]
    
    for i in range(4):
        ax.plot([orig[0], f[i,0]], [orig[1], f[i,1]], [orig[2], f[i,2]], color=color, alpha=0.3, linestyle=':')
        
    for i in range(4):
        next_i = (i + 1) % 4
        ax.plot([n[i,0], n[next_i,0]], [n[i,1], n[next_i,1]], [n[i,2], n[next_i,2]], color=color, linewidth=1.5)
        
        far_ls = ':' if has_extension else '-'
        ax.plot([f[i,0], f[next_i,0]], [f[i,1], f[next_i,1]], [f[i,2], f[next_i,2]], color=color, linewidth=1.5, linestyle=far_ls)
        ax.plot([n[i,0], f[i,0]], [n[i,1], f[i,1]], [n[i,2], f[i,2]], color=color, linewidth=1.5)
        
        if has_extension:
            ext = all_pts[9:13]
            ax.plot([f[i,0], ext[i,0]], [f[i,1], ext[i,1]], [f[i,2], ext[i,2]], color=color, linewidth=1.5, linestyle=':')
            
            if i == 0:
                ax.text(ext[i,0], ext[i,1], ext[i,2] - 40, f"Max depth range at {actual_max_depth}mm", 
                        color=color, fontsize=11, style='italic',
                        bbox=dict(facecolor='white', alpha=0.8, edgecolor='none', pad=2))

    # Realistic Camera Body Geometry
    lw, lh, l_depth = 10.0, 10.0, -12.0
    bw, bh, b_front, b_back = 20.0, 15.0, -12.0, -35.0
    
    cam_body_pts = np.array([
        [0, 0, 0], 
        [-lw, -lh, l_depth], [lw, -lh, l_depth], [lw, lh, l_depth], [-lw, lh, l_depth], 
        [-bw, -bh, b_front], [bw, -bh, b_front], [bw, bh, b_front], [-bw, bh, b_front],
        [-bw, -bh, b_back], [bw, -bh, b_back], [bw, bh, b_back], [-bw, bh, b_back],
    ])
    
    cam_body_world = (R.T @ (cam_body_pts.T - t.reshape(3, 1))).T
    
    box_edges = [
        (0,1), (0,2), (0,3), (0,4),
        (1,2), (2,3), (3,4), (4,1),
        (5,6), (6,7), (7,8), (8,5),
        (9,10), (10,11), (11,12), (12,9),
        (5,9), (6,10), (7,11), (8,12)
    ]
    
    for e1, e2 in box_edges:
        ax.plot([cam_body_world[e1,0], cam_body_world[e2,0]], 
                [cam_body_world[e1,1], cam_body_world[e2,1]], 
                [cam_body_world[e1,2], cam_body_world[e2,2]], 
                color=color, linewidth=0.8)

    ax.plot([], [], [], color=color, linewidth=1.5, label=label)
    
    return all_pts

def fig_pose_3d_with_frames(pose_records, out_dir, cam_properties=None, voxel_size=100):
    if not pose_records and not cam_properties:
        print("  [SKIP] No pose data found.")
        return

    plt.rcParams.update({
        'font.size': 14,
        'axes.titlesize': 16,
        'axes.labelsize': 14,
        'legend.fontsize': 12
    })

    fig = plt.figure(figsize=(12, 9))
    ax = fig.add_subplot(111, projection="3d")

    ax.set_facecolor('white')
    
    ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    
    tx_list, ty_list, tz_list = [], [], []
    length = 100.0
    alpha_val = 0.4
    occupied_voxels = set()

    if pose_records:
        for p in pose_records:
            if "tx" in p:
                t = np.array([p["tx"], p["ty"], p["tz"]])
            elif "t" in p:
                t = np.array(p["t"])
            else:
                continue
            
            if voxel_size is not None and voxel_size > 0:
                voxel_idx = (
                    int(np.floor(t[0] / voxel_size)),
                    int(np.floor(t[1] / voxel_size)),
                    int(np.floor(t[2] / voxel_size))
                )
                if voxel_idx in occupied_voxels:
                    continue
                occupied_voxels.add(voxel_idx)
                
            tx_list.append(t[0])
            ty_list.append(t[1])
            tz_list.append(t[2])

            R = np.array(p["R"]).reshape(3, 3)
            for i, color in enumerate(['r', 'g', 'b']):
                ax.quiver(t[0], t[1], t[2], R[0, i] * length, R[1, i] * length, R[2, i] * length, 
                          color=color, alpha=alpha_val)

        ax.plot([], [], [], color='r', label='X Axis Rotation')
        ax.plot([], [], [], color='g', label='Y Axis Rotation')
        ax.plot([], [], [], color='b', label='Z Axis Rotation')

    all_x, all_y, all_z = list(tx_list), list(ty_list), list(tz_list)
    all_x.append(0.0)
    all_y.append(0.0)
    all_z.append(0.0)

    if cam_properties:
            cmap = plt.get_cmap('viridis')
            
            safe_viridis_values = [0.1, 0.88]
            
            for idx, (cam_id, props) in enumerate(cam_properties.items()):
                K = np.array(props["cam_K"]).reshape(3, 3)
                R = np.array(props.get("R", np.eye(3))).reshape(3, 3)
                t = np.array(props.get("t", np.zeros(3)))
                
                min_depth = props.get("min_depth", 300.0)
                max_depth = props.get("max_depth", 1000.0)
                draw_max_depth = props.get("draw_max_depth", max_depth)
                
                color_val = safe_viridis_values[idx % len(safe_viridis_values)]
                cam_color = cmap(color_val)
                
                legend_label = f"{cam_id} Frustum"
                
                pts = draw_working_frustum(ax, K, R, t, min_depth, max_depth, draw_max_depth=draw_max_depth, color=cam_color, label=legend_label)
                
                all_x.extend(pts[:, 0])
                all_y.extend(pts[:, 1])
                all_z.extend(pts[:, 2])

    if all_x:
        ax.set_xlim(min(all_x), max(all_x))
        ax.set_ylim(min(all_y), max(all_y))
        ax.set_zlim(min(all_z), max(all_z))
    
    ax.set_xlabel("X Translation [mm]", labelpad=20)
    ax.set_ylabel("Y Translation [mm]", labelpad=20)
    ax.set_zlabel("Z Translation [mm]", labelpad=20)

    ax.tick_params(axis='z', pad=10)
    
    if cam_properties or pose_records:
        ax.legend(loc='upper right', bbox_to_anchor=(0.4, 0.78), ncol = 1)

    ax.view_init(elev=8, azim=-79)
    ax.invert_zaxis()
        
    plt.tight_layout()
    plt.savefig(out_dir / "translation_rotation_3d.pdf", bbox_inches='tight')
    plt.rcParams.update(plt.rcParamsDefault)


def _pose_translation(p):
    if "tx" in p:
        return np.array([p["tx"], p["ty"], p["tz"]], dtype=float)
    if "t" in p:
        return np.array(p["t"], dtype=float)
    return None


def fig_pose_3d_train_vs_test(pose_records, train_pose_records, out_dir=None,
                              cam_properties=None, voxel_size=135,
                              sphere_coverage=100.0, show_points=False,
                              show_vectors=True, show_ellipsoids=True,
                              task2_parity="odd"):
    import re

    if not pose_records and not train_pose_records:
        print("  [SKIP] No pose data found for train/test comparison.")
        return

    task2_parity = str(task2_parity).lower()
    if task2_parity not in {"odd", "even", "both"}:
        raise ValueError("task2_parity must be 'odd', 'even', or 'both'")

    def is_task2_pose(p):
        task = str(p.get("task", "")).lower().replace(" ", "")
        if task in {"2", "task2", "task_2"}:
            return True

        for key in ("image_path", "_abs_path", "file_path", "path",
                    "image_name", "file_name"):
            value = str(p.get(key, "")).replace("\\", "/").lower()
            if re.search(r"(?:^|/)task[_]?2(?:/|$)", value):
                return True
        return False

    def get_image_number(p):
        for key in ("image_id", "image_name", "file_name",
                    "image_path", "_abs_path", "file_path", "path"):
            value = str(p.get(key, ""))
            if not value or value.lower() == "none":
                continue
            match = re.search(r"(\d+)(?=\.[^.]+$|$)", value)
            if match:
                return int(match.group(1))
        return None

    sets = [
        ("Test",  pose_records,       "#fde725"),
        ("Train", train_pose_records, "#20a486"),
    ]

    rc = {
        'font.size': 14,
        'axes.titlesize': 16,
        'axes.labelsize': 14,
        'legend.fontsize': 12,
    }

    task2_seen = 0
    task2_kept = 0

    with plt.rc_context(rc):
        fig = plt.figure(figsize=(12, 9))
        ax = fig.add_subplot(111, projection="3d")
        ax.set_facecolor('white')

        ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
        ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
        ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

        length = 100.0
        alpha_val = 0.4
        all_x, all_y, all_z = [0.0], [0.0], [0.0]
        sphere_proxies = []
        point_proxies = []

        scatter_x, scatter_y, scatter_z, scatter_c = [], [], [], []

        for name, poses, color in sets:
            if not poses:
                continue

            all_translations = []
            filtered_translations = []
            occupied_voxels = set()

            for p in poses:
                # Apply parity filtering only to Task 2 poses in the training set.
                if name == "Train" and is_task2_pose(p):
                    task2_seen += 1
                    if task2_parity != "both":
                        image_number = get_image_number(p)
                        if image_number is None:
                            print(
                                "  [WARNING] Could not determine image number "
                                "for a Task 2 training pose; skipping it for "
                                f"task2_parity='{task2_parity}'."
                            )
                            continue
                        if task2_parity == "odd" and image_number % 2 == 0:
                            continue
                        if task2_parity == "even" and image_number % 2 != 0:
                            continue
                    task2_kept += 1

                t = _pose_translation(p)
                if t is None:
                    continue

                all_translations.append(t)

                if voxel_size is not None and voxel_size > 0:
                    voxel_idx = (
                        int(np.floor(t[0] / voxel_size)),
                        int(np.floor(t[1] / voxel_size)),
                        int(np.floor(t[2] / voxel_size)),
                    )
                    if voxel_idx in occupied_voxels:
                        continue
                    occupied_voxels.add(voxel_idx)

                filtered_translations.append(t)

                if show_vectors and p.get("R") is not None:
                    R = np.asarray(p["R"], dtype=float).reshape(3, 3)
                    for i, axis_color in enumerate(['r', 'g', 'b']):
                        ax.quiver(t[0], t[1], t[2],
                                  R[0, i] * length, R[1, i] * length, R[2, i] * length,
                                  color=axis_color, alpha=alpha_val)

            if not all_translations:
                continue

            t_arr_all = np.array(all_translations)
            t_arr_filtered = np.array(filtered_translations)

            if show_points and len(t_arr_filtered) > 0:
                scatter_x.extend(t_arr_filtered[:, 0])
                scatter_y.extend(t_arr_filtered[:, 1])
                scatter_z.extend(t_arr_filtered[:, 2])
                scatter_c.extend([color] * len(t_arr_filtered))

                point_proxies.append(
                    Line2D([0], [0], marker='o', color='w', markerfacecolor=color,
                           markersize=6, label=f"{name} translations")
                )

            center = t_arr_all.mean(axis=0)

            if show_ellipsoids:
                dists = np.linalg.norm(t_arr_all - center, axis=1)
                threshold = np.percentile(dists, sphere_coverage)
                core_points = t_arr_all[dists <= threshold]

                if len(core_points) >= 4:
                    hull = ConvexHull(core_points)
                    faces = [core_points[simplex] for simplex in hull.simplices]
                    poly = Poly3DCollection(faces, alpha=0.2, facecolors=color, linewidths=0)#, shade=True)
                    ax.add_collection3d(poly)

                sphere_proxies.append(
                    Patch(facecolor=color, edgecolor=color, alpha=0.3,
                          label=f"{name} convex hull")
                )

                all_x.extend([core_points[:, 0].min(), core_points[:, 0].max()])
                all_y.extend([core_points[:, 1].min(), core_points[:, 1].max()])
                all_z.extend([core_points[:, 2].min(), core_points[:, 2].max()])
            else:
                all_x.extend(t_arr_filtered[:, 0])
                all_y.extend(t_arr_filtered[:, 1])
                all_z.extend(t_arr_filtered[:, 2])

        if task2_parity != "both":
            print(
                f"  Train Task 2 parity filter ('{task2_parity}'): "
                f"kept {task2_kept}/{task2_seen} Task 2 poses."
            )

        if show_points and scatter_x:
            ax.scatter(scatter_x, scatter_y, scatter_z,
                       s=0.2, c=scatter_c, alpha=1, depthshade=False)

        if show_vectors:
            ax.plot([], [], [], color='r', label='X Axis Rotation')
            ax.plot([], [], [], color='g', label='Y Axis Rotation')
            ax.plot([], [], [], color='b', label='Z Axis Rotation')

        if cam_properties:
            cmap = plt.get_cmap('viridis')
            safe_viridis_values = [0.1, 0.88]

            for idx, (cam_id, props) in enumerate(cam_properties.items()):
                K = np.array(props["cam_K"]).reshape(3, 3)
                R = np.array(props.get("R", np.eye(3))).reshape(3, 3)
                t = np.array(props.get("t", np.zeros(3)))

                min_depth = props.get("min_depth", 300.0)
                max_depth = props.get("max_depth", 1000.0)
                draw_max_depth = props.get("draw_max_depth", max_depth)

                color_val = safe_viridis_values[idx % len(safe_viridis_values)]
                cam_color = cmap(color_val)

                pts = draw_working_frustum(
                    ax, K, R, t, min_depth, max_depth,
                    draw_max_depth=draw_max_depth,
                    color=cam_color,
                    label=f"{cam_id} Frustum",
                )

                all_x.extend(pts[:, 0])
                all_y.extend(pts[:, 1])
                all_z.extend(pts[:, 2])

        if all_x:
            ax.set_xlim(min(all_x), max(all_x))
            ax.set_ylim(min(all_y), max(all_y))
            ax.set_zlim(min(all_z), max(all_z))

        ax.set_xlabel("X Translation [mm]", labelpad=20)
        ax.set_ylabel("Y Translation [mm]", labelpad=20)
        ax.set_zlabel("Z Translation [mm]", labelpad=20)

        ax.tick_params(axis='z', pad=10)

        handles, labels = ax.get_legend_handles_labels()
        handles = point_proxies + handles + sphere_proxies
        ax.legend(handles=handles, loc='upper left', bbox_to_anchor=(0.13, 0.78), ncol=1)

        ax.view_init(elev=8, azim=-79)
        ax.invert_zaxis()

        plt.tight_layout()
        if out_dir:
            out_path = out_dir / "translation_rotation_3d_train_vs_test_vectors.pdf"
            plt.savefig(out_path, bbox_inches='tight')
        plt.show()
        plt.close(fig)

# ---------------------------------------------------------------------------
# INFO Function: Print 6DOF stats
# ---------------------------------------------------------------------------

def print_6dof_stats(pose_records, label=None):
    if label:
        print(f"\n[{label}]")

    if not pose_records:
        print(" [SKIP] No pose data found.")
        return

    translations = []
    rotations_euler = []

    for p in pose_records:
        if "tx" in p:
            t = [p["tx"], p["ty"], p["tz"]]
        elif "t" in p:
            t = p["t"]
        else:
            continue
        translations.append(t)

        if "R" in p:
            rmat = np.array(p["R"]).reshape(3, 3)
            euler = Rotation.from_matrix(rmat).as_euler('xyz', degrees=True)
            rotations_euler.append(euler)
        elif "rx" in p:
            rvec = [p["rx"], p["ry"], p["rz"]]
            euler = Rotation.from_rotvec(rvec).as_euler('xyz', degrees=True)
            rotations_euler.append(euler)
        else:
            rotations_euler.append([0.0, 0.0, 0.0])

    t_arr = np.array(translations)
    r_arr = np.array(rotations_euler)

    t_mean = np.mean(t_arr, axis=0)
    t_std = np.std(t_arr, axis=0)
    r_mean = np.mean(r_arr, axis=0)
    r_std = np.std(r_arr, axis=0)

    print("Translation Statistics [mm]:")
    print(f" X: Mean {t_mean[0]:.3f}, Std {t_std[0]:.3f}")
    print(f" Y: Mean {t_mean[1]:.3f}, Std {t_std[1]:.3f}")
    print(f" Z: Mean {t_mean[2]:.3f}, Std {t_std[2]:.3f}")
    print("Rotation Statistics (Euler XYZ) [degrees]:")
    print(f" RX: Mean {r_mean[0]:.3f}, Std {r_std[0]:.3f}")
    print(f" RY: Mean {r_mean[1]:.3f}, Std {r_std[1]:.3f}")
    print(f" RZ: Mean {r_mean[2]:.3f}, Std {r_std[2]:.3f}")

    return t_mean, t_std, r_mean, r_std


# ---------------------------------------------------------------------------
# Figure 14.2: Spatial annotation heatmap per category
# ---------------------------------------------------------------------------

def fig_spatial_heatmap_ungrouped(ann_records, out_dir):
    H, W = 480, 640
    if not HAS_PYCOCOTOOLS:
        return
    
    FS = 19  # base font size; adjust as needed

    # Merge nuisance_dent and nuisance_plastic into one entry
    MERGED = {
        "nuisance_dent+plastic": ["nuisance_dent", "nuisance_plastic"],
    }
    MERGED_LOOKUP = {}
    for merged_name, members in MERGED.items():
        for m in members:
            MERGED_LOOKUP[m] = merged_name

    # Discover all unique category names, replacing merged members with the merged key
    all_cats_raw = sorted({r["cat_name"] for r in ann_records if "cat_name" in r})
    seen = set()
    all_cats = []
    for cat in all_cats_raw:
        display = MERGED_LOOKUP.get(cat, cat)
        if display not in seen:
            all_cats.append(display)
            seen.add(display)

    # Build one heatmap per display category
    heatmaps = {cat: np.zeros((H, W), dtype=float) for cat in all_cats}

    for r in ann_records:
        seg = r.get("_segmentation")
        if seg is None:
            continue
        cat = r.get("cat_name")
        if cat is None:
            continue
        display = MERGED_LOOKUP.get(cat, cat)
        if display not in heatmaps:
            continue
        try:
            if isinstance(seg, dict) and not isinstance(seg.get("counts"), list):
                rle = seg
            else:
                rle = coco_mask_utils.frPyObjects(seg, H, W)
            m = coco_mask_utils.decode(rle)
            if m.ndim == 3:
                m = m.sum(axis=2)
            heatmaps[display] += m.astype(float)
        except Exception:
            continue

    n_cats = len(all_cats)        # 11 after merge
    n_rows, n_cols = 2, 6

    fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 4, n_rows * 3.5))
    fig.patch.set_facecolor("white")
    axes = axes.flatten()

    for ax, cat in zip(axes, all_cats):
        im = ax.imshow(heatmaps[cat], cmap="viridis", interpolation="bilinear")
        ax.set_title(cat, fontsize=FS)
        ax.axis("off")
        cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
        cbar.ax.tick_params(labelsize=FS - 2)

    for ax in axes[n_cats:]:
        ax.set_visible(False)

    fig.tight_layout()
    save(fig, out_dir / "spatial_heatmap_ungrouped.pdf")


def fig_spatial_heatmap_ungrouped_common_legend(ann_records, out_dir):
    H, W = 480, 640
    if not HAS_PYCOCOTOOLS:
        return
    
    FS = 14  # base font size; adjust as needed

    # Merge nuisance_dent and nuisance_plastic into one entry
    MERGED = {
        "nuisance_dent+plastic": ["nuisance_dent", "nuisance_plastic"],
    }
    MERGED_LOOKUP = {}
    for merged_name, members in MERGED.items():
        for m in members:
            MERGED_LOOKUP[m] = merged_name

    # Discover all unique category names, replacing merged members with the merged key
    all_cats_raw = sorted({r["cat_name"] for r in ann_records if "cat_name" in r})
    seen = set()
    all_cats = []
    for cat in all_cats_raw:
        display = MERGED_LOOKUP.get(cat, cat)
        if display not in seen:
            all_cats.append(display)
            seen.add(display)

    # Build one heatmap per display category
    heatmaps = {cat: np.zeros((H, W), dtype=float) for cat in all_cats}

    for r in ann_records:
        seg = r.get("_segmentation")
        if seg is None:
            continue
        cat = r.get("cat_name")
        if cat is None:
            continue
        display = MERGED_LOOKUP.get(cat, cat)
        if display not in heatmaps:
            continue
        try:
            if isinstance(seg, dict) and not isinstance(seg.get("counts"), list):
                rle = seg
            else:
                rle = coco_mask_utils.frPyObjects(seg, H, W)
            m = coco_mask_utils.decode(rle)
            if m.ndim == 3:
                m = m.sum(axis=2)
            heatmaps[display] += m.astype(float)
        except Exception:
            continue

    n_cats = len(all_cats)        # 11 after merge
    n_rows, n_cols = 4, 3

    fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 4, n_rows * 2.9))
    fig.patch.set_facecolor("white")
    axes = axes.flatten()

    # Exactly 3 pixel ticks per axis
    x_ticks = [0, W // 2, W - 1]
    y_ticks = [0, H // 2, H - 1]

    for ax, cat in zip(axes, all_cats):
        im = ax.imshow(
            heatmaps[cat],
            cmap="viridis",
            interpolation="bilinear"
        )

        ax.set_title(cat, fontsize=FS)

        # Axis names
        ax.set_xlabel("x (pixels)", fontsize=FS - 1)
        ax.set_ylabel("y (pixels)", fontsize=FS - 1)

        # Pixel values
        ax.set_xticks(x_ticks)
        ax.set_yticks(y_ticks)

        ax.tick_params(
            axis="both",
            which="major",
            labelsize=FS - 3
        )

        ax.tick_params(
            axis="y",
            labelrotation=70
        )

        cbar = fig.colorbar(
            im,
            ax=ax,
            fraction=0.046,
            pad=0.07
        )
        cbar.set_label(
            "Annotation count",
            fontsize=FS - 2
        )
        cbar.ax.tick_params(labelsize=FS - 2)

    for ax in axes[n_cats:]:
        ax.set_visible(False)

    fig.subplots_adjust(
    left=0.08,
    right=0.95,
    top=0.97,
    bottom=0.05,
    hspace=0.5,
    wspace=0.30
    )

    fig.tight_layout()
    save(fig, out_dir / "spatial_heatmap_ungrouped.pdf")


# ---------------------------------------------------------------------------
# Main orchestration
# ---------------------------------------------------------------------------

def inject_abs_paths(records, scenes):
    """Attach absolute image paths to each record for pixel-level figures."""
    scene_root_map = {s["scene_id"]: s["root"] for s in scenes}
    for r in records:
        root = scene_root_map.get(r["scene_id"])
        if root:
            r["_abs_path"] = str(root / r["file_name"])
            r["_root"] = str(root)

def inject_segmentation(ann_records, scenes):
    """Attach segmentation data to ann_records for spatial heatmap figure."""
    # Build lookup: (scene_id, image_id, category_name) -> [segmentations]
    for s in scenes:
        scene_id = s["scene_id"]
        cat_map = s["cat_map"]
        for ann in s["coco"].get("annotations", []):
            cat_name = cat_map.get(ann["category_id"], "unknown")
            seg = ann.get("segmentation")
            if seg:
                # Find matching ann_record and inject
                for ar in ann_records:
                    if (ar["scene_id"] == scene_id and
                            ar["image_id"] == ann["image_id"] and
                            ar["cat_name"] == cat_name and
                            "_segmentation" not in ar):
                        ar["_segmentation"] = seg
                        break

my_cameras = {
  "RealSense": {
    "cam_K": [608.43, 0.0, 311.2, 0.0, 608.4, 239.6, 0.0, 0.0, 1.0],
    "min_depth": 300.0,
    "max_depth": 3000.0,
    "draw_max_depth": 1200.0
  },
  "Zivid": {
    "cam_K": [1242.25, 0.0, 620.7, 0.0, 1241.8, 503.7, 0.0, 0.0, 1.0],
    "min_depth": 350.0,
    "max_depth": 1100.0,
    "draw_max_depth": 1100.0
  }
}

def calc_variability_metrics(records, pose_records, label="", ignore_sym=False, sym_axis='z'):
    print("Variability Metrics Report" + label)

    # ------------------------------------------------------------------
    # Illumination spread
    # ------------------------------------------------------------------
    scene_intensity = defaultdict(list)
    all_intensity = []
    if PILImage is not None:
        for r in records:
            img_path_str = r.get("_abs_path", "")
            if not img_path_str:
                continue
            img_path = Path(img_path_str)
            if img_path.is_file():
                try:
                    img = np.array(PILImage.open(img_path).convert("L"))
                    mean_val = np.mean(img)
                    scene_intensity[r["scene_id"]].append(mean_val)
                    all_intensity.append(mean_val)
                except Exception:
                    pass

        print("\nIllumination Spread per Scene (Mean Pixel Intensity):")
        for sc in sorted(scene_intensity.keys()):
            means = scene_intensity[sc]
            if means:
                print(f" Scene {sc}: Mean {np.mean(means):.2f}, StdDev {np.std(means):.2f}, "
                      f"Min {np.min(means):.2f}, Max {np.max(means):.2f}")

        if all_intensity:
            print(f"\nIllumination Spread (All Scenes Pooled): "
                  f"Mean {np.mean(all_intensity):.2f}, StdDev {np.std(all_intensity):.2f}, "
                  f"Min {np.min(all_intensity):.2f}, Max {np.max(all_intensity):.2f}")

    if not pose_records:
        return

    # ------------------------------------------------------------------
    # Pose collection
    # ------------------------------------------------------------------
    scene_poses = defaultdict(lambda: {"t": [], "rot": []})
    t_all = []
    rot_all = []
    scene_ids_all = [] # Track scene IDs for the global calculation

    for p in pose_records:
        sc = p["scene_id"]

        if "tx" in p:
            t = [p["tx"], p["ty"], p["tz"]]
        elif "t" in p:
            t = p["t"]
        else:
            t = None

        rot = None
        if "R" in p:
            rmat = np.array(p["R"]).reshape(3, 3)
            rot = Rotation.from_matrix(rmat)
        elif "rx" in p:
            rvec = [p["rx"], p["ry"], p["rz"]]
            rot = Rotation.from_rotvec(rvec)

        if t is not None:
            t_all.append(t)
            scene_poses[sc]["t"].append(t)
        if rot is not None:
            rot_all.append(rot)
            scene_poses[sc]["rot"].append(rot)
            scene_ids_all.append(sc) # Append to the global tracking list

    def _translation_spread_mm(t_list):
        """Per-pose Euclidean distance from the centroid, merging X/Y/Z
        into a single scalar. Returns (mean, std, min, max)."""
        if len(t_list) < 2:
            return None
        t_arr = np.array(t_list)
        centroid = np.mean(t_arr, axis=0)
        dist = np.linalg.norm(t_arr - centroid, axis=1)
        return float(np.mean(dist)), float(np.std(dist)), float(np.min(dist)), float(np.max(dist))

    def _quat_spread_deg(rot_list, scene_ids=None):
            if len(rot_list) < 2:
                return None
            rots = Rotation.concatenate(rot_list)
            mean_rot = rots.mean()
            rel = mean_rot.inv() * rots
            dev_deg = rel.magnitude() * 180.0 / np.pi
            
            if ignore_sym and scene_ids is not None:
                vec = [0.0, 0.0, 0.0]
                vec[{'x': 0, 'y': 1, 'z': 2}[sym_axis.lower()]] = np.pi
                sym_rot = Rotation.from_rotvec(vec)
                
                rel_sym = mean_rot.inv() * (rots * sym_rot)
                dev_deg_sym = rel_sym.magnitude() * 180.0 / np.pi
                
                # Apply symmetry only to indices where scene_id <= 4
                mask = np.array([int(sid) <= 4 for sid in scene_ids])
                dev_deg[mask] = np.minimum(dev_deg[mask], dev_deg_sym[mask])
                
            return float(np.mean(dev_deg)), float(np.std(dev_deg)), float(np.min(dev_deg)), float(np.max(dev_deg))

    # ------------------------------------------------------------------
    # Global (all scenes pooled)
    # ------------------------------------------------------------------
    print("\nGlobal Pose Diversity:")
    t_global = _translation_spread_mm(t_all)
    if t_global is not None:
        mean_t, std_t, min_t, max_t = t_global
        print(f" Translation Spread [mm]: Mean {mean_t:.1f}, StdDev {std_t:.1f}, "
              f"Min {min_t:.1f}, Max {max_t:.1f}")

    r_global = _quat_spread_deg(rot_all, scene_ids=scene_ids_all)
    if r_global is not None:
        mean_r, std_r, min_r, max_r = r_global
        print(f" Rotation Spread [deg]: Mean {mean_r:.1f}, StdDev {std_r:.1f}, "
              f"Min {min_r:.1f}, Max {max_r:.1f}")

    # ------------------------------------------------------------------
    # Per-scene
    # ------------------------------------------------------------------
    print("\nPer-Scene Pose Spread:")
    for sc in sorted(scene_poses.keys()):
        ts = scene_poses[sc]["t"]
        rots_sc = scene_poses[sc]["rot"]
        line_parts = [f" Scene {sc}:"]

        t_summary = _translation_spread_mm(ts)
        if t_summary is not None:
            mean_t, std_t, min_t, max_t = t_summary
            line_parts.append(
                f"Translation [mm] Mean {mean_t:.1f} StdDev {std_t:.1f} Min {min_t:.1f} Max {max_t:.1f}"
            )

        r_summary = _quat_spread_deg(rots_sc, scene_ids=[sc] * len(rots_sc))
        if r_summary is not None:
            mean_r, std_r, min_r, max_r = r_summary
            line_parts.append(
                f"Rotation [deg] Mean {mean_r:.1f} StdDev {std_r:.1f} Min {min_r:.1f} Max {max_r:.1f}"
            )

        print(" | ".join(line_parts))

def _pose_rotation(pose):
    """Convert a pose record to a scipy Rotation object."""
    if "R" in pose:
        rmat = np.asarray(pose["R"], dtype=float).reshape(3, 3)
        return Rotation.from_matrix(rmat)

    if "rx" in pose:
        rvec = np.array(
            [pose["rx"], pose["ry"], pose["rz"]],
            dtype=float,
        )
        return Rotation.from_rotvec(rvec)

    return None


def _pose_translation(pose):
    """Extract the translation vector from a pose record."""
    if "tx" in pose:
        return np.array(
            [pose["tx"], pose["ty"], pose["tz"]],
            dtype=float,
        )

    if "t" in pose:
        return np.asarray(pose["t"], dtype=float)

    return None


def _pose_key_variants(value):
    """
    Generate possible identifiers for matching a pose record to an image.

    Pose files in I-BADAS may use integer indices, image filenames,
    or filename stems as keys.
    """
    variants = set()

    if value is None:
        return variants

    text = str(value)
    variants.add(text)

    path = Path(text)
    variants.add(path.name)
    variants.add(path.stem)

    try:
        number = int(text)
        variants.add(str(number))
        variants.add(f"{number:05d}")
        variants.add(f"{number:06d}")
        variants.add(f"{number:08d}")
    except (TypeError, ValueError):
        pass

    return variants


def _build_pose_lookup(pose_records):
    """
    Build a lookup table from scene/image identifiers to pose records.
    """
    lookup = {}

    for pose in pose_records:
        scene_id = pose["scene_id"]

        for key in _pose_key_variants(pose.get("image_id")):
            lookup[(scene_id, key)] = pose

    return lookup


def _find_pose_for_record(record, pose_lookup):
    """Find the pose corresponding to an image record."""
    scene_id = record["scene_id"]

    candidates = set()

    candidates.update(_pose_key_variants(record.get("image_id")))
    candidates.update(_pose_key_variants(record.get("file_name")))

    for key in candidates:
        pose = pose_lookup.get((scene_id, key))
        if pose is not None:
            return pose

    return None


def _rotation_distance_deg(reference_rotation, rotation, scene_id=None, ignore_sym=False, sym_axis='z'):
    relative = reference_rotation.inv() * rotation
    dist = float(relative.magnitude() * 180.0 / np.pi)
    
    if ignore_sym and scene_id is not None and int(scene_id) <= 4:
        vec = [0.0, 0.0, 0.0]
        vec[{'x': 0, 'y': 1, 'z': 2}[sym_axis.lower()]] = np.pi
        sym_rot = Rotation.from_rotvec(vec)
        relative_sym = reference_rotation.inv() * (rotation * sym_rot)
        dist_sym = float(relative_sym.magnitude() * 180.0 / np.pi)
        dist = min(dist, dist_sym)
        
    return dist


def _percentile_rank(values):
    """
    Convert values to percentile ranks in [0, 1].

    Lower values correspond to lower variation.
    """
    values = np.asarray(values, dtype=float)

    if len(values) == 0:
        return np.array([])

    order = np.argsort(values, kind="stable")
    ranks = np.empty(len(values), dtype=float)

    if len(values) == 1:
        ranks[order] = 0.0
        return ranks

    ranks[order] = np.arange(len(values)) / (len(values) - 1)

    return ranks


def export_variation_csv(records, pose_records, out_dir,
                         train_records=None, train_pose_records=None,
                         ignore_sym=False, sym_axis='y'):
    """
    Compute per-image illumination and pose variation scores and export them
    to a CSV file.

    The CSV contains raw measurements, per-scene variation scores,
    global variation scores, and percentile ranks.

    If train_records / train_pose_records are given, the CSV additionally
    contains the same deltas measured against the TRAIN data references
    (per train scene and over the whole train set), plus percentile ranks.
    """
    if PILImage is None:
        print("  [SKIP] Pillow not available for illumination analysis.")
        return

    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    pose_lookup = _build_pose_lookup(pose_records)

    rows = []

    # ---------------------------------------------------------------
    # Train reference statistics
    # ---------------------------------------------------------------

    use_train = bool(train_records) or bool(train_pose_records)
    if use_train:
        train_refs = _train_reference_stats(
            train_records or [], train_pose_records or []
        )
    else:
        train_refs = None

    # ---------------------------------------------------------------
    # Illumination measurements
    # ---------------------------------------------------------------

    scene_intensities = defaultdict(list)
    all_intensities = []

    for record in records:
        image_path = Path(record.get("_abs_path", ""))

        if not image_path.is_file():
            continue

        try:
            image = np.asarray(PILImage.open(image_path).convert("L"))
            mean_intensity = float(np.mean(image))
        except Exception:
            continue

        scene_intensities[record["scene_id"]].append(mean_intensity)
        all_intensities.append(mean_intensity)

    scene_intensity_mean = {
        scene_id: float(np.mean(values))
        for scene_id, values in scene_intensities.items()
        if values
    }

    global_intensity_mean = (
        float(np.mean(all_intensities))
        if all_intensities
        else np.nan
    )

    # ---------------------------------------------------------------
    # Pose measurements
    # ---------------------------------------------------------------

    scene_translations = defaultdict(list)
    scene_rotations = defaultdict(list)

    all_translations = []
    all_rotations = []

    matched_pose_count = 0

    for record in records:
        pose = _find_pose_for_record(record, pose_lookup)

        if pose is None:
            continue

        translation = _pose_translation(pose)
        rotation = _pose_rotation(pose)

        if translation is not None:
            scene_translations[record["scene_id"]].append(translation)
            all_translations.append(translation)

        if rotation is not None:
            scene_rotations[record["scene_id"]].append(rotation)
            all_rotations.append(rotation)

        if translation is not None or rotation is not None:
            matched_pose_count += 1

    # Scene translation centroids.
    scene_translation_centroids = {
        scene_id: np.mean(values, axis=0)
        for scene_id, values in scene_translations.items()
        if values
    }

    # Global translation centroid.
    global_translation_centroid = (
        np.mean(all_translations, axis=0)
        if all_translations
        else None
    )

    # Scene mean rotations.
    scene_rotation_means = {}

    for scene_id, rotations in scene_rotations.items():
        if rotations:
            scene_rotation_means[scene_id] = (
                Rotation.concatenate(rotations).mean()
            )

    # Global mean rotation.
    global_rotation_mean = None

    if all_rotations:
        global_rotation_mean = (
            Rotation.concatenate(all_rotations).mean()
        )

    # ---------------------------------------------------------------
    # Compute one row per image
    # ---------------------------------------------------------------

    for record in records:
        scene_id = record["scene_id"]

        row = {
            "scene_id": scene_id,
            "image_id": record["image_id"],
            "file_name": record["file_name"],
            "classification": record.get("classification", ""),
            "camera": record.get("camera", ""),
            "box_type": record.get("box_type", ""),
        }

        # -----------------------------------------------------------
        # Illumination
        # -----------------------------------------------------------

        image_path = Path(record.get("_abs_path", ""))

        mean_intensity = np.nan

        if image_path.is_file():
            try:
                image = np.asarray(
                    PILImage.open(image_path).convert("L")
                )
                mean_intensity = float(np.mean(image))
            except Exception:
                pass

        row["mean_intensity"] = mean_intensity

        if (
            np.isfinite(mean_intensity)
            and scene_id in scene_intensity_mean
        ):
            row["illumination_variation_scene"] = abs(
                mean_intensity - scene_intensity_mean[scene_id]
            )
        else:
            row["illumination_variation_scene"] = np.nan

        if np.isfinite(mean_intensity):
            row["illumination_variation_global"] = abs(
                mean_intensity - global_intensity_mean
            )
        else:
            row["illumination_variation_global"] = np.nan

        # -----------------------------------------------------------
        # Pose
        # -----------------------------------------------------------

        pose = _find_pose_for_record(record, pose_lookup)

        translation = None
        rotation = None

        if pose is not None:
            translation = _pose_translation(pose)
            rotation = _pose_rotation(pose)

        if translation is not None:
            row["tx"] = float(translation[0])
            row["ty"] = float(translation[1])
            row["tz"] = float(translation[2])

            scene_centroid = scene_translation_centroids.get(scene_id)

            if scene_centroid is not None:
                row["translation_variation_scene_mm"] = float(
                    np.linalg.norm(translation - scene_centroid)
                )

            if global_translation_centroid is not None:
                row["translation_variation_global_mm"] = float(
                    np.linalg.norm(
                        translation - global_translation_centroid
                    )
                )
        else:
            row["tx"] = np.nan
            row["ty"] = np.nan
            row["tz"] = np.nan
            row["translation_variation_scene_mm"] = np.nan
            row["translation_variation_global_mm"] = np.nan

        if rotation is not None:
            scene_rotation = scene_rotation_means.get(scene_id)

            if scene_rotation is not None:
                row["rotation_variation_scene_deg"] = (
                    _rotation_distance_deg(
                        scene_rotation,
                        rotation,
                        scene_id=scene_id,
                        ignore_sym=ignore_sym,
                        sym_axis=sym_axis
                    )
                )

            if global_rotation_mean is not None:
                row["rotation_variation_global_deg"] = (
                    _rotation_distance_deg(
                        global_rotation_mean,
                        rotation,
                        scene_id=scene_id,
                        ignore_sym=ignore_sym,
                        sym_axis=sym_axis
                    )
                )
        else:
            row["rotation_variation_scene_deg"] = np.nan
            row["rotation_variation_global_deg"] = np.nan

        # -----------------------------------------------------------
        # Deltas with respect to the TRAIN data
        # -----------------------------------------------------------

        if use_train:
            # Illumination
            ill_train_scene = np.nan
            ill_train_global = np.nan

            if np.isfinite(mean_intensity):
                ref_scene_int = train_refs["scene_intensity_mean"].get(scene_id)
                if ref_scene_int is not None:
                    ill_train_scene = abs(mean_intensity - ref_scene_int)

                if train_refs["global_intensity_mean"] is not None:
                    ill_train_global = abs(
                        mean_intensity - train_refs["global_intensity_mean"]
                    )

            # Translation
            trans_train_scene = np.nan
            trans_train_global = np.nan

            if translation is not None:
                ref_scene_t = train_refs["scene_translation_centroid"].get(scene_id)
                if ref_scene_t is not None:
                    trans_train_scene = float(
                        np.linalg.norm(translation - ref_scene_t)
                    )

                if train_refs["global_translation_centroid"] is not None:
                    trans_train_global = float(
                        np.linalg.norm(
                            translation - train_refs["global_translation_centroid"]
                        )
                    )

            # Rotation
            rot_train_scene = np.nan
            rot_train_global = np.nan

            if rotation is not None:
                ref_scene_r = train_refs["scene_rotation_mean"].get(scene_id)
                if ref_scene_r is not None:
                    rot_train_scene = _rotation_distance_deg(
                        ref_scene_r, rotation,
                        scene_id=scene_id,
                        ignore_sym=ignore_sym,
                        sym_axis=sym_axis
                    )

                if train_refs["global_rotation_mean"] is not None:
                    rot_train_global = _rotation_distance_deg(
                        train_refs["global_rotation_mean"], rotation,
                        scene_id=scene_id,
                        ignore_sym=ignore_sym,
                        sym_axis=sym_axis
                    )

            row["illumination_variation_train_scene"] = ill_train_scene
            row["illumination_variation_train_global"] = ill_train_global
            row["translation_variation_train_scene_mm"] = trans_train_scene
            row["translation_variation_train_global_mm"] = trans_train_global
            row["rotation_variation_train_scene_deg"] = rot_train_scene
            row["rotation_variation_train_global_deg"] = rot_train_global

        rows.append(row)

    # ---------------------------------------------------------------
    # Percentile ranks
    # ---------------------------------------------------------------

    score_columns = [
        "illumination_variation_scene",
        "illumination_variation_global",
        "translation_variation_scene_mm",
        "translation_variation_global_mm",
        "rotation_variation_scene_deg",
        "rotation_variation_global_deg",
    ]

    if use_train:
        score_columns += [
            "illumination_variation_train_scene",
            "illumination_variation_train_global",
            "translation_variation_train_scene_mm",
            "translation_variation_train_global_mm",
            "rotation_variation_train_scene_deg",
            "rotation_variation_train_global_deg",
        ]

    for column in score_columns:
        valid = np.isfinite(
            np.asarray([row[column] for row in rows], dtype=float)
        )

        values = np.asarray(
            [row[column] for row in rows],
            dtype=float,
        )

        ranks = np.full(len(rows), np.nan)

        if np.any(valid):
            ranks[valid] = _percentile_rank(values[valid])

        rank_column = f"{column}_percentile"

        for row, rank in zip(rows, ranks):
            row[rank_column] = rank

    # ---------------------------------------------------------------
    # Per-scene percentile ranks
    # ---------------------------------------------------------------

    scene_score_columns = [
        "illumination_variation_scene",
        "translation_variation_scene_mm",
        "rotation_variation_scene_deg",
    ]

    if use_train:
        scene_score_columns += [
            "illumination_variation_train_scene",
            "translation_variation_train_scene_mm",
            "rotation_variation_train_scene_deg",
        ]

    for score_column in scene_score_columns:
        for scene_id in sorted(
            set(row["scene_id"] for row in rows)
        ):
            indices = [
                i
                for i, row in enumerate(rows)
                if row["scene_id"] == scene_id
                and np.isfinite(row[score_column])
            ]

            if not indices:
                continue

            values = np.asarray(
                [rows[i][score_column] for i in indices],
                dtype=float,
            )

            ranks = _percentile_rank(values)

            for i, rank in zip(indices, ranks):
                rows[i][f"{score_column}_percentile"] = rank

    # ---------------------------------------------------------------
    # Sort by scene and then by each individual variation score.
    # The CSV itself is sorted by scene and illumination variation.
    # The rank columns allow sorting externally by any other factor.
    # ---------------------------------------------------------------

    rows.sort(
        key=lambda row: (
            str(row["scene_id"]),
            np.inf
            if not np.isfinite(row["illumination_variation_scene"])
            else row["illumination_variation_scene"],
        )
    )

    if not rows:
        print("  [SKIP] No image measurements could be generated.")
        return

    import csv

    csv_path = out_dir / "image_variation_scores.csv"

    fieldnames = list(rows[0].keys())

    with open(csv_path, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    print(f"  Saved: {csv_path}")
    print(f"  Images in CSV: {len(rows)}")
    print(f"  Images with matched poses: {matched_pose_count}")


# ---------------------------------------------------------------------------
# Train vs. test mean deltas (terminal output, Test minus Train)
# ---------------------------------------------------------------------------

def print_intensity_stat_deltas(test_stats, train_stats):
    """Delta of the global pixel-mean intensity (Test minus Train)."""
    if not test_stats or not train_stats:
        print(" [SKIP] Missing intensity statistics for train/test delta.")
        return

    print("\nIntensity Mean Delta (Test minus Train):")
    print(f"  Train mean: {train_stats['mean']:.2f}, "
          f"Test mean: {test_stats['mean']:.2f}, "
          f"Delta: {test_stats['mean'] - train_stats['mean']:+.2f}")


def print_6dof_stat_deltas(test_result, train_result):
    """
    Delta of the translation means and of the Euler XYZ rotation means
    (Test minus Train). Inputs are the tuples returned by print_6dof_stats.
    """
    if test_result is None or train_result is None:
        print(" [SKIP] Missing 6DOF statistics for train/test delta.")
        return

    t_mean_test, _, r_mean_test, _ = test_result
    t_mean_train, _, r_mean_train, _ = train_result

    dt = t_mean_test - t_mean_train
    dr = r_mean_test - r_mean_train

    print("\n6DOF Mean Delta (Test minus Train):")
    print("Translation [mm]:")
    print(f" X: {dt[0]:+.3f}")
    print(f" Y: {dt[1]:+.3f}")
    print(f" Z: {dt[2]:+.3f}")
    print(f" Euclidean norm: {np.linalg.norm(dt):.3f}")
    print("Rotation (Euler XYZ) [degrees]:")
    print(f" RX: {dr[0]:+.3f}")
    print(f" RY: {dr[1]:+.3f}")
    print(f" RZ: {dr[2]:+.3f}")



def print_train_test_mean_deltas(records, pose_records, train_records, train_pose_records, ignore_sym=False, sym_axis='z'):
    """
    Global and per-scene deltas between the test and train mean values
    (Test minus Train): mean image intensity, translation centroid, and the
    geodesic angle between the mean rotations.
    """
    if not train_records and not train_pose_records:
        print(" [SKIP] No train data available for train/test deltas.")
        return

    test_refs = _train_reference_stats(records, pose_records)
    train_refs = _train_reference_stats(train_records, train_pose_records)

    print("\nTrain vs. Test Mean Deltas (Test minus Train):")

    # ------------------------------------------------------------------
    # Illumination
    # ------------------------------------------------------------------
    print("\n Illumination (mean image intensity):")
    test_g = test_refs["global_intensity_mean"]
    train_g = train_refs["global_intensity_mean"]
    if test_g is not None and train_g is not None:
        print(f"  Global: Train {train_g:.2f}, Test {test_g:.2f}, "
              f"Delta {test_g - train_g:+.2f}")

    common = sorted(set(test_refs["scene_intensity_mean"])
                    & set(train_refs["scene_intensity_mean"]))
    for sc in common:
        tr = train_refs["scene_intensity_mean"][sc]
        te = test_refs["scene_intensity_mean"][sc]
        print(f"  Scene {sc}: Train {tr:.2f}, Test {te:.2f}, Delta {te - tr:+.2f}")

    # ------------------------------------------------------------------
    # Translation
    # ------------------------------------------------------------------
    print("\n Translation centroid [mm]:")
    test_c = test_refs["global_translation_centroid"]
    train_c = train_refs["global_translation_centroid"]
    if test_c is not None and train_c is not None:
        d = test_c - train_c
        print(f"  Global: Delta X {d[0]:+.1f}, Y {d[1]:+.1f}, Z {d[2]:+.1f}, "
              f"|Delta| {np.linalg.norm(d):.1f}")

    common = sorted(set(test_refs["scene_translation_centroid"])
                    & set(train_refs["scene_translation_centroid"]))
    for sc in common:
        d = (test_refs["scene_translation_centroid"][sc]
             - train_refs["scene_translation_centroid"][sc])
        print(f"  Scene {sc}: Delta X {d[0]:+.1f}, Y {d[1]:+.1f}, Z {d[2]:+.1f}, "
              f"|Delta| {np.linalg.norm(d):.1f}")

    # ------------------------------------------------------------------
    # Rotation
    # ------------------------------------------------------------------
    print("\n Rotation (geodesic angle between mean rotations) [deg]:")
    test_r = test_refs["global_rotation_mean"]
    train_r = train_refs["global_rotation_mean"]
    if test_r is not None and train_r is not None:
        print(f"  Global: {_rotation_distance_deg(train_r, test_r, scene_id=sc, ignore_sym=ignore_sym, sym_axis=sym_axis):.2f}")

    common = sorted(set(test_refs["scene_rotation_mean"]) & set(train_refs["scene_rotation_mean"]))
    for sc in common:
        ang = _rotation_distance_deg(train_refs["scene_rotation_mean"][sc],
                                     test_refs["scene_rotation_mean"][sc],
                                     scene_id=sc, ignore_sym=ignore_sym, sym_axis=sym_axis)
        print(f"  Scene {sc}: {ang:.2f}")


def fig_pose_3d_train_vs_test_hover(
    pose_records,
    train_pose_records,
    out_dir=None,
    cam_properties=None,
    voxel_size=135,
    sphere_coverage=100.0,
    show_points=False,
    show_vectors=True,
    show_ellipsoids=True,
):

    if not pose_records and not train_pose_records:
        print("  [SKIP] No pose data found for train/test comparison.")
        return

    sets = [
        ("Test", pose_records, "#fde725"),
        ("Train", train_pose_records, "#20a486"),
    ]

    rc = {
        "font.size": 14,
        "axes.titlesize": 16,
        "axes.labelsize": 14,
        "legend.fontsize": 12,
    }

    def get_image_metadata(p):
        """
        Extract the image name and path from a pose record.

        Add keys here if your dataset uses different field names.
        """

        # Common path keys.
        path_keys = (
            "image_path",
            "abs_path",
            "absolute_path",
            "file_path",
            "filepath",
            "path",
            "image",
        )

        # Common image-name keys.
        name_keys = (
            "image_name",
            "filename",
            "file_name",
            "name",
        )

        image_path = None
        image_name = None

        for key in path_keys:
            value = p.get(key)

            if isinstance(value, (str, os.PathLike)):
                image_path = os.fspath(value)
                break

        for key in name_keys:
            value = p.get(key)

            if isinstance(value, (str, os.PathLike)):
                image_name = os.fspath(value)
                break

        # Derive the image name from the path when necessary.
        if image_name is None and image_path is not None:
            image_name = os.path.basename(image_path)

        if image_name is None:
            image_name = "Unknown"

        if image_path is None:
            image_path = "Unknown"

        return image_name, image_path

    with plt.rc_context(rc):

        fig = plt.figure(figsize=(12, 9))
        ax = fig.add_subplot(111, projection="3d")

        ax.set_facecolor("white")

        ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
        ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
        ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

        length = 100.0
        alpha_val = 0.4

        all_x = [0.0]
        all_y = [0.0]
        all_z = [0.0]

        sphere_proxies = []
        point_proxies = []

        # Coordinates and metadata for points that survive voxel filtering.
        scatter_x = []
        scatter_y = []
        scatter_z = []
        scatter_c = []
        scatter_metadata = []

        for split_name, poses, color in sets:

            if not poses:
                continue

            all_translations = []
            filtered_translations = []

            # Prevent multiple points from occupying the same voxel
            # within the same split.
            occupied_voxels = set()

            for p in poses:

                t = _pose_translation(p)

                if t is None:
                    continue

                t = np.asarray(t, dtype=float).reshape(-1)

                if t.size != 3 or not np.all(np.isfinite(t)):
                    continue

                all_translations.append(t)

                # Apply voxel filtering.
                if voxel_size is not None and voxel_size > 0:

                    voxel_idx = (
                        int(np.floor(t[0] / voxel_size)),
                        int(np.floor(t[1] / voxel_size)),
                        int(np.floor(t[2] / voxel_size)),
                    )

                    if voxel_idx in occupied_voxels:
                        continue

                    occupied_voxels.add(voxel_idx)

                filtered_translations.append(t)

                # Store coordinates and metadata together.
                # This ensures that hover information corresponds
                # to the exact point retained by voxel filtering.
                if show_points:

                    image_name, image_path = get_image_metadata(p)

                    scatter_x.append(float(t[0]))
                    scatter_y.append(float(t[1]))
                    scatter_z.append(float(t[2]))
                    scatter_c.append(color)

                    scatter_metadata.append({
                        "name": image_name,
                        "path": image_path,
                        "set": split_name,
                        "translation": t.copy(),
                    })

                # Draw rotation vectors for retained poses.
                if show_vectors and p.get("R") is not None:

                    R = np.asarray(
                        p["R"], dtype=float
                    ).reshape(3, 3)

                    for i, axis_color in enumerate(["r", "g", "b"]):

                        ax.quiver(
                            t[0],
                            t[1],
                            t[2],
                            R[0, i] * length,
                            R[1, i] * length,
                            R[2, i] * length,
                            color=axis_color,
                            alpha=alpha_val,
                        )

            if not all_translations:
                continue

            t_arr_all = np.asarray(all_translations)
            t_arr_filtered = np.asarray(filtered_translations)

            # Legend entry for each split.
            if show_points and len(t_arr_filtered) > 0:

                point_proxies.append(
                    Line2D(
                        [0],
                        [0],
                        marker="o",
                        color="w",
                        markerfacecolor=color,
                        markersize=6,
                        label=f"{split_name} translations",
                    )
                )

            center = t_arr_all.mean(axis=0)

            if show_ellipsoids:

                dists = np.linalg.norm(
                    t_arr_all - center,
                    axis=1,
                )

                threshold = np.percentile(
                    dists,
                    sphere_coverage,
                )

                core_points = t_arr_all[dists <= threshold]

                # Compute the convex hull when enough points exist.
                if len(core_points) >= 4:

                    try:
                        hull = ConvexHull(core_points)

                        faces = [
                            core_points[simplex]
                            for simplex in hull.simplices
                        ]

                        poly = Poly3DCollection(
                            faces,
                            alpha=0.2,
                            facecolors=color,
                            linewidths=0,
                            shade=True,
                        )

                        ax.add_collection3d(poly)

                    except QhullError:
                        # Degenerate point configurations cannot
                        # define a 3D convex hull.
                        pass

                sphere_proxies.append(
                    Patch(
                        facecolor=color,
                        edgecolor=color,
                        alpha=0.3,
                        label=f"{split_name} convex hull",
                    )
                )

                if len(core_points) > 0:

                    all_x.extend([
                        core_points[:, 0].min(),
                        core_points[:, 0].max(),
                    ])

                    all_y.extend([
                        core_points[:, 1].min(),
                        core_points[:, 1].max(),
                    ])

                    all_z.extend([
                        core_points[:, 2].min(),
                        core_points[:, 2].max(),
                    ])

            else:

                all_x.extend(t_arr_filtered[:, 0])
                all_y.extend(t_arr_filtered[:, 1])
                all_z.extend(t_arr_filtered[:, 2])

        # ---------------------------------------------------------
        # Scatter plot and interactive hover annotations.
        # ---------------------------------------------------------

        if show_points and scatter_x:

            scatter = ax.scatter(
                scatter_x,
                scatter_y,
                scatter_z,
                s=12,
                c=scatter_c,
                alpha=1.0,
                depthshade=False,
                picker=True,
            )

            # Create the annotation once and update it on mouse movement.
            annot = ax.annotate(
                "",
                xy=(0, 0),
                xytext=(15, 15),
                textcoords="offset points",
                bbox={
                    "boxstyle": "round,pad=0.5",
                    "fc": "white",
                    "ec": "gray",
                    "alpha": 0.95,
                },
                arrowprops={
                    "arrowstyle": "->",
                    "color": "gray",
                },
                zorder=100,
            )

            annot.set_visible(False)

            # Store the current hovered point to avoid unnecessary redraws.
            hover_state = {"index": None}

            def on_move(event):

                if event.inaxes != ax or event.x is None or event.y is None:

                    if annot.get_visible():
                        annot.set_visible(False)
                        hover_state["index"] = None
                        fig.canvas.draw_idle()

                    return

                # Project the 3D coordinates into the current 2D view.
                xyz = np.column_stack((
                    scatter_x,
                    scatter_y,
                    scatter_z,
                ))

                projected_x, projected_y, projected_z = (
                    proj3d.proj_transform(
                        xyz[:, 0],
                        xyz[:, 1],
                        xyz[:, 2],
                        ax.get_proj(),
                    )
                )

                # Convert projected coordinates to display pixels.
                display_points = ax.transData.transform(
                    np.column_stack((
                        projected_x,
                        projected_y,
                    ))
                )

                mouse_position = np.array([
                    event.x,
                    event.y,
                ])

                distances = np.linalg.norm(
                    display_points - mouse_position,
                    axis=1,
                )

                # Find the nearest projected point.
                idx = int(np.argmin(distances))

                # Hover radius in screen pixels.
                hover_radius = 12

                if distances[idx] > hover_radius:

                    if annot.get_visible():
                        annot.set_visible(False)
                        hover_state["index"] = None
                        fig.canvas.draw_idle()

                    return

                # Do not redraw if the mouse remains over the same point.
                if (
                    hover_state["index"] == idx
                    and annot.get_visible()
                ):
                    return

                metadata = scatter_metadata[idx]

                image_name = metadata["name"]
                image_path = metadata["path"]
                split_name = metadata["set"]
                translation = metadata["translation"]

                # Position the annotation at the projected point.
                annot.xy = (
                    projected_x[idx],
                    projected_y[idx],
                )

                annot.set_text(
                    f"Image: {image_name}\n"
                    f"Path: {image_path}\n"
                    f"Split: {split_name}\n"
                    f"X: {translation[0]:.2f} mm\n"
                    f"Y: {translation[1]:.2f} mm\n"
                    f"Z: {translation[2]:.2f} mm"
                )

                annot.set_visible(True)
                hover_state["index"] = idx

                fig.canvas.draw_idle()

            # Keep the callback registered for the lifetime of the figure.
            fig.canvas.mpl_connect(
                "motion_notify_event",
                on_move,
            )

        # ---------------------------------------------------------
        # Rotation-vector legend.
        # ---------------------------------------------------------

        if show_vectors:

            ax.plot(
                [], [], [],
                color="r",
                label="X Axis Rotation",
            )

            ax.plot(
                [], [], [],
                color="g",
                label="Y Axis Rotation",
            )

            ax.plot(
                [], [], [],
                color="b",
                label="Z Axis Rotation",
            )

        # ---------------------------------------------------------
        # Camera frustums.
        # ---------------------------------------------------------

        if cam_properties:

            cmap = plt.get_cmap("viridis")
            safe_viridis_values = [0.1, 0.88]

            for idx, (cam_id, props) in enumerate(
                cam_properties.items()
            ):

                K = np.asarray(
                    props["cam_K"]
                ).reshape(3, 3)

                R = np.asarray(
                    props.get("R", np.eye(3))
                ).reshape(3, 3)

                t = np.asarray(
                    props.get("t", np.zeros(3))
                )

                min_depth = props.get("min_depth", 300.0)
                max_depth = props.get("max_depth", 1000.0)

                draw_max_depth = props.get(
                    "draw_max_depth",
                    max_depth,
                )

                color_val = safe_viridis_values[
                    idx % len(safe_viridis_values)
                ]

                cam_color = cmap(color_val)

                pts = draw_working_frustum(
                    ax,
                    K,
                    R,
                    t,
                    min_depth,
                    max_depth,
                    draw_max_depth=draw_max_depth,
                    color=cam_color,
                    label=f"{cam_id} Frustum",
                )

                all_x.extend(pts[:, 0])
                all_y.extend(pts[:, 1])
                all_z.extend(pts[:, 2])

        # ---------------------------------------------------------
        # Axes and formatting.
        # ---------------------------------------------------------

        if all_x:

            ax.set_xlim(min(all_x), max(all_x))
            ax.set_ylim(min(all_y), max(all_y))
            ax.set_zlim(min(all_z), max(all_z))

        ax.set_xlabel("X Translation [mm]", labelpad=20)
        ax.set_ylabel("Y Translation [mm]", labelpad=20)
        ax.set_zlabel("Z Translation [mm]", labelpad=20)

        ax.tick_params(axis="z", pad=10)

        handles, labels = ax.get_legend_handles_labels()

        handles = point_proxies + handles + sphere_proxies

        ax.legend(
            handles=handles,
            loc="upper left",
            bbox_to_anchor=(0.13, 0.78),
            ncol=1,
        )

        ax.view_init(elev=8, azim=-79)
        ax.invert_zaxis()

        plt.tight_layout()

        # Save the static PDF.
        if out_dir:

            out_path = (
                out_dir
                / "translation_rotation_3d_train_vs_test_vectors.pdf"
            )

            plt.savefig(
                out_path,
                bbox_inches="tight",
            )

            print(f"  Saved figure: {out_path}")

        # Keep the figure open for interactive inspection.
        plt.show(block=True)


def attach_image_metadata(pose_records, image_records, label=""):
    """Attach image names and paths to pose records."""

    def normalize_stem(value):
        stem = Path(str(value)).stem

        # Handle filenames such as rgb_00001.png.
        if stem.startswith("rgb_"):
            stem = stem[4:]

        # Normalize numeric IDs while preserving leading-zero equivalence.
        if stem.isdigit():
            stem = str(int(stem))

        return stem

    image_lookup = {}

    for record in image_records:
        scene_id = str(record.get("scene_id", "")).strip()
        filename = record.get("file_name", "")

        # Prefer the actual filename over the numeric image_id.
        image_stem = normalize_stem(
            filename if filename else record.get("image_id", "")
        )

        key = (scene_id, image_stem)

        # Store a list so duplicate keys cannot silently overwrite records.
        image_lookup.setdefault(key, []).append(record)

    matched = 0
    unmatched = []

    for pose in pose_records:
        scene_id = str(pose.get("scene_id", "")).strip()
        pose_image_id = str(pose.get("image_id", ""))

        image_stem = normalize_stem(pose_image_id)
        key = (scene_id, image_stem)

        candidates = image_lookup.get(key, [])

        if len(candidates) == 1:
            image_record = candidates[0]

            pose["image_name"] = image_record.get(
                "file_name",
                pose_image_id,
            )
            pose["image_path"] = image_record.get(
                "_abs_path",
                image_record.get("file_name", "Unknown"),
            )

            matched += 1

        else:
            pose["image_name"] = pose_image_id
            pose["image_path"] = (
                "Not found" if not candidates else "Ambiguous match"
            )

            if len(unmatched) < 10:
                unmatched.append({
                    "scene_id": scene_id,
                    "pose_image_id": pose_image_id,
                    "candidate_count": len(candidates),
                })

    print(
        f"  Matched {label}pose records to images: "
        f"{matched}/{len(pose_records)}"
    )

    if unmatched:
        print(f"  Unmatched {label}pose examples:")
        for item in unmatched:
            print(f"    {item}")

    return pose_records

def main():
    import matplotlib.ticker

    parser = argparse.ArgumentParser(
        description="Generate I-BADAS dataset statistics figures.")
    parser.add_argument("--root", type=str, default="/media/rtx5090/i-badas/test",
                        help="Path to the dataset root (containing scene folders)")
    parser.add_argument("--train_root", type=str, default="/media/rtx5090/i-badas/train",
                        help="Optional path to the train split (train/ or train/real/). "
                             "If given, train-referenced deltas are added to the "
                             "variation CSV.")
    parser.add_argument("--out", type=str, default="/media/rtx5090/i-badas/scripts/figures",
                        help="Output directory for figures")
    args = parser.parse_args()

    root = Path(args.root)
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)

    print("=" * 60)
    print("I-BADAS Dataset Statistics Generator")
    print("=" * 60)

    plt.rcParams.update({
        "font.family": "DejaVu Sans",
        "axes.titlepad": 10,
        "figure.dpi": 100,
        "savefig.facecolor": "white",
    })

    # --- Load data ---
    print("\n[1/4] Loading annotations...")
    scenes, global_cats = load_all_scenes(root)
    records, ann_records = aggregate(scenes)
    inject_abs_paths(records, scenes)
    inject_segmentation(ann_records, scenes)
    pose_records = load_poses(scenes)

    print(f"  Total images  : {len(records)}")
    print(f"  Total annots  : {len(ann_records)}")
    print(f"  Total poses   : {len(pose_records)}")
    print(f"  Categories    : {sorted(global_cats.keys())}")

    print("\n[1/4] Loading train data (reference for train-referenced deltas)...")
    train_records, train_pose_records = load_train_data(args.train_root)
    have_train = bool(train_records) or bool(train_pose_records)

    print("\n[1/4] Exporting Variation Metrics")
    export_variation_csv(records, pose_records, out_dir,
                         train_records=train_records,
                         train_pose_records=train_pose_records,
                         ignore_sym=True, sym_axis='y')

    print("\n[3/4] Generating figures...")
    # Paper selection
    fig_class_per_scene(records, out_dir)
    fig_mask_area_violin(ann_records, out_dir)
    fig_intensity_histogram_global(records, out_dir,
                                   train_records=train_records if train_records else None)

    test_int_stats = calc_intensity_statistics_global(
        records, label="Test" if have_train else "Dataset")
    if have_train and train_records:
        print()
        train_int_stats = calc_intensity_statistics_global(train_records, label="Train")
        print_intensity_stat_deltas(test_int_stats, train_int_stats)

    fig_pose_3d_with_frames(pose_records, out_dir, my_cameras)
    

    attach_image_metadata(
        pose_records=pose_records,
        image_records=records,
        label="test ",
    )

    attach_image_metadata(
        pose_records=train_pose_records,
        image_records=train_records,
        label="train ",
    )

    if have_train:
        fig_pose_3d_train_vs_test(pose_records=pose_records, train_pose_records=train_pose_records, 
                                  task2_parity="both", out_dir=out_dir, cam_properties=my_cameras,
                                  show_points=False,
                                  show_vectors=True,
                                  show_ellipsoids=True,
                                  voxel_size=135)
        # --- Interactive 3D pose visualization ---
        print("\n[Interactive] Generating 3D train/test pose visualization...")

        #fig_pose_3d_train_vs_test_hover(
        #    pose_records=pose_records,
        #    train_pose_records=train_pose_records,
        #    out_dir=out_dir,
        #    voxel_size=135,
        #   sphere_coverage=100.0,
        #    show_points=True,
        #    show_vectors=True,
        #    show_ellipsoids=True,
        #)

    test_6dof = print_6dof_stats(pose_records, label="Test" if have_train else None)
    if have_train and train_pose_records:
        train_6dof = print_6dof_stats(train_pose_records, label="Train")
        print_6dof_stat_deltas(test_6dof, train_6dof)

    fig_spatial_heatmap_ungrouped_common_legend(ann_records, out_dir)

    calc_variability_metrics(records, pose_records,
                             label=" (Test)" if have_train else "", ignore_sym=True, sym_axis="y")
    if have_train:
        print()
        calc_variability_metrics(train_records, train_pose_records, label=" (Train)", ignore_sym=True, sym_axis="y")
        print_train_test_mean_deltas(records, pose_records,
                                     train_records, train_pose_records, ignore_sym=True, sym_axis="y")

    print("\n[4/4] Done.")
    print(f"  All figures written to: {out_dir.resolve()}")
    print("=" * 60)


if __name__ == "__main__":
    main()