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

Generates two separate figures:

1. Qualitative comparison:
   - 3DGS and TRELLIS reconstructions
   - Four representative object classes
   - Native Matplotlib viridis colorbar (0.0–1.5 mm)
   - Optional right-edge cropping of every input PNG

2. Quantitative comparison:
   - Chamfer distance (mm)
   - Hausdorff distance (mm)
   - Absolute scale error (%)
   - All object classes, preserving underscores in class names

Input files
-----------
/media/rtx5090/IASSET/tmp/metrics_per_class.csv

/media/rtx5090/IASSET/tmp/figures/
    3DGS_C_Steel_Ball_L_dev.png
    3DGS_FestoY_dev.png
    3DGS_GF_Plain_Screw_M8_dev.png
    3DGS_MM_Spring_dev.png
    TRELLIS_C_Steel_Ball_L_dev.png
    TRELLIS_FestoY_dev.png
    TRELLIS_GF_Plain_Screw_M8_dev.png
    TRELLIS_GF_Plain_Screw_M8_colorbar.pdf  # Not required
    TRELLIS_MM_Spring_dev.png

Output files
------------
qualitative_comparison.pdf
qualitative_comparison.png
quantitative_comparison.pdf
quantitative_comparison.png

Dependencies
------------
pip install numpy pandas matplotlib pillow
"""

from pathlib import Path
import warnings

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

from matplotlib.gridspec import GridSpec
from matplotlib.lines import Line2D
from matplotlib.ticker import MaxNLocator, FuncFormatter
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
from PIL import Image

from matplotlib.patches import Patch
from matplotlib.ticker import LogLocator, NullLocator



# ============================================================
# Configuration
# ============================================================

BASE_DIR = Path("/media/rtx5090/IASSET/tmp")

CSV_PATH = BASE_DIR / "metrics_per_class.csv"
FIGURES_DIR = BASE_DIR / "figures"

# Output paths.
OUTPUT_QUALITATIVE_PDF = BASE_DIR / "qualitative_geometry_comparison.pdf"
OUTPUT_QUALITATIVE_PNG = BASE_DIR / "qualitative_geometry_comparison.png"

OUTPUT_QUANTITATIVE_PDF = BASE_DIR / "quantitative_geometry_comparison.pdf"
OUTPUT_QUANTITATIVE_PNG = BASE_DIR / "quantitative_geometry_comparison.png"


# ------------------------------------------------------------
# Figure dimensions
# ------------------------------------------------------------

# Qualitative figure: double-column width.
QUALITATIVE_WIDTH = 7.16
QUALITATIVE_HEIGHT = 2.55

# Quantitative figure: single-column width.
QUANTITATIVE_WIDTH = 3.50
QUANTITATIVE_HEIGHT = 7.2

DPI = 600


# ------------------------------------------------------------
# Typography
# ------------------------------------------------------------

# Single parameter controlling font sizes throughout both figures.
FONT_SIZE = 8

# ------------------------------------------------------------
# Input image cropping
# ------------------------------------------------------------

# Fraction removed from the RIGHT edge of every input PNG.
#
# 0.00 = no cropping
# 0.05 = crop the rightmost 5%
# 0.10 = crop the rightmost 10%
#
# Applied to each input PNG before plotting, not to the figure.
CROP_RIGHT_FRACTION = 0.165


# ------------------------------------------------------------
# Colorbar
# ------------------------------------------------------------

COLORBAR_MIN = 0.0
COLORBAR_MAX = 1.5
COLORBAR_LABEL = "Deviation [mm]"

# Colorbar position in figure coordinates:
# [left, bottom, width, height].
#
# The colorbar is placed outside the image grid so its ticks,
# label, and pointed end do not get clipped by the image axes.
COLORBAR_AXES = [0.895, 0.14, 0.025, 0.72]


# ------------------------------------------------------------
# Methods and colors
# ------------------------------------------------------------

METHODS = ["3DGS", "TRELLIS"]

VIRIDIS = mpl.colormaps["viridis"]

METHOD_COLORS = {
    "3DGS": VIRIDIS(0.25),
    "TRELLIS": VIRIDIS(0.80),
}


# Output paths.
OUTPUT_COMPACT_PDF = BASE_DIR / "quantitative_geometry_compact.pdf"
OUTPUT_COMPACT_PNG = BASE_DIR / "quantitative_geometry_compact.png"
 
# Geometry. The figure height is derived automatically from the font
# size, the number of rows, and COMPACT_ROW_PLOT_HEIGHT, so rotated
# class labels and the legend never clip.
COMPACT_WIDTH = 7.16             # inches, double-column width
COMPACT_ROW_PLOT_HEIGHT = 1.40   # inches of plotting area per row
COMPACT_N_ROWS = 1               # 2 rows of 16 classes; 1 gives a single strip
 
# Single parameter controlling all text in the compact figure.
COMPACT_FONT_SIZE = 8
 
# Class order: None (CSV order), "alphabetical", or a metric column name
# such as "chamfer_mm" (ascending, mean over both methods).
COMPACT_SORT_BY = None
 
# Same exclusion as in make_quantitative_figure(). Use set() to keep all.
COMPACT_EXCLUDED_CLASSES = {"GF_Collar_S"}
 
# Method colors (viridis, consistent with the other figures).
COMPACT_METHOD_COLORS = METHOD_COLORS
 
# Marker encodes the metric, color encodes the method.
COMPACT_MM_METRICS = [
    {"column": "chamfer_mm", "label": "Chamfer",   "marker": "o", "size": 12},
    {"column": "hd_mm",      "label": "Hausdorff", "marker": "^", "size": 14},
]
COMPACT_PCT_METRIC = {
    "column": "scale_err_abs", "label": "Scale error", "marker": "D", "size": 9,
}
 
# Horizontal slot offsets inside one class group (group pitch = 1.0).
# Left pair: [mm] axis (3DGS, TRELLIS). Right pair: [%] axis (3DGS, TRELLIS).
COMPACT_MM_OFFSETS = (-0.33, -0.13)
COMPACT_PCT_OFFSETS = (0.13, 0.33)
 
COMPACT_BAND_COLOR = "#EFEFEF"   # alternating class background

# ------------------------------------------------------------
# Qualitative examples
# ------------------------------------------------------------

# The strings are the exact class identifiers used in the CSV
# and image filenames.
#
# GF_Collar_S is intentionally excluded.
EXAMPLES = [
    "C_Steel_Ball_L",
    "FestoY",
    "GF_Plain_Screw_M8",
    "MM_Spring",
]


# ------------------------------------------------------------
# Quantitative metrics
# ------------------------------------------------------------

# Layout of the figure:
#   "vertical"   : classes on the y-axis, one panel per metric side by side
#                  (single column, QUANTITATIVE_WIDTH x QUANTITATIVE_HEIGHT).
#   "horizontal" : classes on the x-axis, panels stacked
#                  (double column, HORIZONTAL_WIDTH x HORIZONTAL_HEIGHT).
QUANTITATIVE_LAYOUT = "horizontal"
 
# Figure size in inches for the horizontal layout. The vertical layout
# keeps using QUANTITATIVE_WIDTH and QUANTITATIVE_HEIGHT.
HORIZONTAL_WIDTH = 7.16
HORIZONTAL_HEIGHT = 3.8
 
# Scale of the Chamfer axis: "log" or "linear".
CHAMFER_SCALE = "linear"
 
# Rotation of the class labels in degrees (0 = horizontal).
# Vertical layout: the left margin adapts to the angle.
# Horizontal layout: the bottom margin adapts to the angle; use 30 to 90
# (0 would make the labels overlap).
CLASS_LABEL_ROTATION = 40
 
# Class order. SORT_BY: None (CSV order), "alphabetical", or a metric
# column such as "chamfer_mm" or "scale_err_abs".
# SORT_METHOD: None sorts by the mean over both methods; a method name
# such as "TRELLIS" sorts by that method only.
# The first class is drawn at the top (vertical) or at the left
# (horizontal).
SORT_BY = "chamfer_mm"
SORT_METHOD = "TRELLIS"
SORT_DESCENDING = False
 
# Print the numeric values next to the marks: None (off), "chamfer",
# "scale" or "both". Number formats are set per metric in METRICS
# ("value_format"). In the horizontal layout the values are rotated 90
# degrees and placed above the marks.
SHOW_VALUES = "both"
VALUE_FONT_SIZE = 6

# Light background band behind every other class (first, third, ...).
SHOW_BANDS = True
BAND_COLOR = "#EFEFEF"

 
# Bar thickness and offset of each method within a class
# (class pitch = 1.0).
BAR_HEIGHT = 0.34
METHOD_OFFSETS = {
    "3DGS": -0.19,
    "TRELLIS": 0.19,
}
 
# "bar"      : bars (Chamfer)
# "lollipop" : line with dot (scale error)
METRICS = [
    {
        "column": "chamfer_mm",
        "title": "Chamfer distance",
        "xlabel": "Chamfer (mm)",
        "kind": "bar",
        "value_format": "{:.2f}",
    },
    {
        "column": "scale_err_abs",
        "title": "Absolute scale error",
        "xlabel": "Scale error (%)",
        "kind": "lollipop",
        "value_format": "{:.1f}",
    },
]



# ============================================================
# Matplotlib publication style
# ============================================================

mpl.rcParams.update({
    # Typography.
    "font.family": "serif",
    "font.serif": [
        "STIX Two Text",
        "STIXGeneral",
        "DejaVu Serif",
    ],
    "mathtext.fontset": "stix",

    "font.size": FONT_SIZE,
    "axes.titlesize": FONT_SIZE,
    "axes.labelsize": FONT_SIZE,
    "xtick.labelsize": FONT_SIZE,
    "ytick.labelsize": FONT_SIZE,
    "legend.fontsize": FONT_SIZE,

    # All text remains black.
    "text.color": "black",
    "axes.labelcolor": "black",
    "axes.titlecolor": "black",
    "xtick.color": "black",
    "ytick.color": "black",

    # Lines and axes.
    "axes.linewidth": 0.65,
    "lines.linewidth": 0.9,
    "xtick.major.width": 0.6,
    "ytick.major.width": 0.6,
    "xtick.major.size": 2.5,
    "ytick.major.size": 0,

    # Background.
    "figure.facecolor": "white",
    "axes.facecolor": "white",
    "savefig.facecolor": "white",

    "axes.edgecolor": "black",
    "grid.color": "#D9D9D9",
    "grid.linewidth": 0.45,
    "grid.alpha": 0.8,

    # Vector-friendly PDF output.
    "pdf.fonttype": 42,
    "ps.fonttype": 42,
    "svg.fonttype": "none",

    # Export resolution.
    "savefig.dpi": DPI,
})


# ============================================================
# Validation and loading
# ============================================================

def load_metrics(path: Path) -> pd.DataFrame:
    """Load and validate the per-class metrics CSV."""

    if not path.exists():
        raise FileNotFoundError(
            f"Metrics CSV not found: {path}"
        )

    df = pd.read_csv(path)

    required = {
        "method",
        "cls",
        "chamfer_mm",
        "hd_mm",
        "scale_err_abs",
    }

    missing = required.difference(df.columns)

    if missing:
        raise ValueError(
            f"Missing required CSV columns: {sorted(missing)}"
        )

    df["method"] = df["method"].astype(str).str.strip()
    df["cls"] = df["cls"].astype(str).str.strip()

    # Keep only the methods being compared.
    df = df[df["method"].isin(METHODS)].copy()

    # Convert relevant metrics to numeric values.
    for column in [
        "chamfer_mm",
        "hd_mm",
        "scale_err_abs",
    ]:
        df[column] = pd.to_numeric(
            df[column],
            errors="coerce",
        )

    df = df.replace(
        [np.inf, -np.inf],
        np.nan,
    )

    # Check for duplicate method/class pairs.
    duplicates = df.duplicated(
        subset=["method", "cls"],
        keep=False,
    )

    if duplicates.any():
        pairs = df.loc[
            duplicates,
            ["method", "cls"],
        ]

        raise ValueError(
            "Duplicate method/class entries found:\n"
            f"{pairs.to_string(index=False)}"
        )

    if df.empty:
        raise ValueError(
            "No measurements found for 3DGS or TRELLIS."
        )

    return df


# ============================================================
# Image loading and cropping
# ============================================================

def load_image(path: Path):
    """
    Load an RGB image and crop its right edge.

    Cropping is performed on the original image before insertion
    into the figure. The image height remains unchanged.
    """

    if not 0.0 <= CROP_RIGHT_FRACTION < 1.0:
        raise ValueError(
            "CROP_RIGHT_FRACTION must be >= 0 and < 1."
        )

    if not path.exists():
        warnings.warn(
            f"Image not found: {path}",
            stacklevel=2,
        )
        return None

    try:
        with Image.open(path) as im:
            im = im.convert("RGB")

            width, height = im.size

            cropped_width = max(
                1,
                int(round(
                    width * (1.0 - CROP_RIGHT_FRACTION)
                )),
            )

            # Crop from x=0 to the new right boundary.
            im = im.crop(
                (0, 0, cropped_width, height)
            )

            return np.asarray(im)

    except Exception as exc:
        warnings.warn(
            f"Could not read image {path}: {exc}",
            stacklevel=2,
        )
        return None


def image_path(method: str, cls: str) -> Path:
    """Return the expected reconstruction PNG path."""

    return FIGURES_DIR / f"{method}_{cls}_dev.png"


# ============================================================
# Save figures
# ============================================================

def save_figure(
    fig,
    pdf_path: Path,
    png_path: Path,
):
    """
    Save PDF and PNG without cropping the figure canvas.

    Using bbox_inches=None preserves the configured dimensions
    and avoids unintended changes to the figure's aspect ratio.
    """

    fig.savefig(
        pdf_path,
        format="pdf",
        dpi=DPI,
        bbox_inches=None,
        pad_inches=0,
    )

    fig.savefig(
        png_path,
        format="png",
        dpi=DPI,
        bbox_inches=None,
        pad_inches=0,
    )

    plt.close(fig)

    print(f"Saved PDF: {pdf_path}")
    print(f"Saved PNG: {png_path}")


# ============================================================
# Qualitative comparison
# ============================================================

def make_qualitative_figure():
    """
    Create the qualitative comparison matrix.

    Layout:
        Columns: object classes
        Rows:    3DGS and TRELLIS
        Right:   native Matplotlib deviation colorbar

    The colorbar is independent of the image grid and is placed
    at the far right of the figure.
    """

    n_examples = len(EXAMPLES)

    fig = plt.figure(
        figsize=(
            QUALITATIVE_WIDTH,
            QUALITATIVE_HEIGHT,
        ),
        facecolor="white",
    )

    # The grid contains only the image matrix.
    # The colorbar has a dedicated figure-level axes.
    #
    # A slightly larger left margin accommodates the rotated
    # method labels. The right margin leaves space for the
    # independently positioned colorbar.
    gs = GridSpec(
        3,
        n_examples,
        figure=fig,
        height_ratios=[0.20, 1.0, 1.0],
        left=0.095,
        right=0.86,
        top=0.96,
        bottom=0.04,
        hspace=0.04,
        wspace=0.08,
    )

    first_image_axes = {}

    # --------------------------------------------------------
    # Column headers
    # --------------------------------------------------------

    for col, cls in enumerate(EXAMPLES):

        ax = fig.add_subplot(gs[0, col])
        ax.axis("off")

        ax.text(
            0.5,
            0.5,
            cls,
            ha="center",
            va="center",
            fontsize=FONT_SIZE,
            fontweight="semibold",
            color="black",
            transform=ax.transAxes,
        )

    # --------------------------------------------------------
    # Reconstruction images
    # --------------------------------------------------------

    for row, method in enumerate(METHODS, start=1):

        for col, cls in enumerate(EXAMPLES):

            ax = fig.add_subplot(gs[row, col])

            img = load_image(
                image_path(method, cls)
            )

            if img is not None:
                ax.imshow(
                    img,
                    interpolation="nearest",
                )
            else:
                ax.text(
                    0.5,
                    0.5,
                    "Not available",
                    ha="center",
                    va="center",
                    fontsize=FONT_SIZE,
                    color="black",
                    transform=ax.transAxes,
                )

            ax.set_xticks([])
            ax.set_yticks([])

            for spine in ax.spines.values():
                spine.set_visible(False)

            ax.patch.set_edgecolor("#DDDDDD")
            ax.patch.set_linewidth(0.4)

            if col == 0:
                first_image_axes[method] = ax

    # --------------------------------------------------------
    # Method labels
    # --------------------------------------------------------

    for method, ax in first_image_axes.items():

        ax.text(
            -0.035,
            0.5,
            method,
            rotation=90,
            ha="right",
            va="center",
            fontsize=FONT_SIZE,
            fontweight="bold",
            color="black",
            transform=ax.transAxes,
            clip_on=False,
        )

    # --------------------------------------------------------
    # Native Matplotlib colorbar
    # --------------------------------------------------------

    cmap = mpl.colormaps["viridis"]

    norm = Normalize(
        vmin=COLORBAR_MIN,
        vmax=COLORBAR_MAX,
    )

    sm = ScalarMappable(
        norm=norm,
        cmap=cmap,
    )
    sm.set_array([])

    # Dedicated axes outside the image grid.
    #
    # Increase the first value to move the colorbar right.
    # Decrease it if more room is needed for the label.
    colorbar_ax = fig.add_axes(
        COLORBAR_AXES
    )

    cbar = fig.colorbar(
        sm,
        cax=colorbar_ax,
        orientation="vertical",
        extend="max",
        extendfrac=0.06,
    )

    cbar.set_label(
        COLORBAR_LABEL,
        fontsize=FONT_SIZE,
        color="black",
        labelpad=5,
    )

    # Ticks from 0.0 through 1.4 mm in 0.2 mm increments.
    cbar.set_ticks(
        np.arange(0.0, 1.51, 0.2)
    )

    cbar.ax.tick_params(
        labelsize=FONT_SIZE,
        colors="black",
        width=0.6,
        length=2.5,
        pad=2,
    )

    cbar.outline.set_edgecolor("black")
    cbar.outline.set_linewidth(0.65)

    # --------------------------------------------------------
    # Export
    # --------------------------------------------------------

    save_figure(
        fig,
        OUTPUT_QUALITATIVE_PDF,
        OUTPUT_QUALITATIVE_PNG,
    )


# ============================================================
# Quantitative comparison
# ============================================================

def _sort_classes(
    df: pd.DataFrame,
    classes: list,
    sort_by,
    sort_method,
    descending: bool,
):
    """Return classes in the requested order (missing values last)."""
 
    if sort_by is None:
        return classes
 
    if sort_by == "alphabetical":
        return sorted(
            classes,
            key=str.lower,
            reverse=descending,
        )
 
    if sort_by not in df.columns:
        raise ValueError(
            f"Unknown sort_by value: {sort_by!r}"
        )
 
    subset = df[df["cls"].isin(classes)]
 
    if sort_method is not None:
 
        if sort_method not in METHODS:
            raise ValueError(
                f"Unknown sort_method: {sort_method!r}"
            )
 
        subset = subset[subset["method"] == sort_method]
 
    key = subset.groupby("cls")[sort_by].mean()
 
    valid = [c for c in classes if pd.notna(key.get(c, np.nan))]
    missing = [c for c in classes if c not in valid]
 
    valid = sorted(
        valid,
        key=lambda c: key[c],
        reverse=descending,
    )
 
    return valid + missing
 
 
def add_metric_panel(
    ax,
    df: pd.DataFrame,
    classes: list,
    metric: dict,
    show_class_labels: bool,
    chamfer_scale: str,
    label_rotation: float,
    show_values: bool = False,
    layout: str = "vertical",
    bands: bool = False,
):
    """
    Plot one metric panel.
 
    layout == "vertical"   : classes on the y-axis, values on the x-axis.
    layout == "horizontal" : classes on the x-axis, values on the y-axis.
 
    kind == "bar"      : grouped bars (one per method). On a log axis the
                         bars start at the lower axis limit (a power of
                         ten below the data).
    kind == "lollipop" : line from zero to the value, with a dot.
 
    If show_values is True, each value is printed next to its mark and
    the value-axis limit is widened so the text stays inside the axes.
    If bands is True, every other class gets a light background band.
    """
 
    horizontal = (layout == "horizontal")
 
    column = metric["column"]
    kind = metric["kind"]
    use_log = (kind == "bar" and chamfer_scale == "log")
 
    n_classes = len(classes)
    pos = np.arange(n_classes)
 
    # Axis-dependent helpers: the "value axis" carries the metric,
    # the "class axis" carries the classes.
    value_axis = ax.yaxis if horizontal else ax.xaxis
    value_axis_name = "y" if horizontal else "x"
    set_value_scale = ax.set_yscale if horizontal else ax.set_xscale
    set_value_lim = ax.set_ylim if horizontal else ax.set_xlim
 
    # --------------------------------------------------------
    # Collect valid values
    # --------------------------------------------------------
 
    records = []
 
    for method in METHODS:
 
        subset = (
            df[df["method"] == method]
            .set_index("cls")
        )
 
        for i, cls in enumerate(classes):
 
            if cls not in subset.index:
                continue
 
            value = subset.loc[cls, column]
 
            if pd.isna(value):
                continue
 
            value = float(value)
 
            # Logarithmic axes cannot display zero or negative values.
            if use_log and value <= 0:
                continue
 
            records.append(
                (method, pos[i] + METHOD_OFFSETS[method], value)
            )
 
    if not records:
        raise ValueError(
            f"No valid values for metric {column!r}."
        )
 
    all_values = np.array([r[2] for r in records])
 
    # --------------------------------------------------------
    # Value-axis scale, limits, and bar baseline
    # --------------------------------------------------------
 
    value_format = metric.get("value_format", "{:.3g}")
 
    # Fraction of the value axis reserved for the printed values.
    frac = 0.0
 
    if show_values:
 
        bbox = ax.get_position()
 
        if horizontal:
            axis_len_in = bbox.height * ax.figure.get_figheight()
        else:
            axis_len_in = bbox.width * ax.figure.get_figwidth()
 
        longest = max(
            len(value_format.format(v)) for v in all_values
        )
 
        label_len_in = longest * VALUE_FONT_SIZE * 0.52 / 72.0 + 0.06
 
        frac = min(label_len_in / axis_len_in, 0.6)
 
    vmax = max(all_values.max(), 1e-9)
 
    if use_log:
 
        baseline = 10 ** np.floor(np.log10(all_values.min()))
 
        if baseline >= all_values.min():
            baseline /= 10.0
 
        set_value_scale("log")
 
        # Place the largest value at (1 - frac) of the axis length.
        span = np.log10(vmax / baseline)
 
        upper = max(
            vmax * 1.25,
            baseline * 10 ** (span / (1.0 - frac)),
        )
 
        set_value_lim(baseline, upper)
 
    else:
 
        baseline = 0.0
 
        upper = max(vmax * 1.08, vmax / (1.0 - frac))
 
        set_value_lim(0.0, upper)
 
    # --------------------------------------------------------
    # Alternating class bands (behind everything else)
    # --------------------------------------------------------
 
    if bands:
 
        for i in range(0, n_classes, 2):
 
            if horizontal:
                ax.axvspan(
                    i - 0.5,
                    i + 0.5,
                    facecolor=BAND_COLOR,
                    edgecolor="none",
                    linewidth=0,
                    zorder=0,
                )
            else:
                ax.axhspan(
                    i - 0.5,
                    i + 0.5,
                    facecolor=BAND_COLOR,
                    edgecolor="none",
                    linewidth=0,
                    zorder=0,
                )
 
    # --------------------------------------------------------
    # Draw
    # --------------------------------------------------------
 
    for method in METHODS:
 
        ps = np.array(
            [r[1] for r in records if r[0] == method]
        )
        vs = np.array(
            [r[2] for r in records if r[0] == method]
        )
 
        if ps.size == 0:
            continue
 
        color = METHOD_COLORS[method]
 
        if kind == "bar":
 
            if horizontal:
                ax.bar(
                    ps,
                    vs - baseline,
                    bottom=baseline,
                    width=BAR_HEIGHT,
                    color=color,
                    edgecolor="none",
                    zorder=3,
                )
            else:
                ax.barh(
                    ps,
                    vs - baseline,
                    left=baseline,
                    height=BAR_HEIGHT,
                    color=color,
                    edgecolor="none",
                    zorder=3,
                )
 
            offset = 2.0
 
        else:
 
            if horizontal:
                ax.vlines(
                    ps,
                    0.0,
                    vs,
                    color=color,
                    linewidth=0.8,
                    zorder=2,
                )
                ax.scatter(
                    ps,
                    vs,
                    s=13,
                    marker="o",
                    color=color,
                    edgecolors="white",
                    linewidths=0.35,
                    zorder=3,
                )
            else:
                ax.hlines(
                    ps,
                    0.0,
                    vs,
                    color=color,
                    linewidth=0.8,
                    zorder=2,
                )
                ax.scatter(
                    vs,
                    ps,
                    s=13,
                    marker="o",
                    color=color,
                    edgecolors="white",
                    linewidths=0.35,
                    zorder=3,
                )
 
            offset = 4.0
 
        if show_values:
 
            for p, v in zip(ps, vs):
 
                if horizontal:
                    # Vertical text above the mark.
                    ax.annotate(
                        value_format.format(v),
                        xy=(p, v),
                        xytext=(0, offset),
                        textcoords="offset points",
                        ha="center",
                        va="bottom",
                        rotation=90,
                        fontsize=VALUE_FONT_SIZE,
                        color="black",
                        zorder=5,
                    )
                else:
                    ax.annotate(
                        value_format.format(v),
                        xy=(v, p),
                        xytext=(offset, 0),
                        textcoords="offset points",
                        ha="left",
                        va="center",
                        fontsize=VALUE_FONT_SIZE,
                        color="black",
                        zorder=5,
                    )
 
    # --------------------------------------------------------
    # Titles and labels: always black
    # --------------------------------------------------------
 
    if horizontal:
 
        # The y-label already names the metric, so no panel title is
        # drawn; this saves vertical space between the stacked panels.
        ax.set_ylabel(
            metric["xlabel"],
            labelpad=3,
            color="black",
        )
 
    else:
 
        ax.set_title(
            metric["title"],
            loc="left",
            pad=5,
            fontweight="semibold",
            color="black",
        )
 
        ax.set_xlabel(
            metric["xlabel"],
            labelpad=4,
            color="black",
        )
 
    # --------------------------------------------------------
    # Class labels (exact names, underscores preserved)
    # --------------------------------------------------------
 
    if horizontal:
 
        ax.set_xticks(pos)
        ax.set_xlim(-0.5, n_classes - 0.5)
 
        if show_class_labels:
 
            if label_rotation >= 80:
                ha, mode = "center", "default"
            else:
                ha, mode = "right", "anchor"
 
            # The end of each label is anchored at its tick and the text
            # rotates around that point.
            ax.set_xticklabels(
                classes,
                rotation=label_rotation,
                ha=ha,
                va="top",
                rotation_mode=mode,
                color="black",
            )
        else:
            ax.set_xticklabels([])
 
        ax.tick_params(axis="x", length=0, pad=2)
 
    else:
 
        ax.set_yticks(pos)
 
        if show_class_labels:
            ax.set_yticklabels(
                classes,
                rotation=label_rotation,
                ha="right",
                va="center",
                rotation_mode="anchor",
                color="black",
            )
        else:
            ax.set_yticklabels([])
 
        ax.tick_params(axis="y", length=0, pad=2)
 
        ax.invert_yaxis()
        ax.set_ylim(
            n_classes - 0.5,
            -0.5,
        )
 
    # --------------------------------------------------------
    # Grid and spines
    # --------------------------------------------------------
 
    ax.set_axisbelow(True)
 
    other_axis_name = "x" if horizontal else "y"
 
    ax.grid(
        axis=value_axis_name,
        linestyle="-",
        linewidth=0.45,
        alpha=0.8,
        zorder=0,
    )
 
    ax.grid(
        axis=other_axis_name,
        visible=False,
    )
 
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
 
    if not horizontal:
        ax.spines["left"].set_visible(False)
 
    # --------------------------------------------------------
    # Value-axis ticks
    # --------------------------------------------------------
 
    if use_log:
 
        value_axis.set_major_locator(
            mpl.ticker.LogLocator(base=10, numticks=5)
        )
 
        value_axis.set_major_formatter(
            FuncFormatter(lambda value, _: f"{value:g}")
        )
 
        value_axis.set_minor_formatter(
            mpl.ticker.NullFormatter()
        )
 
    else:
 
        value_axis.set_major_locator(
            MaxNLocator(nbins=4)
        )
 
        value_axis.set_major_formatter(
            FuncFormatter(lambda value, _: f"{value:g}")
        )
 
    ax.tick_params(
        axis=value_axis_name,
        length=2.5,
        pad=2,
        colors="black",
    )
 
 
def make_quantitative_figure(
    df: pd.DataFrame,
    chamfer_scale: str = None,
    label_rotation: float = None,
    sort_by=None,
    sort_method=None,
    sort_descending: bool = None,
    show_values=None,
    layout: str = None,
    bands: bool = None,
):
    """
    Create the quantitative comparison figure.
 
    Panels: Chamfer distance [mm] (bars, log or linear axis) and
    absolute scale error [%] (line with dot).
 
    Parameters
    ----------
    chamfer_scale  : "log" or "linear". Defaults to CHAMFER_SCALE.
    label_rotation : class label angle in degrees. Defaults to
                     CLASS_LABEL_ROTATION.
    sort_by        : None, "alphabetical", or a metric column name.
                     Defaults to SORT_BY.
    sort_method    : None (mean over methods) or a method name.
                     Defaults to SORT_METHOD.
    sort_descending: reverse the order. Defaults to SORT_DESCENDING.
    show_values    : None (use SHOW_VALUES), False (off), "chamfer",
                     "scale" or "both": print the values on the plots.
    layout         : "vertical" or "horizontal". Defaults to
                     QUANTITATIVE_LAYOUT.
    bands          : True/False, light background band behind every
                     other class. Defaults to SHOW_BANDS.
    """
 
    if chamfer_scale is None:
        chamfer_scale = CHAMFER_SCALE
 
    if label_rotation is None:
        label_rotation = CLASS_LABEL_ROTATION
 
    if sort_by is None:
        sort_by = SORT_BY
 
    if sort_method is None:
        sort_method = SORT_METHOD
 
    if sort_descending is None:
        sort_descending = SORT_DESCENDING
 
    if show_values is None:
        show_values = SHOW_VALUES
 
    if layout is None:
        layout = QUANTITATIVE_LAYOUT
 
    if bands is None:
        bands = SHOW_BANDS
 
    value_kinds = {
        None: set(),
        False: set(),
        "chamfer": {"bar"},
        "scale": {"lollipop"},
        "both": {"bar", "lollipop"},
    }
 
    if show_values not in value_kinds:
        raise ValueError(
            "show_values must be None, False, 'chamfer', "
            "'scale' or 'both'."
        )
 
    if chamfer_scale not in ("log", "linear"):
        raise ValueError(
            "chamfer_scale must be 'log' or 'linear'."
        )
 
    if layout not in ("vertical", "horizontal"):
        raise ValueError(
            "layout must be 'vertical' or 'horizontal'."
        )
 
    horizontal = (layout == "horizontal")
 
    # Preserve the CSV class order unless sorting is requested.
    classes = df["cls"].drop_duplicates().tolist()
 
    # Remove the unused collar class if present.
    classes = [
        cls for cls in classes
        if cls != "GF_Collar_S"
    ]
 
    if not classes:
        raise ValueError(
            "No classes remain after filtering."
        )
 
    classes = _sort_classes(
        df,
        classes,
        sort_by,
        sort_method,
        sort_descending,
    )
 
    if horizontal:
        fig_w, fig_h = HORIZONTAL_WIDTH, HORIZONTAL_HEIGHT
    else:
        fig_w, fig_h = QUANTITATIVE_WIDTH, QUANTITATIVE_HEIGHT
 
    fig = plt.figure(
        figsize=(fig_w, fig_h),
        facecolor="white",
    )
 
    # --------------------------------------------------------
    # Layout in inches
    # --------------------------------------------------------
 
    pt = 1.0 / 72.0
    theta = np.deg2rad(label_rotation)
 
    # Approximate extent of the longest class label.
    longest = max(len(c) for c in classes)
    text_w = longest * FONT_SIZE * 0.56 * pt
    text_h = FONT_SIZE * 1.2 * pt
 
    n_panels = len(METRICS)
 
    if horizontal:
 
        # Height taken by the rotated labels below the bottom panel.
        bottom_in = (
            text_w * abs(np.sin(theta))
            + text_h * abs(np.cos(theta))
            + 0.08
        )
 
        top_in = FONT_SIZE * 2.0 * pt + 0.08   # legend
        left_in = FONT_SIZE * 4.6 * pt         # y-label and tick labels
        right_in = 0.06
        gap_in = 0.12
 
        axes_h = (
            fig_h - top_in - bottom_in - (n_panels - 1) * gap_in
        ) / n_panels
 
        if axes_h < 0.8:
            warnings.warn(
                f"Panels are only {axes_h:.2f} in tall; increase "
                "HORIZONTAL_HEIGHT or reduce CLASS_LABEL_ROTATION.",
                stacklevel=2,
            )
 
        gs = GridSpec(
            n_panels,
            1,
            figure=fig,
            left=left_in / fig_w,
            right=1.0 - right_in / fig_w,
            top=1.0 - top_in / fig_h,
            bottom=bottom_in / fig_h,
            hspace=gap_in / axes_h,
        )
 
    else:
 
        # Width taken by the rotated labels left of the first panel.
        left_in = (
            text_w * abs(np.cos(theta))
            + text_h * abs(np.sin(theta))
            + 0.08
        )
 
        # Room for the legend and the panel titles.
        top_in = FONT_SIZE * 3.4 * pt + 0.08
 
        gs = GridSpec(
            1,
            n_panels,
            figure=fig,
            width_ratios=[1.0] + [0.8] * (n_panels - 1),
            left=left_in / fig_w,
            right=0.97,
            top=1.0 - top_in / fig_h,
            bottom=0.09,
            wspace=0.15,
        )
 
    for i, metric in enumerate(METRICS):
 
        ax = fig.add_subplot(
            gs[i, 0] if horizontal else gs[0, i]
        )
 
        # Class labels once: bottom panel (horizontal) or first panel
        # (vertical).
        show_class_labels = (
            (i == n_panels - 1) if horizontal else (i == 0)
        )
 
        add_metric_panel(
            ax=ax,
            df=df,
            classes=classes,
            metric=metric,
            show_class_labels=show_class_labels,
            chamfer_scale=chamfer_scale,
            label_rotation=label_rotation,
            show_values=(
                metric["kind"] in value_kinds[show_values]
            ),
            layout=layout,
            bands=bands,
        )
 
    # --------------------------------------------------------
    # Shared legend (color = method)
    # --------------------------------------------------------
 
    handles = [
        mpl.patches.Patch(
            facecolor=METHOD_COLORS[method],
            edgecolor="none",
            label=method,
        )
        for method in METHODS
    ]
 
    fig.legend(
        handles=handles,
        loc="upper center",
        bbox_to_anchor=(0.5, 1.0),
        ncol=len(handles),
        frameon=False,
        handletextpad=0.4,
        columnspacing=1.2,
        borderaxespad=0.1,
    )
 
    # --------------------------------------------------------
    # Export
    # --------------------------------------------------------
 
    save_figure(
        fig,
        OUTPUT_QUANTITATIVE_PDF,
        OUTPUT_QUANTITATIVE_PNG,
    )


def _order_classes(df: pd.DataFrame, classes: list, sort_by):
    """Return classes in the requested order."""
 
    if sort_by is None:
        return classes
 
    if sort_by == "alphabetical":
        return sorted(classes, key=str.lower)
 
    if sort_by in df.columns:
        key = (
            df[df["cls"].isin(classes)]
            .groupby("cls")[sort_by]
            .mean()
        )
        return sorted(
            classes,
            key=lambda c: key.get(c, np.inf)
            if pd.notna(key.get(c, np.nan)) else np.inf,
        )
 
    raise ValueError(
        f"Unknown sort_by value: {sort_by!r}"
    )
 
 
def make_compact_quantitative_figure(
    df: pd.DataFrame,
    font_size: float = COMPACT_FONT_SIZE,
    n_rows: int = COMPACT_N_ROWS,
    sort_by=COMPACT_SORT_BY,
):
    """
    Compact double-column quantitative comparison with dual y-axes.
 
    Encoding
    --------
    Spatial grouping : one group per class (alternating grey bands).
                       Inside a group, the left pair of slots uses the
                       left axis [mm] and the right pair uses the right
                       axis [%]. Within each pair: 3DGS, then TRELLIS.
    Color            : method (viridis).
    Marker           : metric (circle = Chamfer, triangle = Hausdorff,
                       diamond = absolute scale error).
    Connectors       : a vertical line joins Chamfer and Hausdorff of the
                       same method and class; scale error has a stem to
                       the zero baseline of the right axis.
 
    Chamfer and Hausdorff share a logarithmic left axis [mm]. The scale
    error uses a linear right axis [%] starting at zero.
 
    Parameters
    ----------
    font_size : font size in points for all text in this figure.
    n_rows    : number of stacked rows the classes are split into.
    sort_by   : None, "alphabetical", or a metric column name.
    """
 
    # --------------------------------------------------------
    # Data preparation
    # --------------------------------------------------------
 
    classes = [
        c for c in df["cls"].drop_duplicates().tolist()
        if c not in COMPACT_EXCLUDED_CLASSES
    ]
 
    if not classes:
        raise ValueError("No classes remain after filtering.")
 
    classes = _order_classes(df, classes, sort_by)
 
    n_classes = len(classes)
    per_row = int(np.ceil(n_classes / n_rows))
 
    sub = df[df["cls"].isin(classes)]
    lookup = sub.set_index(["method", "cls"])
 
    mm_cols = [m["column"] for m in COMPACT_MM_METRICS]
    pct_col = COMPACT_PCT_METRIC["column"]
 
    mm_vals = sub[mm_cols].to_numpy(dtype=float).ravel()
    mm_vals = mm_vals[np.isfinite(mm_vals) & (mm_vals > 0)]
 
    pct_vals = sub[pct_col].to_numpy(dtype=float)
    pct_vals = pct_vals[np.isfinite(pct_vals)]
 
    if mm_vals.size == 0 or pct_vals.size == 0:
        raise ValueError("No valid values to plot.")
 
    # Shared limits across rows so that rows are directly comparable.
    mm_lo = mm_vals.min() / 1.4
    mm_hi = mm_vals.max() * 1.4
    pct_hi = max(pct_vals.max(), 1e-9) * 1.08
 
    decades = np.log10(mm_hi / mm_lo)
    log_subs = (1.0, 2.0, 5.0) if decades <= 2.5 else (1.0,)
 
    # --------------------------------------------------------
    # Layout in inches (robust to font size changes)
    # --------------------------------------------------------
 
    pt = 1.0 / 72.0
 
    longest = max(len(c) for c in classes)
    label_h = longest * font_size * 0.56 * pt + 0.06
    legend_h = font_size * 2.0 * pt + 0.04
    left_in = font_size * 4.4 * pt
    right_in = font_size * 4.2 * pt
    row_gap = 0.08
    plot_h = COMPACT_ROW_PLOT_HEIGHT
 
    fig_w = COMPACT_WIDTH
    fig_h = (
        legend_h
        + n_rows * (plot_h + label_h)
        + (n_rows - 1) * row_gap
        + 0.04
    )
 
    rc = {
        "font.size": font_size,
        "axes.titlesize": font_size,
        "axes.labelsize": font_size,
        "xtick.labelsize": font_size,
        "ytick.labelsize": font_size,
        "legend.fontsize": font_size,
        "ytick.major.size": 2.5,
    }
 
    with mpl.rc_context(rc):
 
        fig = plt.figure(
            figsize=(fig_w, fig_h),
            facecolor="white",
        )
 
        for r in range(n_rows):
 
            chunk = classes[r * per_row:(r + 1) * per_row]
 
            if not chunk:
                continue
 
            top_in = legend_h + r * (plot_h + label_h + row_gap)
            bottom_in = fig_h - (top_in + plot_h)
 
            ax = fig.add_axes([
                left_in / fig_w,
                bottom_in / fig_h,
                (fig_w - left_in - right_in) / fig_w,
                plot_h / fig_h,
            ])
            ax2 = ax.twinx()
 
            ax.set_yscale("log")
            ax.set_axisbelow(True)
 
            # ------------------------------------------------
            # Data
            # ------------------------------------------------
 
            for i, cls in enumerate(chunk):
 
                if i % 2 == 0:
                    ax.axvspan(
                        i - 0.5,
                        i + 0.5,
                        facecolor=COMPACT_BAND_COLOR,
                        linewidth=0,
                        zorder=0,
                    )
 
                for k, method in enumerate(METHODS):
 
                    if (method, cls) not in lookup.index:
                        continue
 
                    rec = lookup.loc[(method, cls)]
                    color = COMPACT_METHOD_COLORS[method]
 
                    # Left axis: Chamfer and Hausdorff [mm].
                    x_mm = i + COMPACT_MM_OFFSETS[k]
                    pts = []
 
                    for metric in COMPACT_MM_METRICS:
 
                        value = pd.to_numeric(
                            rec[metric["column"]],
                            errors="coerce",
                        )
 
                        if not np.isfinite(value) or value <= 0:
                            continue
 
                        pts.append(float(value))
 
                        ax.scatter(
                            x_mm,
                            value,
                            s=metric["size"],
                            marker=metric["marker"],
                            color=color,
                            edgecolors="black",
                            linewidths=0.25,
                            zorder=4,
                        )
 
                    if len(pts) == 2:
                        ax.plot(
                            [x_mm, x_mm],
                            pts,
                            color=color,
                            linewidth=0.8,
                            solid_capstyle="butt",
                            zorder=3,
                        )
 
                    # Right axis: absolute scale error [%].
                    x_pct = i + COMPACT_PCT_OFFSETS[k]
 
                    se = pd.to_numeric(
                        rec[pct_col],
                        errors="coerce",
                    )
 
                    if np.isfinite(se):
 
                        ax2.vlines(
                            x_pct,
                            0,
                            se,
                            color=color,
                            linewidth=0.6,
                            alpha=0.6,
                            zorder=3,
                        )
 
                        ax2.scatter(
                            x_pct,
                            se,
                            s=COMPACT_PCT_METRIC["size"],
                            marker=COMPACT_PCT_METRIC["marker"],
                            color=color,
                            edgecolors="black",
                            linewidths=0.25,
                            zorder=4,
                        )
 
            # ------------------------------------------------
            # Axes formatting
            # ------------------------------------------------
 
            ax.set_xlim(-0.5, per_row - 0.5)
            ax.set_ylim(mm_lo, mm_hi)
            ax2.set_ylim(0, pct_hi)
 
            ax.set_xticks(range(len(chunk)))
            ax.set_xticklabels(
                chunk,
                rotation=90,
                ha="center",
                va="top",
                color="black",
            )
            ax.tick_params(axis="x", length=0, pad=2)
 
            ax.yaxis.set_major_locator(
                LogLocator(base=10, subs=log_subs, numticks=20)
            )
            ax.yaxis.set_minor_locator(NullLocator())
            ax.yaxis.set_major_formatter(
                FuncFormatter(lambda v, _: f"{v:g}")
            )
 
            ax2.yaxis.set_major_locator(MaxNLocator(nbins=5))
            ax2.yaxis.set_major_formatter(
                FuncFormatter(lambda v, _: f"{v:g}")
            )
 
            ax.grid(
                axis="y",
                color="#D0D0D0",
                linewidth=0.45,
                zorder=0.5,
            )
            ax.grid(axis="x", visible=False)
            ax2.grid(False)
 
            for side in ("top", "right"):
                ax.spines[side].set_visible(False)
 
            for side in ("top", "left", "bottom"):
                ax2.spines[side].set_visible(False)
 
            ax.set_ylabel("Distance [mm]", labelpad=2)
            ax2.set_ylabel(
                "Scale error [%]",
                rotation=270,
                va="bottom",
                labelpad=2,
            )
 
            ax.tick_params(axis="y", colors="black", pad=2)
            ax2.tick_params(axis="y", colors="black", pad=2)
 
        # ----------------------------------------------------
        # Shared legend (method = color, metric = marker)
        # ----------------------------------------------------
 
        handles = [
            Patch(
                facecolor=COMPACT_METHOD_COLORS[m],
                edgecolor="black",
                linewidth=0.3,
                label=m,
            )
            for m in METHODS
        ]
 
        for metric, side in zip(
            COMPACT_MM_METRICS + [COMPACT_PCT_METRIC],
            ["left", "left", "right"],
        ):
            handles.append(
                Line2D(
                    [0],
                    [0],
                    marker=metric["marker"],
                    linestyle="none",
                    markerfacecolor="#6E6E6E",
                    markeredgecolor="black",
                    markeredgewidth=0.3,
                    markersize=np.sqrt(metric["size"]) + 0.8,
                    label=f"{metric['label']} ({side} axis)",
                )
            )
 
        fig.legend(
            handles=handles,
            loc="upper center",
            bbox_to_anchor=(0.5, 1.0),
            ncol=len(handles),
            frameon=False,
            handletextpad=0.4,
            columnspacing=1.1,
            borderaxespad=0.1,
        )
 
        save_figure(
            fig,
            OUTPUT_COMPACT_PDF,
            OUTPUT_COMPACT_PNG,
        )


# ============================================================
# Main
# ============================================================

def main():

    print("Loading metrics...")

    df = load_metrics(CSV_PATH)

    print(
        f"Loaded {len(df)} measurements "
        f"for {df['cls'].nunique()} classes."
    )

    print(
        "Methods:",
        ", ".join(
            method
            for method in METHODS
            if method in df["method"].unique()
        ),
    )

    # Validate requested quantitative metrics.
    for metric in METRICS:

        column = metric["column"]

        if df[column].notna().sum() == 0:
            raise ValueError(
                f"No valid values for metric {column!r}."
            )

    # --------------------------------------------------------
    # Figure 1: qualitative comparison
    # --------------------------------------------------------

    print("\nGenerating qualitative comparison...")

    make_qualitative_figure()

    # --------------------------------------------------------
    # Figure 2: quantitative comparison
    # --------------------------------------------------------

    print("\nGenerating quantitative comparison...")

    make_quantitative_figure(df)

    print("\nGenerating compact quantitative comparison...")
    #make_compact_quantitative_figure(df)
    make_compact_quantitative_figure(df, font_size=9, sort_by="chamfer_mm")


    print("\nAll figures generated successfully.")


if __name__ == "__main__":
    main()