File size: 138,504 Bytes
7b0de7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build a simple PDF slide deck from the figures in visualize_chesapeake_ny.ipynb.

usage: /opt/miniconda3/envs/rishabh_sat/bin/python make_slides.py
Runs the notebook headlessly and writes slides_chesapeake.pdf (16:9, one figure per slide, no notes, no pptx).
Captions are derived from each figure's own cell, so adding/reordering cells keeps them correct.
Tall multi-row figures are split into 2-row slides so the maps stay readable.
All text, on the slides and inside the notebook figures, is set in Times New Roman.
The last slide shows the training-loss curves of the three Paraformer runs (read from their log.txt).
"""
import atexit, base64, io, re
import numpy as np
import nbformat
from nbclient import NotebookClient
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
FONT_RC = {"font.family": "Times New Roman", "mathtext.fontset": "stix"}
plt.rcParams.update(FONT_RC)
from matplotlib.backends.backend_pdf import PdfPages
from PIL import Image

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   # the project root; every other path below is relative to it
os.chdir(ROOT)
NB, OUT = "slides/visualize_chesapeake_ny.ipynb", "slides/slides_chesapeake.pdf"
ROWS_PER_SLIDE = 2
STATE_NAMES = ["Delaware", "New York", "Maryland", "Pennsylvania", "Virginia", "West Virginia"]
CCLC = {1: ("Water", "Water"), 2: ("Tree Canopy and Shrubs", "Tree canopy"), 3: ("Low Vegetation", "Low vegetation"),
        4: ("Barren", "Built-up"), 5: ("Impervious Surfaces", "Built-up"), 6: ("Impervious Roads", "Built-up")}

def describe(src):
    """(caption, labels of the figure's panel rows or None) for one code cell."""
    if 'plot_row(row, "ny"' in src:
        return "New York tiles: NAIP RGB  |  NLCD 30 m label  |  CCLC 1 m ground truth", ["train", "val", "test"]
    if "STATES.items()" in src:
        split = re.search(r'plot_row\(row, code, "(\w+)"', src).group(1)
        return f"One {split} tile from each state: NAIP RGB  |  NLCD 30 m label  |  CCLC 1 m ground truth", STATE_NAMES
    m = re.search(r"show_cclc_class\((\d+)\)", src)
    if m:
        name, uni = CCLC[int(m.group(1))]
        return (f"CCLC class {m.group(1)} = {name}  ->  " + (f"unified class: {uni}" if uni else "ignored in evaluation")), None
    if "UNIFIED_COLORS" in src:
        return "Both labels after unification to the 4 evaluation classes (what mIoU is computed on)", None
    first = next((l.lstrip("# ").strip() for l in src.splitlines() if l.startswith("#")), "Figure")
    return first, None

def figures(path):
    nb = nbformat.read(path, as_version=4)
    first_code = next(i for i, c in enumerate(nb.cells) if c.cell_type == "code")
    nb.cells.insert(first_code + 1, nbformat.v4.new_code_cell(f"import matplotlib.pyplot as plt\nplt.rcParams.update({FONT_RC!r})"))
    NotebookClient(nb, timeout=900, kernel_name="python3").execute()
    out = []
    for cell in nb.cells:
        if cell.cell_type != "code": continue
        for o in cell.get("outputs", []):
            png = o.get("data", {}).get("image/png")
            if png:
                out.append((Image.open(io.BytesIO(base64.b64decode(png))).convert("RGB"), *describe(cell.source)))
    return out

def split_rows(img, n_rows):
    """Cut a figure of n_rows panel rows into chunks of ROWS_PER_SLIDE, snapping each cut to a blank band."""
    a = np.asarray(img.convert("L")); H = a.shape[0]
    blank = (a >= 250).all(axis=1)
    cuts = [0]
    for k in range(ROWS_PER_SLIDE, n_rows, ROWS_PER_SLIDE):
        target = int(H * k / n_rows); win = int(0.06 * H)
        cand = [y for y in range(max(0, target - win), min(H, target + win)) if blank[y]]
        cuts.append(min(cand, key=lambda y: abs(y - target)) if cand else target)
    cuts.append(H)
    return [img.crop((0, cuts[i], img.width, cuts[i + 1])) for i in range(len(cuts) - 1)]

RUNS_DIR = "Paraformer_hr_landcover/runs"
RUNS = [  # (label, short name, run folder, colour) - first three slots of the dataviz reference palette, validated all-pairs
    ("Baseline: ImageNet ViT-B/16, fine-tuned", "baseline", "paraformer_adamw_lr1e-4_w128_bs8", "#2a78d6"),
    ("DINOv3 ViT-L/16 satellite, frozen", "DINOv3 satellite", "paraformer_dinov3_sat_frozen_adamw_lr1e-4_w128_bs8", "#eb6834"),
    ("DINOv3 ViT-L/16 web, frozen", "DINOv3 web", "paraformer_dinov3_web_frozen_adamw_lr1e-4_w128_bs8", "#1baf7a"),
]
LOG_RE = re.compile(r"Epoch : (\d+), CE-branch1 : (\S+), MCE-branch2: (\S+), loss: (\S+), lr: (\S+)")
INK, MUTED, GRID = "#0b0b0b", "#52514e", "#e4e3df"

def read_log(run):
    rows = [tuple(float(v) for v in m.groups()) for m in map(LOG_RE.search, open(os.path.join(RUNS_DIR, run, "log.txt"))) if m]
    a = np.array(rows)                       # columns: epoch, ce1, mce2, loss, lr
    ok = np.isfinite(a[:, 3])
    return a[ok], int((~ok).sum())

def _bw_box(fig, x, y, w, h, title, body, fill="white", dashed=False, lw=1.6, tfs=15, bfs=12):
    from matplotlib.patches import FancyBboxPatch
    fig.patches.append(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.006,rounding_size=0.012", transform=fig.transFigure,
                                      facecolor=fill, edgecolor="black", lw=lw, ls=(0, (5, 3)) if dashed else "-"))
    if body:
        fig.text(x + w / 2, y + h - 0.035, title, ha="center", va="center", fontsize=tfs, weight="bold", color="black")
        fig.text(x + w / 2, y + (h - 0.05) / 2 - 0.005, body, ha="center", va="center", fontsize=bfs, color="black", linespacing=1.35)
    else:
        fig.text(x + w / 2, y + h / 2, title, ha="center", va="center", fontsize=tfs, weight="bold", color="black")

def _bw_arrow(fig, p, q, lw=1.6):
    from matplotlib.patches import FancyArrowPatch
    fig.patches.append(FancyArrowPatch(p, q, transform=fig.transFigure, arrowstyle="-|>", mutation_scale=16, color="black", lw=lw,
                                       shrinkA=2, shrinkB=2))

def architecture_slide(pdf):
    """One-slide black-and-white block diagram of Paraformer as trained here."""
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#efefef"
    fig.text(0.5, 0.95, "Paraformer in one picture", ha="center", va="center", fontsize=26, weight="bold", color="black")
    fig.text(0.5, 0.905, "One 1 m image chip, two branches, one fused prediction. Training sees only the 30 m NLCD label.",
             ha="center", va="center", fontsize=14, color=MUTED)
    _bw_box(fig, 0.03, 0.47, 0.15, 0.19, "Input", "NAIP image chip\n224 x 224 px at 1 m\n4 bands: R, G, B, NIR", fill=LIGHT)
    _bw_box(fig, 0.26, 0.64, 0.22, 0.17, "CNN branch", "5 blocks, never downsamples\nkeeps 1 m detail: edges, roads")
    _bw_box(fig, 0.26, 0.32, 0.22, 0.17, "Transformer branch", "ViT-B/16, 12 layers\nglobal context on a 14 x 14 grid")
    _bw_box(fig, 0.56, 0.47, 0.15, 0.19, "Fusion decoder", "upsamples Transformer\nfeatures, adds CNN\nfeatures at each step")
    _bw_box(fig, 0.79, 0.64, 0.18, 0.17, "Prediction A", "CNN head\n17 NLCD classes per pixel")
    _bw_box(fig, 0.79, 0.32, 0.18, 0.17, "Prediction B", "Transformer head\n17 NLCD classes per pixel")
    for p, q in [((0.18, 0.60), (0.26, 0.72)), ((0.18, 0.53), (0.26, 0.41)), ((0.48, 0.72), (0.56, 0.60)), ((0.48, 0.41), (0.56, 0.53)),
                 ((0.71, 0.60), (0.79, 0.72)), ((0.71, 0.53), (0.79, 0.41))]:
        _bw_arrow(fig, p, q)
    _bw_box(fig, 0.03, 0.08, 0.15, 0.17, "NLCD label", "30 m, 16 classes\nused for training only", fill=LIGHT)
    _bw_box(fig, 0.26, 0.08, 0.71, 0.17, "Training: PLAT loss (pseudo-label-assisted)",
            "Loss A = cross entropy between Prediction A and the NLCD label.\n"
            "Loss B = the same for Prediction B, but only on pixels where Prediction A already agrees with NLCD, so the label's mistakes are filtered out.\n"
            "Total loss = 0.5 Loss A + 0.5 Loss B.", dashed=True)
    _bw_arrow(fig, (0.18, 0.165), (0.26, 0.165)); _bw_arrow(fig, (0.88, 0.64), (0.88, 0.25)); _bw_arrow(fig, (0.88, 0.32), (0.88, 0.25))
    fig.text(0.03, 0.045, "Inference: average Predictions A and B, take the most likely class per pixel, then map the 17 NLCD classes to the 4 evaluation classes (Table S1). "
             "The CCLC 1 m ground truth is used only for evaluation.", fontsize=12, color=MUTED, va="center")
    fig.text(0.03, 0.018, "Our DINOv3 variant: the Transformer branch is a frozen DINOv3 ViT-L/16 that reads the RGB chip directly; CNN branch, decoder, heads and loss are unchanged.",
             fontsize=12, color=MUTED, va="center")
    pdf.savefig(fig); plt.close(fig)

BASE_DIAGRAM = ("new 1 x 1 conv\n1024 -> 768\n= 196 tokens", "ImageNet-21k ViT-B/16",
                "12 pretrained blocks\nfine-tuned, full LR\npretrained position\nembeddings (CLS slot dropped)")

def _serial_diagram(fig, proj, vit_title, vit_body, dy=0.0, bands="R, G, B, NIR", cnn_reads="reads all 4 bands"):
    """The serial CNN -> projection -> Transformer -> decoder block diagram, shifted vertically by dy (figure fraction)."""
    from matplotlib.lines import Line2D
    LIGHT = "#efefef"; y, h = 0.50 + dy, 0.24; ym = 0.62 + dy
    _bw_box(fig, 0.02, y, 0.12, h, "Input", f"NAIP chip\n224 x 224 px, 1 m\n{bands}", fill=LIGHT)
    _bw_box(fig, 0.18, y, 0.13, h, "CNN branch", f"L2HNet\ntrained from scratch\n{cnn_reads}\nout: 14 x 14 x 1024")
    _bw_box(fig, 0.35, y, 0.12, h, "Projection", proj, dashed=True)
    _bw_box(fig, 0.51, y, 0.17, h, vit_title, vit_body)
    _bw_box(fig, 0.72, y, 0.11, h, "Fusion\ndecoder", "\n\nupsamples tokens,\nadds CNN skips")
    _bw_box(fig, 0.87, 0.64 + dy, 0.11, 0.15, "Prediction A", "CNN head")
    _bw_box(fig, 0.87, 0.45 + dy, 0.11, 0.15, "Prediction B", "Transformer head")
    for a, b in [(0.14, 0.18), (0.31, 0.35), (0.47, 0.51), (0.68, 0.72)]: _bw_arrow(fig, (a, ym), (b, ym))
    _bw_arrow(fig, (0.83, 0.66 + dy), (0.87, 0.715 + dy)); _bw_arrow(fig, (0.83, 0.58 + dy), (0.87, 0.525 + dy))
    fig.lines.append(Line2D([0.245, 0.245, 0.775], [y, 0.40 + dy, 0.40 + dy], transform=fig.transFigure, color="black", lw=1.6))
    _bw_arrow(fig, (0.775, 0.40 + dy), (0.775, y))
    fig.text(0.51, 0.38 + dy, "skip features at 224, 112, 56 and 14 px", ha="center", va="top", fontsize=13, color="black")

def _serial_slide(pdf, title, subtitle, proj, vit_title, vit_body, box_title, box_body):
    """Black-and-white slide of the serial wiring (Base and Model 1): title, subtitle, diagram and a notes box."""
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.95, title, ha="center", va="center", fontsize=26, weight="bold", color="black")
    fig.text(0.5, 0.905, subtitle, ha="center", va="center", fontsize=14, color=MUTED)
    _serial_diagram(fig, proj, vit_title, vit_body)
    _bw_box(fig, 0.02, 0.06, 0.96, 0.24, box_title, box_body, dashed=True, bfs=13)
    pdf.savefig(fig); plt.close(fig)

def dino_baseline_slide(pdf):
    """Base, black and white: the baseline Paraformer exactly as the code wires it (serial), the reference for Model 1 and Model 2."""
    _serial_slide(pdf, "Base: the baseline Paraformer (ImageNet ViT-B/16)",
                  "Serial design: the CNN reads the image and the Transformer reads the CNN's output. The reference for Model 1 and Model 2. Trained: val 58.34, test 63.21 (epoch 40).",
                  *BASE_DIAGRAM,
                  "What the baseline takes from the ImageNet ViT",
                  "Loaded from ImageNet-21k: the 12 Transformer blocks, the final norm and the position embeddings (the CLS slot is dropped).\n"
                  "Not used: the ViT's RGB patch embedding. Tokens come from CNN features through the new projection, so NIR also reaches the Transformer.\n"
                  "Note: slide 20 draws the two branches side by side; in the code the Transformer sits after the CNN, as drawn here.")

def _best_scores(run, max_epoch=None):
    """(epoch, val row, test row) of the checkpoint with the best val average among those scored on both val and test."""
    import pandas as pd
    d = os.path.join(RUNS_DIR, run, "eval")
    hv, ht = [pd.read_csv(os.path.join(d, f"history_{s}.csv")) for s in ("val", "test")]
    hv, ht = hv[hv.mapping == "paper"], ht[ht.mapping == "paper"]
    hv = hv[hv.epoch.isin(ht.epoch)]
    if max_epoch is not None: hv = hv[hv.epoch <= max_epoch]
    v = hv.sort_values(["avg_mIoU", "pooled_mIoU"], ascending=False).iloc[0]; ep = int(v.epoch)
    return ep, v, ht[ht.epoch == ep].iloc[0], sorted(int(e) for e in hv.epoch)

def option_results_slide(pdf, run, name, n_epochs, last_epoch, reference=None, test_colour=None, ckpt_every=10, ref_all_epochs=False):
    """Best val-chosen checkpoint of one run: val and test mIoU, per class (pooled) and per state.
    reference = (label, run) or a list of them: muted rows of other runs at their own val-chosen checkpoint, for comparison.
    test_colour: if set, every test row (this run's and the references') is drawn in that colour."""
    if not os.path.exists(os.path.join(RUNS_DIR, run, "eval", "history_test.csv")): return 0
    ep, v, t, scored = _best_scores(run)
    done = last_epoch in scored
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.95, f"{name}: best checkpoint = epoch {ep}, chosen on val" + ("" if done else " (so far)"),
             ha="center", va="center", fontsize=26, weight="bold", color=INK)
    sub = (f"Trained {n_epochs} epochs (0 to {last_epoch}); checkpoints every {ckpt_every} epochs + epoch {last_epoch}, all scored on val and test. The epoch with the best val average is kept."
           if done else f"Training to {n_epochs} epochs is still running: checkpoints scored so far on val and test: {', '.join(map(str, scored))}. The epoch with the best val average is kept.")
    fig.text(0.5, 0.905, sub, ha="center", va="center", fontsize=14, color=MUTED)
    refs = [reference] if isinstance(reference, tuple) else list(reference or [])
    ref = []
    for item in refs:
        rlab, rrun = item[:2]
        if not os.path.exists(os.path.join(RUNS_DIR, rrun, "eval", "history_test.csv")): continue
        rep, rv, rt, _ = _best_scores(rrun, max_epoch=None if ref_all_epochs else last_epoch); ref.append((item[2] if len(item) > 2 else f"{rlab}, epoch {rep}", rv, rt))
    tc = lambda ours: test_colour or (INK if ours else MUTED)
    fig.text(0.04, 0.84, "IoU (%) per class, pooled over all six states", fontsize=17, weight="bold", color=INK, va="center")
    header = ["Split", "Built-up", "Tree canopy", "Low vegetation", "Water", "mIoU (pooled)", "mIoU (avg of states)"]
    col_x = [0.04, 0.33, 0.45, 0.59, 0.68, 0.81, 0.96]; aligns = ["left"] + ["right"] * 6
    row = lambda lab, r, ours, col=None: ([lab] + [f"{r[f'pooled_{c}']:.1f}" for c in CLASS_COLS] + [f"{r.pooled_mIoU:.1f}", f"{r.avg_mIoU:.2f}"], ours, col or (INK if ours else MUTED))
    body = [row(f"Val, epoch {ep}", v, True), row(f"Test, epoch {ep}", t, True, tc(True))]
    for rl, rv, rt in ref: body += [row(f"{rl}: val", rv, False), row(f"{rl}: test", rt, False, tc(False))]
    rh = {0: 0.065, 1: 0.05}.get(len(ref), 0.04)
    end = draw_table(fig, 0.775, header, body, best_cols=[], col_x=col_x, aligns=aligns, row_h=rh)
    fig.text(0.04, end - 0.03, "mIoU per state (%)", fontsize=17, weight="bold", color=INK, va="center")
    header = ["Split", "DE", "NY", "MD", "PA", "VA", "WV", "Average"]
    col_x = [0.04, 0.38, 0.465, 0.55, 0.635, 0.72, 0.805, 0.96]; aligns = ["left"] + ["right"] * 7
    srow = lambda lab, r, ours, col=None: ([lab] + [f"{r[f'{st}_mIoU']:.1f}" for st in STATE_COLS] + [f"{r.avg_mIoU:.2f}"], ours, col or (INK if ours else MUTED))
    body = [srow(f"Val, epoch {ep}", v, True), srow(f"Test, epoch {ep}", t, True, tc(True))]
    for rl, rv, rt in ref: body += [srow(f"{rl}: val", rv, False), srow(f"{rl}: test", rt, False, tc(False))]
    lab, vals = PAPER[0]
    body.append(([lab + " (test)"] + [f"{x:.1f}" for x in vals[:6]] + [f"{vals[6]:.2f}"], False, tc(False)))
    end = draw_table(fig, end - (0.075 if len(ref) > 1 else 0.085 if ref else 0.095), header, body, best_cols=[], col_x=col_x, aligns=aligns, row_h=rh)
    note = "Class mapping: the paper's Table S1. The paper reports only the test average per state (Table 1), so it has no val row and no per-class row.\n"
    if ref: note += f"Lighter rows: {' and '.join(r[0] for r in refs)} at their own val-chosen checkpoint" + ("" if ref_all_epochs else f" within epochs 0 to {last_epoch}, for a like-for-like comparison") + "." + (" Red rows: test." if test_colour else "") + "\n"
    note += "CCLC 1 m ground truth is used for scoring and for choosing the epoch on val; test is never used for any choice."
    fig.text(0.04, end - 0.005, note, fontsize=12.5, color=MUTED, va="top")
    pdf.savefig(fig); plt.close(fig)
    return 1

def option0_results_slide(pdf):
    return option_results_slide(pdf, "paraformer_adamw_lr1e-4_w128_bs8", "Base (baseline Paraformer)", 100, 99)

def option1_results_slide(pdf):
    return option_results_slide(pdf, "paraformer_dinov3_web_serial_ft_lr1e-4_vit0.1_w128_bs8_50ep", "Model 1 (DINOv3-web, serial)", 50, 49,
                                reference=("Base", "paraformer_adamw_lr1e-4_w128_bs8"))

def option2_results_slide(pdf):
    return option_results_slide(pdf, "paraformer_vit_b16_plus_dinov3_web_frozen_adamw_lr1e-4_w128_bs8_50ep", "Model 2 (base + DINOv3-web)", 50, 49,
                                reference=[("Base", "paraformer_adamw_lr1e-4_w128_bs8"),
                                           ("Model 1", "paraformer_dinov3_web_serial_ft_lr1e-4_vit0.1_w128_bs8_50ep")], test_colour="#c62828")

def dino_serial_slide(pdf):
    """Black and white: Model 1, DINOv3-web blocks dropped into the baseline's serial CNN -> Transformer wiring."""
    _serial_slide(pdf, "Model 1: DINOv3-web inside the base wiring (drop-in)",
                  "Same serial design as the baseline: the Transformer reads the CNN's output. Only the Transformer's pretrained weights change. Trained 50 epochs; results on the next slide.",
                  "new 1 x 1 conv\n1024 -> 1024\n= 196 tokens", "DINOv3-web ViT-L/16",
                  "24 pretrained blocks\nfine-tuned, 0.1 x LR\nRoPE on the 14 x 14 grid\n+ CLS and 4 registers",
                  "What changes compared with the baseline",
                  "Changed: ImageNet-21k ViT-B/16 (12 layers, 768-d)  ->  DINOv3-web ViT-L/16 (24 layers, 1024-d); its CLS and register tokens are dropped after the last block.\n"
                  "Unchanged: 4-band input, CNN branch, serial wiring, fusion decoder, two heads, PLAT loss, training recipe (AdamW 1e-4, width 128, batch 8).\n"
                  "Caveat: DINOv3 never sees RGB pixels here. Its tokens come from CNN features through a new projection, the same handicap the baseline's ViT has.")

def dino_dual_slide(pdf):
    """Black and white: Model 2, the base unchanged plus a frozen DINOv3-web branch fused at the token level."""
    from matplotlib.lines import Line2D
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#efefef"
    fig.text(0.5, 0.95, "Model 2: base + a DINOv3-web branch (ImageNet ViT kept)", ha="center", va="center", fontsize=26, weight="bold", color="black")
    fig.text(0.5, 0.905, "Base stays exactly as it is. A frozen DINOv3 reads the RGB bands; its tokens are fused with the ImageNet ViT's tokens before the decoder. Trained 50 epochs; results on the next slide.",
             ha="center", va="center", fontsize=14, color=MUTED)
    _bw_box(fig, 0.02, 0.44, 0.10, 0.22, "Input", "NAIP chip\n224 x 224 px\n1 m\nR, G, B, NIR", fill=LIGHT)
    _bw_box(fig, 0.15, 0.62, 0.12, 0.17, "CNN branch", "L2HNet, 4 bands\nout: 14 x 14 x 1024")
    _bw_box(fig, 0.30, 0.62, 0.10, 0.17, "Projection", "1 x 1 conv\n1024 -> 768")
    _bw_box(fig, 0.43, 0.62, 0.14, 0.17, "ImageNet ViT-B/16", "12 blocks, fine-tuned\nout: 196 x 768")
    fig.text(0.36, 0.585, "Base path, unchanged", ha="center", va="center", fontsize=13, color="black", style="italic")
    _bw_box(fig, 0.15, 0.30, 0.42, 0.15, "NEW: DINOv3-web ViT-L/16, frozen",
            "own pretrained patch embedding, RGB only  ->  24 blocks  ->  drop CLS + 4 registers  ->  196 x 1024")
    _bw_box(fig, 0.60, 0.44, 0.10, 0.22, "NEW: token\nfusion", "\n\nconcat 768 + 1024\n-> linear -> 768\nDINOv3 half\nstarts at zero", dashed=True)
    _bw_box(fig, 0.73, 0.44, 0.09, 0.22, "Fusion\ndecoder", "\n\nunchanged\nadds CNN skips")
    _bw_box(fig, 0.85, 0.585, 0.13, 0.14, "Prediction A", "CNN head")
    _bw_box(fig, 0.85, 0.375, 0.13, 0.14, "Prediction B", "Transformer head")
    for p, q in [((0.12, 0.59), (0.15, 0.70)), ((0.12, 0.51), (0.15, 0.375)), ((0.27, 0.705), (0.30, 0.705)), ((0.40, 0.705), (0.43, 0.705)),
                 ((0.57, 0.705), (0.60, 0.60)), ((0.57, 0.375), (0.60, 0.50)), ((0.70, 0.55), (0.73, 0.55)),
                 ((0.82, 0.59), (0.85, 0.655)), ((0.82, 0.51), (0.85, 0.445))]:
        _bw_arrow(fig, p, q)
    fig.text(0.14, 0.53, "RGB only", ha="left", va="center", fontsize=12, color="black", style="italic")
    fig.lines.append(Line2D([0.21, 0.21, 0.775], [0.79, 0.845, 0.845], transform=fig.transFigure, color="black", lw=1.6))
    _bw_arrow(fig, (0.775, 0.845), (0.775, 0.66))
    fig.text(0.49, 0.853, "skip features at 224, 112, 56 and 14 px", ha="center", va="bottom", fontsize=13, color="black")
    _bw_box(fig, 0.02, 0.04, 0.96, 0.21, "What is added to the baseline",
            "Added: a frozen DINOv3-web ViT-L/16 that reads the RGB bands through its own pretrained patch embedding (the input it was trained on), and a token-fusion layer.\n"
            "Token fusion: at each of the 196 grid cells, ImageNet token (768) + DINOv3 token (1024) are concatenated and mapped back to 768; the DINOv3 half starts at zero, so step 0 = the baseline.\n"
            "Unchanged: CNN, 1 x 1 projection, ImageNet ViT-B/16 (fine-tuned), fusion decoder, two heads, PLAT loss, training recipe (AdamW 1e-4, width 128, batch 8).",
            dashed=True, bfs=13)
    pdf.savefig(fig); plt.close(fig)

def fusion_arch_slide(pdf):
    """Model 3, black and white: Base + SAM 3 masks, trained late fusion (a small fusion head trained on NLCD only)."""
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#efefef"
    fig.text(0.5, 0.95, "Model 3: Base + SAM 3 masks, trained late fusion (head trained on NLCD only)", ha="center", va="center", fontsize=24, weight="bold", color="black")
    fig.text(0.5, 0.905, "Both large models stay frozen. The only trainable part is the fusion head. HR CCLC is seen only by the final scorer. Trained with per-pixel cross entropy (L1); results on the next two slides.",
             ha="center", va="center", fontsize=14, color=MUTED)
    _bw_box(fig, 0.02, 0.45, 0.11, 0.24, "Input", "NAIP tile\n1 m\nR, G, B, NIR", fill=LIGHT)
    _bw_box(fig, 0.17, 0.64, 0.25, 0.19, "Base (Paraformer), frozen", "epoch 40, trained on NLCD only\n224-px chips, stride 112\nout: 17 NLCD probabilities per pixel")
    _bw_box(fig, 0.17, 0.31, 0.25, 0.19, "SAM 3, frozen", "6 text prompts, zoom 1: building, road,\nparking lot, runway, water, river\nout: 6 score maps per pixel (0 to 1)")
    _bw_box(fig, 0.46, 0.50, 0.08, 0.14, "concat", "23 channels\nper pixel", fill=LIGHT)
    _bw_box(fig, 0.58, 0.45, 0.19, 0.24, "Fusion head, TRAINED", "1 x 1 conv, 23 -> 17 classes\n408 weights\nstarts as a copy of Paraformer,\nSAM 3 weights = 0", dashed=True)
    _bw_box(fig, 0.81, 0.64, 0.17, 0.19, "Training (L1)", "per-pixel cross entropy\nvs NLCD 30 m, AdamW, 5 epochs\n~120 training tiles\nno selection on CCLC", fill=LIGHT)
    _bw_box(fig, 0.81, 0.31, 0.17, 0.19, "Inference", "argmax of the 17 fused logits\n-> Table S1 -> 4 classes\n-> scored on CCLC\n(evaluation only)")
    for p, q in [((0.13, 0.60), (0.17, 0.735)), ((0.13, 0.54), (0.17, 0.405)), ((0.42, 0.735), (0.46, 0.60)), ((0.42, 0.405), (0.46, 0.54)),
                 ((0.54, 0.57), (0.58, 0.57)), ((0.77, 0.60), (0.81, 0.735)), ((0.77, 0.54), (0.81, 0.405))]:
        _bw_arrow(fig, p, q)
    fig.text(0.165, 0.78, "4 bands", ha="right", va="center", fontsize=12, color="black", style="italic")
    fig.text(0.165, 0.36, "RGB only", ha="right", va="center", fontsize=12, color="black", style="italic")
    fig.text(0.455, 0.71, "17 ch.", ha="center", va="center", fontsize=11, color="black", style="italic")
    fig.text(0.455, 0.43, "6 ch.", ha="center", va="center", fontsize=11, color="black", style="italic")
    _bw_box(fig, 0.02, 0.06, 0.96, 0.20, "What the head learns from per-pixel NLCD (L1)",
            "Learns, per NLCD class, how much to trust each Paraformer class and each SAM 3 prompt, e.g. SAM 3 building + Paraformer forest -> developed (add). Starting as Paraformer, it can only improve on NLCD.\n"
            "Cannot learn to trim: NLCD labels a whole 30 m block developed, lawns and trees included, so a per-pixel loss rewards calling those pixels built-up. Trimming gave most of the rule gain (30.6 -> 51.9).\n"
            "Models 4, 5 and 6 keep this L1 training and give the head richer inputs: SAM 3 image features, NDVI with object pooling, and DOFA features.",
            dashed=True, bfs=12.5)
    pdf.savefig(fig); plt.close(fig)

def _block_grid(fig, rect, sam, built, title):
    """A 30 m NLCD block drawn as a 6 x 6 grid: hatched = SAM 3 sees a building or road, grey = labelled built-up."""
    from matplotlib.patches import Rectangle
    ax = fig.add_axes(rect); ax.set_xlim(0, 6); ax.set_ylim(0, 6); ax.set_xticks([]); ax.set_yticks([]); ax.set_aspect("equal")
    for i in range(6):
        for j in range(6):
            ax.add_patch(Rectangle((j, 5 - i), 1, 1, facecolor="#8c8c8c" if built[i][j] else "white", edgecolor="black", lw=0.8,
                                   hatch="////" if sam[i][j] else None))
    ax.set_title(title, fontsize=12)
    for sp in ax.spines.values(): sp.set_linewidth(1.2)

def fusion_loss_slide(pdf):
    """Proposal, black and white: Level 1 (per-pixel NLCD cross entropy) against Level 2 (block-level share from NLCD's class definitions)."""
    from matplotlib.lines import Line2D
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.95, "Model 3 training signal: per-pixel NLCD (Level 1) or the block share NLCD implies (Level 2)", ha="center", va="center", fontsize=22, weight="bold", color="black")
    fig.text(0.5, 0.905, "Same architecture, same inputs, only the loss changes. One NLCD pixel is a 30 m block = 30 x 30 NAIP pixels; here drawn as a 6 x 6 grid. Hatched: SAM 3 sees a building or road. Grey: labelled built-up.",
             ha="center", va="center", fontsize=13, color=MUTED)
    sam = [[True, True, False, False, False, False], [False] * 6, [True] * 6, [False] * 6,
           [False, False, False, True, True, False], [False, False, False, True, True, False]]           # road + two buildings = 12 of 36 cells
    allb = [[True] * 6 for _ in range(6)]
    for x0, name, built, caption, loss in [
            (0.03, "Level 1: per-pixel cross entropy", allb,
             "Every pixel of the block is pushed towards 'developed',\nlawns and trees included. The head can add built-up\nwhere SAM 3 sees a building; it can never trim it.",
             "loss = CE( fused logits at each pixel,  NLCD class of its block )"),
            (0.52, "Level 2: block-level share", sam,
             "The block's mean built-up probability must be about 0.35.\nThe cheapest way: built-up on the SAM 3 pixels, vegetation\nelsewhere. Trimming is learned from the LR map alone.",
             "loss = (mean over block of P(built-up) - target share)^2   developed blocks\n       CE as in Level 1                                      other blocks")]:
        fig.text(x0 + 0.225, 0.862, name, ha="center", va="center", fontsize=17, weight="bold", color="black")
        fig.text(x0 + 0.225, 0.825, "NLCD label of the block: developed, low intensity (20 to 49 % impervious)", ha="center", va="center", fontsize=12, color="black")
        _block_grid(fig, [x0 + 0.03, 0.48, 0.16, 0.285], sam, [[False] * 6 for _ in range(6)], "SAM 3 sees")
        _block_grid(fig, [x0 + 0.26, 0.48, 0.16, 0.285], sam, built, "what the loss asks for")
        _bw_arrow(fig, (x0 + 0.20, 0.62), (x0 + 0.25, 0.62))
        fig.text(x0 + 0.225, 0.635, "training", ha="center", va="bottom", fontsize=11, color="black", style="italic")
        fig.text(x0 + 0.225, 0.455, caption, ha="center", va="top", fontsize=12.5, color="black", linespacing=1.3)
        fig.text(x0 + 0.225, 0.345, loss, ha="center", va="top", fontsize=11, color="black", family="monospace")
    fig.lines.append(Line2D([0.5, 0.5], [0.30, 0.88], transform=fig.transFigure, color="black", lw=1.0, ls=(0, (4, 4))))
    _bw_box(fig, 0.02, 0.04, 0.96, 0.22, "Target share per NLCD developed class, read off NLCD's published definitions (no HR label involved)",
            "open space (21): < 20 % impervious -> 0.10      low intensity (22): 20 to 49 % -> 0.35      medium intensity (23): 50 to 79 % -> 0.65      high intensity (24): 80 to 100 % -> 0.90\n"
            "All other NLCD classes (forest, water, crops, wetlands, ...): per-pixel cross entropy, as in Level 1.\n"
            "Only NLCD and its class definitions train the head; CCLC is used by the scorer alone. The block-share idea is label super-resolution (Malkin et al., ICLR 2019) in its smallest form, with SAM 3 giving the within-block structure.",
            dashed=True, bfs=12)
    pdf.savefig(fig); plt.close(fig)

def _row_dict(r):
    """An eval history row as a dict: pooled class IoUs, per-state mIoU, avg, pooled."""
    return {**{c: r[f"pooled_{c}"] for c in CLASS_COLS}, **{st: r[f"{st}_mIoU"] for st in STATE_COLS}, "avg": r.avg_mIoU, "pooled": r.pooled_mIoU}

def _hist_row(path, ep):
    """One checkpoint's row of an eval history CSV as a dict."""
    import pandas as pd
    h = pd.read_csv(path); return _row_dict(h[(h.mapping == "paper") & (h.epoch == ep)].iloc[0])

FUSION_HEADS = {   # model number -> (run folder, [(head folder, label)], short description for the slide title)
    4: ("model4", [("M4_L1", "L1 (per-pixel NLCD)")], "Base + SAM 3 image features"),
    5: ("model5", [("M5_L1", "L1 (per-pixel NLCD)")], "Base + NDVI + SAM 3 masks, per object"),
    6: ("model6", [("M6_L1", "L1 (per-pixel NLCD)")], "feature-space fusion with DOFA"),
    7: ("model7", [("M7_L1", "L1 (per-pixel NLCD)")], "Model 5 on RGB only (no NIR)"),
    9: ("model9", [("M9_L1", "L1 (per-pixel NLCD)")], "Model 7 with a 4.9 M mask UNet (no SAM 3)"),
}
RGB_BASE_RUN = "paraformer_rgb_coloraug_adamw_lr1e-4_w128_bs8_50ep"      # Model 7 stage 1: Paraformer retrained on R, G, B
MODEL8_RUN = "model8/student"                                               # Model 8: Paraformer-S distilled from Model 7
MODEL10_RUN, MODEL10_PILOT = "model10/final", "model10/pilot"                # Model 10: MapOT from the RGB Base / pilot from the 4-band Base

def model10_results_slide(pdf):
    n = option_results_slide(pdf, MODEL10_RUN, "Model 10 (MapOT, RGB)", 20, 19, ckpt_every=5, test_colour="#c62828", ref_all_epochs=True,
                             reference=[("Base-RGB", RGB_BASE_RUN), ("Model 7", "model7/M7_L1", "Model 7 (Base-RGB + SAM 3 head)")])
    if n == 0:
        n = option_results_slide(pdf, MODEL10_PILOT, "Model 10 pilot (MapOT from the 4-band Base, NIR weights dropped)", 20, 19, ckpt_every=5, test_colour="#c62828", ref_all_epochs=True,
                                 reference=[("Base", "paraformer_adamw_lr1e-4_w128_bs8", "Base (4 bands)")])
    return n

def model7_base_results_slide(pdf):
    """Model 7, stage 1: the Base retrained on RGB only, checkpoint by checkpoint as they are scored (4-band Base for reference)."""
    return option_results_slide(pdf, RGB_BASE_RUN, "Model 7, stage 1: the Base retrained on RGB only (no NIR)", 50, 49, test_colour="#c62828",
                                reference=("Base", "paraformer_adamw_lr1e-4_w128_bs8", "Base (4 bands)"))

def model8_results_slide(pdf):
    return option_results_slide(pdf, MODEL8_RUN, "Model 8 (Paraformer-S, 26.8 M, distilled)", 50, 49,
                                reference=[("Base-RGB", RGB_BASE_RUN), ("Model 7", "model7/M7_L1", "Model 7 (teacher, 985 M)")], test_colour="#c62828")

def _fusion_head_rows(model_no):
    """(label, val dict, test dict or None) for every trained head of Model 4 / 5 / 6 that has a val score."""
    d, heads, _ = FUSION_HEADS[model_no]; rows = []
    for name, lab in heads:
        e = os.path.join(RUNS_DIR, d, name, "eval")
        if not os.path.exists(f"{e}/history_val.csv"): continue
        t = _hist_row(f"{e}/history_test.csv", 4) if os.path.exists(f"{e}/history_test.csv") else None
        rows.append((f"Model {model_no}: {lab}", _hist_row(f"{e}/history_val.csv", 4), t))
    return rows

def fusion_results_slide(pdf, model_no, red="#c62828"):
    """Results of one of Models 4 / 5 / 6: both tables (per class, per state), Base rows for reference, test rows in red."""
    rows = _fusion_head_rows(model_no)
    if not rows: return 0
    _, _, desc = FUSION_HEADS[model_no]
    b = os.path.join(RUNS_DIR, "paraformer_adamw_lr1e-4_w128_bs8", "eval")
    base_v, base_t = _hist_row(f"{b}/history_val.csv", 40), _hist_row(f"{b}/history_test.csv", 40)
    pending = any(t is None for _, _, t in rows)
    cells = lambda d, keys: [f"{d[k]:.1f}" if k != "avg" else f"{d[k]:.2f}" for k in keys]
    rgb = None
    if model_no in (7, 9) and os.path.exists(os.path.join(RUNS_DIR, RGB_BASE_RUN, "eval", "history_test.csv")):
        rep, rv, rt, _ = _best_scores(RGB_BASE_RUN); rgb = (f"Base-RGB (Paraformer on RGB only, epoch {rep})", _row_dict(rv), _row_dict(rt))
    def body_for(keys, paper=False):
        body = [(["Base (Paraformer alone, epoch 40)", "val"] + cells(base_v, keys), False, MUTED), (["", "test"] + cells(base_t, keys), False, red)]
        if rgb: body += [([rgb[0], "val"] + cells(rgb[1], keys), False, MUTED), (["", "test"] + cells(rgb[2], keys), False, red)]
        for lab, v, t in rows:
            body.append(([lab, "val"] + cells(v, keys), True, INK))
            body.append((["", "test"] + (cells(t, keys) if t else ["pending"] + [""] * (len(keys) - 1)), True, red))
        if paper:
            lab, vals = PAPER[0]; body.append(([lab, "test"] + [f"{x:.1f}" for x in vals[:6]] + [f"{vals[6]:.2f}"], False, red))
        return body
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.95, f"Model {model_no} results: {desc}" + (" (test pending)" if pending else ""), ha="center", va="center", fontsize=25, weight="bold", color=INK)
    fig.text(0.5, 0.905, "Same Base checkpoint (epoch 40) in every row. Heads: fixed recipe, trained on NLCD 30 m only, last epoch kept, nothing chosen on CCLC. Val: 30 tiles, test: 120 tiles.",
             ha="center", va="center", fontsize=13.5, color=MUTED)
    rh, fs = 0.042, 13
    fig.text(0.04, 0.85, "IoU (%) per class, pooled over all six states", fontsize=16, weight="bold", color=INK, va="center")
    keys = CLASS_COLS + ["pooled", "avg"]
    nref = 4 if rgb else 2
    end = draw_table(fig, 0.805, ["Method", "Split", "Built-up", "Tree canopy", "Low veg.", "Water", "mIoU (pooled)", "mIoU (avg)"], body_for(keys), best_cols=[],
                     col_x=[0.04, 0.40, 0.50, 0.60, 0.69, 0.76, 0.865, 0.96], aligns=["left", "left"] + ["right"] * 6, row_h=rh, rules_before=(nref,), fontsize=fs)
    fig.text(0.04, end - 0.02, "mIoU per state (%)", fontsize=16, weight="bold", color=INK, va="center")
    keys = STATE_COLS + ["avg"]
    end = draw_table(fig, end - 0.065, ["Method", "Split", "DE", "NY", "MD", "PA", "VA", "WV", "Average"], body_for(keys, paper=True), best_cols=[],
                     col_x=[0.04, 0.40, 0.49, 0.565, 0.64, 0.715, 0.79, 0.865, 0.96], aligns=["left", "left"] + ["right"] * 7, row_h=rh, rules_before=(nref,), fontsize=fs)
    fig.text(0.04, end - 0.005, "Red rows: test, never used for any choice. Lighter rows: Base" + (" (4 bands) and the RGB-only Base" if rgb else "") +
             " for reference. Class mapping: the paper's Table S1.", fontsize=12, color=MUTED, va="top")
    pdf.savefig(fig); plt.close(fig)
    return 1

def _sam3_compare_rows():
    """(label, val dict, test dict) for the base model and every SAM 3 variant; dicts hold pooled class IoUs, per-state mIoU, avg, pooled."""
    import json, pandas as pd
    R = os.path.join(RUNS_DIR)
    def from_hist(path, ep):
        h = pd.read_csv(path); r = h[(h.mapping == "paper") & (h.epoch == ep)].iloc[0]
        return {**{c: r[f"pooled_{c}"] for c in CLASS_COLS}, **{st: r[f"{st}_mIoU"] for st in STATE_COLS}, "avg": r.avg_mIoU, "pooled": r.pooled_mIoU}
    def from_json(res):
        return {**{c: res["pooled"]["IoU"][c.replace("_", " ")] for c in CLASS_COLS}, **{st: res["per_state"][st]["mIoU"] for st in STATE_COLS},
                "avg": res["mean_over_states_mIoU"], "pooled": res["pooled"]["mIoU"]}
    rows = []
    b = os.path.join(R, "paraformer_adamw_lr1e-4_w128_bs8", "eval")
    rows.append(("Base (Paraformer alone, epoch 40)", from_hist(f"{b}/history_val.csv", 40), from_hist(f"{b}/history_test.csv", 40)))
    ch = json.load(open(os.path.join(R, "sam3", "tune", "choice.json"))); c = ch["builtup"]
    key = f"{'+'.join(c['prompts'])}|{c['kind']}|s{c['scale']}|t{c['thr10'] / 10:.1f}|{c['rule']}"
    st2 = pd.read_csv(os.path.join(R, "sam3", "tune", "stage2.csv")); r = st2[st2.config == key].iloc[0]
    val_rule = {**{cc: r[f"IoU_{cc.replace('_', ' ')}"] for cc in CLASS_COLS}, **{st: r[f"{st}_mIoU"] for st in STATE_COLS}, "avg": r.val_avg_mIoU, "pooled": r.val_pooled_mIoU}
    test_rule = from_json(json.load(open(os.path.join(R, "sam3", "test", "results.json")))["paraformer_sam3"])
    rows.append(("Base + SAM 3, rule-based (8 settings tuned on val)", val_rule, test_rule))
    for name, lab in (("L1_linear", "Model 3: L1 (per-pixel NLCD)"),):
        d = os.path.join(R, "fusion", name, "eval")
        if os.path.exists(f"{d}/history_test.csv"): rows.append((lab, from_hist(f"{d}/history_val.csv", 4), from_hist(f"{d}/history_test.csv", 4)))
    return rows

def sam3_compare_slides(pdf, red="#c62828"):
    """Two table slides: Base, the rule-based SAM 3 overlay and Model 3 (L1 head, trained late fusion), val and test."""
    try: rows = _sam3_compare_rows()
    except (FileNotFoundError, IndexError, KeyError): return 0
    note = ("All rows use the same Paraformer checkpoint (base, epoch 40). Rule-based: prompts, zoom, threshold and add/trim rule chosen on val CCLC (slides 30 to 32). "
            "Model 3 (L1 head): fixed recipe, per-pixel cross entropy on NLCD 30 m only, last epoch kept, nothing chosen on CCLC (slide 53). Red rows: test. Class mapping: Table S1.")
    for kind in ("class", "state"):
        fig = plt.figure(figsize=(16, 9))
        title = "Model 3 results: IoU (%) per class, pooled over all six states" if kind == "class" else "Model 3 results: mIoU (%) per state"
        fig.text(0.5, 0.95, title, ha="center", va="center", fontsize=25, weight="bold", color=INK)
        fig.text(0.5, 0.905, "Base alone and Base + rule-based SAM 3 overlay for reference, then Model 3 (L1 head); val (30 tiles) and test (120 tiles).",
                 ha="center", va="center", fontsize=14, color=MUTED)
        if kind == "class":
            header = ["Method", "Split", "Built-up", "Tree canopy", "Low veg.", "Water", "mIoU (pooled)", "mIoU (avg)"]
            col_x = [0.04, 0.42, 0.51, 0.605, 0.69, 0.76, 0.865, 0.96]; keys = CLASS_COLS + ["pooled", "avg"]
        else:
            header = ["Method", "Split", "DE", "NY", "MD", "PA", "VA", "WV", "Average"]
            col_x = [0.04, 0.42, 0.50, 0.565, 0.63, 0.695, 0.76, 0.825, 0.96]; keys = STATE_COLS + ["avg"]
        body = []
        for lab, v, t in rows:
            body.append(([lab, "val"] + [f"{v[k]:.1f}" if k != "avg" else f"{v[k]:.2f}" for k in keys], True, INK))
            body.append((["", "test"] + [f"{t[k]:.1f}" if k != "avg" else f"{t[k]:.2f}" for k in keys], True, red))
        if kind == "state":
            lab, vals = PAPER[0]
            body.append(([lab, "test"] + [f"{x:.1f}" for x in vals[:6]] + [f"{vals[6]:.2f}"], False, red))
        end = draw_table(fig, 0.83, header, body, best_cols=[], col_x=col_x, aligns=["left", "left"] + ["right"] * (len(keys)), row_h=0.056)
        fig.text(0.04, end - 0.005, note, fontsize=12, color=MUTED, va="top", wrap=True)
        pdf.savefig(fig); plt.close(fig)
    return 2

def model_compare_slide(pdf, red="#c62828"):
    """One table: every model and every SAM 3 variant at its val-chosen checkpoint; val average in black, test columns in red."""
    import json
    BASE_RUN = "paraformer_adamw_lr1e-4_w128_bs8"
    runs = [("Base: ImageNet ViT-B/16, serial (fine-tuned)", BASE_RUN, 100),
            ("DINOv3-sat, parallel (frozen)", "paraformer_dinov3_sat_frozen_adamw_lr1e-4_w128_bs8", 100),
            ("DINOv3-web, parallel (frozen)", "paraformer_dinov3_web_frozen_adamw_lr1e-4_w128_bs8", 100),
            ("Model 1: DINOv3-web, serial (fine-tuned)", "paraformer_dinov3_web_serial_ft_lr1e-4_vit0.1_w128_bs8_50ep", 50),
            ("Model 2: Base + frozen DINOv3-web branch", "paraformer_vit_b16_plus_dinov3_web_frozen_adamw_lr1e-4_w128_bs8_50ep", 50),
            ("Base-RGB: Paraformer on RGB only (no NIR), colour aug.", RGB_BASE_RUN, 50),
            ("Model 8: Paraformer-S (26.8 M) distilled from Model 7, RGB", MODEL8_RUN, 50),
            ("Model 10 pilot: MapOT from the 4-band Base, NIR dropped", MODEL10_PILOT, 20),
            ("Model 10: MapOT from Base-RGB (optimal-transport labels)", MODEL10_RUN, 20)]
    fmt = lambda name, ep, n, v, t: [name, str(ep), str(n)] + [f"{t[c]:.1f}" for c in CLASS_COLS] + [f"{t['pooled']:.1f}", f"{v['avg']:.2f}", f"{t['avg']:.2f}"]
    as_dict = lambda r: {**{c: r[f"pooled_{c}"] for c in CLASS_COLS}, "pooled": r.pooled_mIoU, "avg": r.avg_mIoU}
    body, running = [], []
    for name, run, n in runs:
        if not os.path.exists(os.path.join(RUNS_DIR, run, "eval", "history_test.csv")): continue
        ep, v, t, scored = _best_scores(run)
        if n - 1 not in scored: running.append(name.split(":")[0]); name += " *"
        body.append((fmt(name, ep, n, as_dict(v), as_dict(t)), True))
    n_models = len(body)
    try: sam = _sam3_compare_rows()[1:]
    except (FileNotFoundError, IndexError, KeyError): sam = []
    for lab, v, t in sam:
        body.append((fmt(lab, 40, 100, v, t), True))
    for m in (4, 5, 6, 7, 9):
        for lab, v, t in _fusion_head_rows(m):
            if t is None: continue
            ep, n_ep = (40, 100)
            if m in (7, 9) and os.path.exists(os.path.join(RUNS_DIR, "model7", "base_choice.json")):
                ep, n_ep = json.load(open(os.path.join(RUNS_DIR, "model7", "base_choice.json")))["epoch"], 50
            body.append((fmt(lab, ep, n_ep, v, t), True))
    lab, vals = PAPER[0]
    body.insert(0, ([lab, "", "", "", "", "", "", "", "", f"{vals[6]:.2f}"], False))
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.95, "All models side by side: best checkpoint chosen on val", ha="center", va="center", fontsize=25, weight="bold", color=INK)
    fig.text(0.5, 0.905, "Black: val average (used to choose the checkpoint). Red: test, never used for any choice. Class IoUs and pooled mIoU are test, pooled over all six states.",
             ha="center", va="center", fontsize=14, color=MUTED)
    header = ["Model", "Epoch", "Trained", "Built-up", "Tree", "Low veg.", "Water", "Pooled", "Val avg", "Test avg"]
    col_x = [0.03, 0.465, 0.53, 0.605, 0.67, 0.74, 0.80, 0.86, 0.915, 0.975]
    cols = [None, None, None, red, red, red, red, red, None, red]
    best = list(range(3, 10))
    rh = 0.058 if len(body) <= 11 else max(0.038, 0.66 / (len(body) + 1)); fs = 14 if len(body) <= 11 else 12
    end = draw_table(fig, 0.83, header, body, best_cols=best, col_x=col_x, aligns=["left"] + ["right"] * 9, row_h=rh,
                     col_colours=cols, rules_before=(1 + n_models,), fontsize=fs)
    note = ("Bold: best in that column. 'Trained' = epochs trained; 'Epoch' = the val-chosen checkpoint. Top group: different backbones and wirings.\n"
            "Bottom group: the Base checkpoint + SAM 3 (rule-based overlay: settings tuned on val CCLC; Models 3 to 7 and 9: L1 heads, per-pixel cross entropy on NLCD only, last epoch kept; Models 7 and 9 sit on Base-RGB).")
    if running: note += f"\n* Still training to 50 epochs ({', '.join(running)}): best among the checkpoints scored so far."
    fig.text(0.03, end - 0.005, note, fontsize=12, color=MUTED, va="top")
    pdf.savefig(fig); plt.close(fig)
    return 1

def feature_fusion_slide(pdf):
    """Proposal, black and white: feature-level fusion. Frozen Paraformer log-probabilities + frozen SAM 3 encoder features
    (FPN 144 x 144 level, PCA to 64 channels) -> small residual head trained on NLCD only. One block per step, little text."""
    from matplotlib.lines import Line2D
    from matplotlib.patches import Ellipse, FancyArrowPatch, FancyBboxPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#e6e6e6"
    fig.text(0.5, 0.95, "Model 4: Base + SAM 3 image features (feature-level fusion)", ha="center", va="center", fontsize=26, weight="bold", color="black")
    fig.text(0.5, 0.905, "Both large models stay frozen; only the small fusion head is trained, on NLCD 30 m only. Proposed, not yet trained.",
             ha="center", va="center", fontsize=14, color=MUTED)
    lab = lambda x, y, t, **k: fig.text(x, y, t, ha=k.pop("ha", "center"), va=k.pop("va", "bottom"), fontsize=k.pop("fs", 10.5),
                                        style="italic", color="black", linespacing=1.1, **k)
    yA, yB = 0.735, 0.455                                              # row centres: Paraformer, SAM 3 / head
    # input
    _bw_box(fig, 0.015, 0.39, 0.055, 0.41, "Input", "NAIP tile\n1 m\nRGB + NIR", fill=LIGHT, tfs=14, bfs=12)
    _bw_arrow(fig, (0.07, yA), (0.115, yA)); lab(0.0925, yA + 0.008, "4 bands")
    _bw_arrow(fig, (0.07, yB), (0.115, yB)); lab(0.0925, yB + 0.008, "RGB")
    # row A: Paraformer
    _bw_box(fig, 0.115, 0.67, 0.11, 0.13, "Paraformer", "Base, epoch 40\nfrozen", tfs=15, bfs=12)
    # row B: SAM 3 encoder -> PCA -> upsample -> concat
    _bw_box(fig, 0.115, 0.39, 0.11, 0.13, "SAM 3 encoder", "ViT, 32 layers\nfrozen", tfs=14, bfs=12)
    _bw_box(fig, 0.255, 0.39, 0.065, 0.13, "PCA", "256 → 64\nno labels", tfs=13, bfs=11.5)
    _bw_box(fig, 0.35, 0.39, 0.065, 0.13, "Upsample", "× 7\n7 m → 1 m", tfs=13, bfs=11.5)
    _bw_box(fig, 0.445, 0.39, 0.06, 0.13, "Concat", "17 + 64\n= 81", tfs=13, bfs=11.5)
    for (a, b), t in zip([(0.225, 0.255), (0.32, 0.35), (0.415, 0.445)], ["256 ch\n7 m", "64 ch\n7 m", "64 ch\n1 m"]):
        _bw_arrow(fig, (a, yB), (b, yB)); lab((a + b) / 2, 0.372, t.replace("\n", ", "), va="top", fs=10.5)
    # fusion head (trained): container + three convs
    _bw_box(fig, 0.535, 0.375, 0.255, 0.16, "", None, dashed=True, lw=1.8)
    fig.text(0.6625, 0.553, "Fusion head  (trained, ~0.1 M weights)", ha="center", va="center", fontsize=13, weight="bold", color="black")
    xs, w = [0.543, 0.6287, 0.7143], 0.0677
    for x, (t, b) in zip(xs, [("1 × 1 conv", "81 → 64"), ("3 × 3 conv", "× 3 layers"), ("1 × 1 conv", "64 → 17\nstarts at 0")]):
        _bw_box(fig, x, 0.39, w, 0.13, t, b, dashed=True, tfs=12.5, bfs=11.5)
    _bw_arrow(fig, (0.505, yB), (0.543, yB)); lab(0.522, 0.372, "81 ch", va="top", fs=10.5)
    _bw_arrow(fig, (xs[0] + w, yB), (xs[1], yB)); _bw_arrow(fig, (xs[1] + w, yB), (xs[2], yB))
    # residual add and output
    fig.patches.append(Ellipse((0.835, yB), 0.028, 0.05, transform=fig.transFigure, facecolor="white", edgecolor="black", lw=1.6))
    fig.text(0.835, yB + 0.003, "+", ha="center", va="center", fontsize=22, weight="bold", color="black")
    _bw_arrow(fig, (xs[2] + w, yB), (0.821, yB)); lab(0.806, 0.372, "17 ch", va="top", fs=10.5)
    _bw_box(fig, 0.875, 0.39, 0.11, 0.13, "Fused logits", "17 classes\n1 m", fill=LIGHT, tfs=14, bfs=12)
    _bw_arrow(fig, (0.849, yB), (0.875, yB))
    # Paraformer log-probabilities: into the concat, and the skip to the add
    fig.lines.append(Line2D([0.225, 0.835], [yA, yA], transform=fig.transFigure, color="black", lw=1.6))
    _bw_arrow(fig, (0.475, yA), (0.475, 0.52))
    fig.lines.append(Line2D([0.835, 0.835], [yA, 0.5], transform=fig.transFigure, color="black", lw=1.6))
    _bw_arrow(fig, (0.835, 0.5), (0.835, yB + 0.025))
    lab(0.35, yA + 0.01, "log-probabilities: 17 ch, 1 m", fs=11.5)
    lab(0.842, 0.62, "skip", ha="left", va="center", fs=11.5)
    # training and inference
    _bw_box(fig, 0.42, 0.11, 0.10, 0.14, "NLCD label", "30 m\ntraining only", fill=LIGHT, tfs=13.5, bfs=12)
    _bw_box(fig, 0.555, 0.11, 0.12, 0.14, "Training (L1)", "per-pixel\ncross entropy", tfs=13.5, bfs=12)
    _bw_box(fig, 0.73, 0.11, 0.105, 0.14, "CCLC 1 m", "scoring only", fill=LIGHT, tfs=13.5, bfs=12)
    _bw_box(fig, 0.875, 0.11, 0.11, 0.14, "Inference", "argmax\n→ 4 classes", tfs=14, bfs=12)
    _bw_arrow(fig, (0.52, 0.18), (0.555, 0.18)); _bw_arrow(fig, (0.835, 0.18), (0.875, 0.18))
    _bw_arrow(fig, (0.89, 0.39), (0.665, 0.25)); _bw_arrow(fig, (0.93, 0.39), (0.93, 0.25))
    fig.patches.append(FancyArrowPatch((0.60, 0.25), (0.60, 0.375), transform=fig.transFigure, arrowstyle="-|>", mutation_scale=14,
                                       color="black", lw=1.3, ls=(0, (4, 3)), shrinkA=2, shrinkB=2))
    lab(0.607, 0.30, "gradient", ha="left", va="center", fs=11.5)
    # legend
    for x, fill, dashed, t in [(0.03, LIGHT, False, "data"), (0.12, "white", False, "frozen / fixed"), (0.27, "white", True, "trained")]:
        fig.patches.append(FancyBboxPatch((x, 0.195), 0.03, 0.05, boxstyle="round,pad=0.004,rounding_size=0.008", transform=fig.transFigure,
                                          facecolor=fill, edgecolor="black", lw=1.4, ls=(0, (4, 2.5)) if dashed else "-"))
        fig.text(x + 0.04, 0.22, t, ha="left", va="center", fontsize=13, color="black")
    fig.text(0.03, 0.135, "The last conv starts at 0, so at step 0\nthe output is exactly Paraformer's.", ha="left", va="center", fontsize=13, color=MUTED, linespacing=1.3)
    pdf.savefig(fig); plt.close(fig)

def model5_slide(pdf):
    """Proposal, black and white: Model 5. Base (frozen) + NDVI + SAM 3 masks at 1 m -> trained fusion head -> logits pooled inside
    each SAM 3 object. One block per step, little text."""
    from matplotlib.lines import Line2D
    from matplotlib.patches import FancyBboxPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#e6e6e6"
    fig.text(0.5, 0.95, "Model 5: Base + image evidence at 1 m, decided per SAM 3 object", ha="center", va="center", fontsize=26, weight="bold", color="black")
    fig.text(0.5, 0.905, "Base stays frozen. NDVI and SAM 3 masks are added at 1 m; inside each SAM 3 object the decision is shared. Only the fusion head is trained, on NLCD only.",
             ha="center", va="center", fontsize=13.5, color=MUTED)
    lab = lambda x, y, t, **k: fig.text(x, y, t, ha=k.pop("ha", "center"), va=k.pop("va", "bottom"), fontsize=k.pop("fs", 10.5),
                                        style="italic", color="black", linespacing=1.1, **k)
    line = lambda xs, ys: fig.lines.append(Line2D(xs, ys, transform=fig.transFigure, color="black", lw=1.6))
    yA, yB, yC = 0.775, 0.60, 0.425
    _bw_box(fig, 0.015, 0.36, 0.055, 0.48, "Input", "NAIP tile\n1 m\nRGB + NIR", fill=LIGHT, tfs=14, bfs=12)
    _bw_box(fig, 0.115, 0.715, 0.12, 0.12, "Paraformer", "Base, epoch 40\nfrozen", tfs=14, bfs=12)
    _bw_box(fig, 0.115, 0.54, 0.12, 0.12, "NDVI", "(NIR − R) / (NIR + R)\nfixed formula", tfs=14, bfs=11.5)
    _bw_box(fig, 0.115, 0.365, 0.12, 0.12, "SAM 3", "6 text prompts\nfrozen", tfs=14, bfs=12)
    for y, t in ((yA, "4 bands"), (yB, "R, NIR"), (yC, "RGB")):
        _bw_arrow(fig, (0.07, y), (0.115, y)); lab(0.0925, y + 0.008, t)
    _bw_box(fig, 0.29, 0.54, 0.06, 0.12, "Concat", "17 + 1 + 6\n= 24", tfs=13, bfs=11.5)
    line([0.235, 0.32], [yA, yA]); _bw_arrow(fig, (0.32, yA), (0.32, 0.66)); lab(0.2625, yA + 0.008, "17 ch")
    _bw_arrow(fig, (0.235, yB), (0.29, yB)); lab(0.2625, yB + 0.008, "1 ch")
    line([0.235, 0.32], [0.455, 0.455]); _bw_arrow(fig, (0.32, 0.455), (0.32, 0.54)); lab(0.2625, 0.463, "6 masks")
    # fusion head
    _bw_box(fig, 0.39, 0.525, 0.30, 0.165, "", None, dashed=True, lw=1.8)
    fig.text(0.54, 0.707, "Fusion head  (trained, ~0.1 M weights)", ha="center", va="center", fontsize=13, weight="bold", color="black")
    xs, w = [0.398, 0.4975, 0.597], 0.085
    for x, (t, b) in zip(xs, [("1 × 1 conv", "24 → 64"), ("3 × 3 conv", "× 3 layers"), ("1 × 1 conv", "64 → 17, starts at 0\n+ log p (skip)")]):
        _bw_box(fig, x, 0.54, w, 0.12, t, b, dashed=True, tfs=12.5, bfs=11)
    _bw_arrow(fig, (0.35, yB), (0.398, yB)); lab(0.374, 0.57, "24 ch", va="top", fs=10)
    _bw_arrow(fig, (xs[0] + w, yB), (xs[1], yB)); _bw_arrow(fig, (xs[1] + w, yB), (xs[2], yB))
    # object pooling and output
    _bw_box(fig, 0.73, 0.54, 0.115, 0.12, "Object pooling", "mean of the logits\ninside each object;\nother pixels unchanged", tfs=13, bfs=10.5)
    _bw_arrow(fig, (xs[2] + w, yB), (0.73, yB)); lab(0.706, 0.57, "17 ch", va="top", fs=10)
    _bw_box(fig, 0.88, 0.54, 0.105, 0.12, "Fused logits", "17 classes\n1 m", fill=LIGHT, tfs=14, bfs=12)
    _bw_arrow(fig, (0.845, yB), (0.88, yB))
    line([0.175, 0.175, 0.7875], [0.365, 0.31, 0.31]); _bw_arrow(fig, (0.7875, 0.31), (0.7875, 0.54))
    lab(0.48, 0.318, "objects = connected components of the SAM 3 masks (score ≥ 0.5)", fs=11)
    # bottom row: training and inference
    _bw_box(fig, 0.135, 0.09, 0.09, 0.13, "NLCD label", "30 m\ntraining only", fill=LIGHT, tfs=13, bfs=11.5)
    _bw_box(fig, 0.25, 0.09, 0.17, 0.13, "Training (L1)", "NLCD only: per-pixel\ncross entropy", tfs=13.5, bfs=11.5)
    _bw_box(fig, 0.73, 0.09, 0.105, 0.13, "CCLC 1 m", "scoring only", fill=LIGHT, tfs=13, bfs=11.5)
    _bw_box(fig, 0.875, 0.09, 0.11, 0.13, "Inference", "argmax\n→ 4 classes", tfs=13.5, bfs=11.5)
    _bw_arrow(fig, (0.225, 0.155), (0.25, 0.155)); _bw_arrow(fig, (0.835, 0.155), (0.875, 0.155))
    line([0.90, 0.90, 0.335], [0.54, 0.26, 0.26]); _bw_arrow(fig, (0.335, 0.26), (0.335, 0.22))
    _bw_arrow(fig, (0.95, 0.54), (0.95, 0.22))
    # legend
    for y, fill, dashed, t in [(0.27, LIGHT, False, "data"), (0.215, "white", False, "frozen / fixed"), (0.16, "white", True, "trained")]:
        fig.patches.append(FancyBboxPatch((0.02, y - 0.02), 0.025, 0.04, boxstyle="round,pad=0.004,rounding_size=0.008", transform=fig.transFigure,
                                          facecolor=fill, edgecolor="black", lw=1.4, ls=(0, (4, 2.5)) if dashed else "-"))
        fig.text(0.053, y, t, ha="left", va="center", fontsize=12, color="black")
    fig.text(0.5, 0.04, "A roof or a road gets one decision; a lawn pixel decides on its own, with its NDVI. The head starts as an exact copy of Paraformer.",
             ha="center", va="center", fontsize=12, color=MUTED)
    pdf.savefig(fig); plt.close(fig)

def model6_slide(pdf):
    """Proposal, black and white: Model 6, feature-space fusion. Paraformer decoder features + DOFA features of all four bands
    (NIR included) + NDVI + SAM 3 encoder features -> trained head -> pooled per SAM 3 object. One block per step."""
    from matplotlib.lines import Line2D
    from matplotlib.patches import FancyBboxPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#e6e6e6"
    fig.text(0.5, 0.95, "Model 6: feature-space fusion with a multispectral foundation encoder", ha="center", va="center", fontsize=25, weight="bold", color="black")
    fig.text(0.5, 0.905, "Paraformer's decoder features, DOFA features of all four bands (NIR included), NDVI, SAM 3 masks and SAM 3 encoder features, fused by a trained head and decided per SAM 3 object. NLCD only.",
             ha="center", va="center", fontsize=12.5, color=MUTED)
    lab = lambda x, y, t, **k: fig.text(x, y, t, ha=k.pop("ha", "center"), va=k.pop("va", "bottom"), fontsize=k.pop("fs", 10),
                                        style="italic", color="black", linespacing=1.1, **k)
    line = lambda xs, ys: fig.lines.append(Line2D(xs, ys, transform=fig.transFigure, color="black", lw=1.6))
    yP, yD, yN, yS = 0.805, 0.655, 0.5125, 0.385                      # row centres: Paraformer, DOFA, NDVI, SAM 3
    _bw_box(fig, 0.015, 0.33, 0.055, 0.54, "Input", "NAIP tile\n1 m\nRGB + NIR", fill=LIGHT, tfs=14, bfs=12)
    _bw_box(fig, 0.11, 0.75, 0.12, 0.11, "Paraformer", "Base, epoch 40\nfrozen", tfs=13.5, bfs=11.5)
    _bw_box(fig, 0.11, 0.60, 0.12, 0.11, "DOFA ViT-L/16", "frozen; bands given by\nwavelength, NIR included", tfs=13, bfs=10.5)
    _bw_box(fig, 0.11, 0.47, 0.12, 0.085, "NDVI", "(NIR − R) / (NIR + R)", tfs=13, bfs=10.5)
    _bw_box(fig, 0.11, 0.33, 0.12, 0.11, "SAM 3 encoder", "frozen", tfs=13, bfs=11.5)
    for y, t in ((yP, "4 bands"), (yD, "4 bands"), (yN, "R, NIR"), (yS, "RGB")):
        _bw_arrow(fig, (0.07, y), (0.11, y)); lab(0.09, y + 0.008, t, fs=9.5)
    # DOFA and SAM 3 rows: PCA then upsample
    for y0, a, b in ((0.60, "1024 → 64\nno labels", "× 16\n16 m → 1 m"), (0.33, "256 → 64\nno labels", "× 7\n7 m → 1 m")):
        _bw_box(fig, 0.27, y0, 0.075, 0.11, "PCA", a, tfs=12.5, bfs=10.5); _bw_box(fig, 0.385, y0, 0.075, 0.11, "Upsample", b, tfs=12.5, bfs=10.5)
        yc = y0 + 0.055
        _bw_arrow(fig, (0.23, yc), (0.27, yc)); _bw_arrow(fig, (0.345, yc), (0.385, yc))
        lab(0.25, y0 - 0.012, "1024 ch, 16 m" if y0 == 0.60 else "256 ch, 7 m", va="top", fs=9.5)
        lab(0.365, y0 - 0.012, "64 ch", va="top", fs=9.5)
    _bw_box(fig, 0.50, 0.55, 0.065, 0.14, "Concat", "408 ch\n1 m", tfs=13, bfs=11)
    line([0.23, 0.52], [yP, yP]); _bw_arrow(fig, (0.52, yP), (0.52, 0.69)); lab(0.375, yP + 0.008, "decoder features 256 ch + log p 17 ch, 1 m")
    _bw_arrow(fig, (0.46, yD), (0.50, yD)); lab(0.48, yD + 0.008, "64 ch", fs=9.5)
    line([0.23, 0.52], [yN, yN]); _bw_arrow(fig, (0.52, yN), (0.52, 0.55)); lab(0.375, yN + 0.008, "1 ch, 1 m")
    line([0.46, 0.545], [yS, yS]); _bw_arrow(fig, (0.545, yS), (0.545, 0.55)); lab(0.50, yS + 0.008, "64 ch + 6 masks", fs=9.5)
    # fusion head
    _bw_box(fig, 0.60, 0.545, 0.20, 0.155, "", None, dashed=True, lw=1.8)
    fig.text(0.70, 0.715, "Fusion head  (trained, ~0.5 M weights)", ha="center", va="center", fontsize=12.5, weight="bold", color="black")
    xs, w = [0.606, 0.670, 0.734], 0.06
    for x, (t, b) in zip(xs, [("1 × 1 conv", "408 → 128"), ("3 × 3 conv", "× 3, 128 ch"), ("1 × 1 conv", "128 → 17\nstarts at 0\n+ log p")]):
        _bw_box(fig, x, 0.56, w, 0.12, t, b, dashed=True, tfs=11.5, bfs=10)
    _bw_arrow(fig, (0.565, 0.62), (0.606, 0.62)); _bw_arrow(fig, (xs[0] + w, 0.62), (xs[1], 0.62)); _bw_arrow(fig, (xs[1] + w, 0.62), (xs[2], 0.62))
    # object pooling and output
    _bw_box(fig, 0.825, 0.56, 0.08, 0.12, "Object\npooling", "\n\nmean logits per\nSAM 3 object", tfs=12, bfs=9.5)
    _bw_arrow(fig, (xs[2] + w, 0.62), (0.825, 0.62))
    _bw_box(fig, 0.92, 0.56, 0.07, 0.12, "Fused\nlogits", "\n\n17 classes\n1 m", fill=LIGHT, tfs=12, bfs=10)
    _bw_arrow(fig, (0.905, 0.62), (0.92, 0.62))
    line([0.17, 0.17, 0.865], [0.33, 0.29, 0.29]); _bw_arrow(fig, (0.865, 0.29), (0.865, 0.56))
    lab(0.66, 0.298, "objects = connected components of the SAM 3 masks (score ≥ 0.5)", fs=10.5)
    # bottom row
    _bw_box(fig, 0.13, 0.08, 0.09, 0.12, "NLCD label", "30 m\ntraining only", fill=LIGHT, tfs=12.5, bfs=11)
    _bw_box(fig, 0.245, 0.08, 0.17, 0.12, "Training (L1)", "NLCD only: per-pixel\ncross entropy", tfs=13, bfs=11)
    _bw_box(fig, 0.73, 0.08, 0.105, 0.12, "CCLC 1 m", "scoring only", fill=LIGHT, tfs=12.5, bfs=11)
    _bw_box(fig, 0.875, 0.08, 0.11, 0.12, "Inference", "argmax\n→ 4 classes", tfs=13, bfs=11)
    _bw_arrow(fig, (0.22, 0.14), (0.245, 0.14)); _bw_arrow(fig, (0.835, 0.14), (0.875, 0.14))
    line([0.94, 0.94, 0.33], [0.56, 0.245, 0.245]); _bw_arrow(fig, (0.33, 0.245), (0.33, 0.20))
    _bw_arrow(fig, (0.975, 0.56), (0.975, 0.20))
    for y, fill, dashed, t in [(0.25, LIGHT, False, "data"), (0.20, "white", False, "frozen / fixed"), (0.15, "white", True, "trained")]:
        fig.patches.append(FancyBboxPatch((0.02, y - 0.02), 0.025, 0.04, boxstyle="round,pad=0.004,rounding_size=0.008", transform=fig.transFigure,
                                          facecolor=fill, edgecolor="black", lw=1.4, ls=(0, (4, 2.5)) if dashed else "-"))
        fig.text(0.053, y, t, ha="left", va="center", fontsize=11.5, color="black")
    fig.text(0.5, 0.035, "DOFA (Dynamic One-For-All) is the one foundation encoder here that reads NIR: each band is identified by its wavelength. The head starts as an exact copy of Paraformer.",
             ha="center", va="center", fontsize=11.5, color=MUTED)
    pdf.savefig(fig); plt.close(fig)

def model7_slide(pdf):
    """Proposal, black and white: Model 7 = Model 5 on RGB only, NIR dropped completely (no NDVI, no surrogate). The Base is
    drawn broken open (CNN -> projection -> ViT -> decoder -> two heads) and retrained on three bands. One block per step."""
    from matplotlib.lines import Line2D
    from matplotlib.patches import FancyBboxPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#e6e6e6"
    fig.text(0.5, 0.955, "Model 7: Model 5 on RGB only (no NIR), with the Base broken open", ha="center", va="center", fontsize=25, weight="bold", color="black")
    fig.text(0.5, 0.905, "Every input is RGB; NIR is dropped completely (no NDVI). Stage 1: the Base is retrained on three bands (NLCD only, colour augmentation).\n"
             "Stage 2: Base and SAM 3 are frozen and only the fusion head is trained, on NLCD only. The rest is Model 5: SAM 3 masks at 1 m and one decision per SAM 3 object.",
             ha="center", va="center", fontsize=11.5, color=MUTED, linespacing=1.25)
    lab = lambda x, y, t, **k: fig.text(x, y, t, ha=k.pop("ha", "center"), va=k.pop("va", "bottom"), fontsize=k.pop("fs", 10),
                                        style="italic", color="black", linespacing=1.1, **k)
    line = lambda xs, ys: fig.lines.append(Line2D(xs, ys, transform=fig.transFigure, color="black", lw=1.6))
    yB, yN = 0.725, 0.465                                             # row centres: Base chain, SAM 3 / head
    _bw_box(fig, 0.015, 0.38, 0.055, 0.48, "Input", "NAIP tile\n1 m\nRGB only\n(NIR dropped)", fill=LIGHT, tfs=14, bfs=11.5)
    # Base, broken open
    _bw_box(fig, 0.085, 0.62, 0.63, 0.24, "", None, lw=1.8)
    fig.text(0.40, 0.838, "Base (Paraformer), broken open  —  stage 1: retrained on RGB only (3 bands), NLCD only, colour augmentation; frozen in stage 2",
             ha="center", va="center", fontsize=11.5, weight="bold", color="black")
    boxes = [(0.10, 0.115, "CNN branch", "L2HNet, 3 bands → 128\nout: 14 × 14 × 1024"), (0.24, 0.075, "Projection", "1 × 1 conv\n1024 → 768"),
             (0.34, 0.115, "ImageNet ViT-B/16", "12 blocks\nfine-tuned"), (0.48, 0.095, "Fusion decoder", "+ CNN skips"),
             (0.60, 0.10, "Two heads", "CNN head + ViT head\naveraged → 17 probs")]
    for x, w, t, b in boxes: _bw_box(fig, x, 0.665, w, 0.12, t, b, tfs=12, bfs=10)
    for (x, w, _, _), (x2, _, _, _) in zip(boxes[:-1], boxes[1:]): _bw_arrow(fig, (x + w, yB), (x2, yB))
    _bw_arrow(fig, (0.07, yB), (0.10, yB)); lab(0.085, yB + 0.008, "RGB", fs=9.5)
    line([0.1575, 0.1575, 0.5275], [0.665, 0.64, 0.64]); _bw_arrow(fig, (0.5275, 0.64), (0.5275, 0.665))
    lab(0.345, 0.634, "skip features at 224, 112, 56 and 14 px", va="top", fs=9.5)
    line([0.65, 0.65, 0.43], [0.665, 0.60, 0.60]); _bw_arrow(fig, (0.43, 0.60), (0.43, 0.525)); lab(0.54, 0.597, "17 probabilities, 1 m", va="top", fs=10)
    # SAM 3 -> masks and objects
    _bw_box(fig, 0.10, 0.405, 0.14, 0.12, "SAM 3", "6 text prompts: building, road,\nparking lot, runway, water, river\nfrozen", tfs=12.5, bfs=9.5)
    _bw_arrow(fig, (0.07, yN), (0.10, yN)); lab(0.085, yN + 0.008, "RGB", fs=9.5)
    _bw_arrow(fig, (0.24, yN), (0.40, yN)); lab(0.32, yN + 0.008, "6 masks, 1 m", fs=10)
    line([0.17, 0.17, 0.80], [0.405, 0.20, 0.20]); _bw_arrow(fig, (0.80, 0.20), (0.80, 0.405))
    lab(0.52, 0.208, "objects = connected components of the SAM 3 masks (score ≥ 0.5)", fs=10)
    # concat, head, pooling, output
    _bw_box(fig, 0.40, 0.405, 0.06, 0.12, "Concat", "17 + 6\n= 23", tfs=12.5, bfs=10.5)
    _bw_box(fig, 0.47, 0.385, 0.25, 0.16, "", None, dashed=True, lw=1.8)
    fig.text(0.595, 0.561, "Fusion head  (trained in stage 2, ~0.1 M weights)", ha="center", va="center", fontsize=11.5, weight="bold", color="black")
    xs, w = [0.478, 0.560, 0.642], 0.07
    for x, (t, b) in zip(xs, [("1 × 1 conv", "23 → 64"), ("3 × 3 conv", "× 3 layers"), ("1 × 1 conv", "64 → 17, starts at 0\n+ log p (skip)")]):
        _bw_box(fig, x, 0.40, w, 0.12, t, b, dashed=True, tfs=11.5, bfs=9.5)
    _bw_arrow(fig, (0.46, yN), (xs[0], yN)); _bw_arrow(fig, (xs[0] + w, yN), (xs[1], yN)); _bw_arrow(fig, (xs[1] + w, yN), (xs[2], yN))
    _bw_box(fig, 0.745, 0.405, 0.11, 0.12, "Object pooling", "mean logits per\nSAM 3 object; other\npixels unchanged", tfs=12, bfs=9.5)
    _bw_arrow(fig, (xs[2] + w, yN), (0.745, yN))
    _bw_box(fig, 0.88, 0.405, 0.105, 0.12, "Fused logits", "17 classes\n1 m", fill=LIGHT, tfs=12.5, bfs=10.5)
    _bw_arrow(fig, (0.855, yN), (0.88, yN))
    # bottom row
    _bw_box(fig, 0.13, 0.03, 0.09, 0.12, "NLCD label", "30 m\ntraining only", fill=LIGHT, tfs=12, bfs=10.5)
    _bw_box(fig, 0.245, 0.03, 0.17, 0.12, "Training (L1)", "NLCD only: per-pixel\ncross entropy", tfs=12.5, bfs=10.5)
    _bw_box(fig, 0.73, 0.03, 0.105, 0.12, "CCLC 1 m", "scoring only", fill=LIGHT, tfs=12, bfs=10.5)
    _bw_box(fig, 0.875, 0.03, 0.11, 0.12, "Inference", "argmax\n→ 4 classes", tfs=12.5, bfs=10.5)
    _bw_arrow(fig, (0.22, 0.09), (0.245, 0.09)); _bw_arrow(fig, (0.835, 0.09), (0.875, 0.09))
    line([0.93, 0.93, 0.33], [0.405, 0.175, 0.175]); _bw_arrow(fig, (0.33, 0.175), (0.33, 0.15))
    _bw_arrow(fig, (0.965, 0.405), (0.965, 0.15))
    for y, fill, dashed, t in [(0.13, LIGHT, False, "data"), (0.09, "white", False, "frozen in stage 2"), (0.05, "white", True, "trained in stage 2")]:
        fig.patches.append(FancyBboxPatch((0.02, y - 0.016), 0.022, 0.032, boxstyle="round,pad=0.003,rounding_size=0.007", transform=fig.transFigure,
                                          facecolor=fill, edgecolor="black", lw=1.3, ls=(0, (4, 2.5)) if dashed else "-"))
        fig.text(0.048, y, t, ha="left", va="center", fontsize=10.5, color="black")
    pdf.savefig(fig); plt.close(fig)

def _sbox(fig, x, y, w, h, t, b, fill="white", dashed=False, tfs=11, bfs=9.5):
    """Compact block for dense one-slide diagrams: title in the upper part, one short body line in the lower part."""
    from matplotlib.patches import FancyBboxPatch
    fig.patches.append(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.004,rounding_size=0.008", transform=fig.transFigure,
                                      facecolor=fill, edgecolor="black", lw=1.3, ls=(0, (4, 2.5)) if dashed else "-"))
    if b:
        fig.text(x + w / 2, y + h * 0.68, t, ha="center", va="center", fontsize=tfs, weight="bold", color="black")
        fig.text(x + w / 2, y + h * 0.28, b, ha="center", va="center", fontsize=bfs, color="black")
    else:
        fig.text(x + w / 2, y + h / 2, t, ha="center", va="center", fontsize=tfs, weight="bold", color="black")

def model8_slide(pdf):
    """Proposal, black and white, one compact slide: Model 8 = Model 7 distilled into a slim RGB Paraformer (student, 26.8 M).
    Training: frozen Model 7 (teacher) labels every 1 m pixel on the fly; student learns from it + NLCD. Inference: student alone."""
    from matplotlib.lines import Line2D
    from matplotlib.patches import FancyBboxPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#e6e6e6"
    B = lambda *a, **k: _sbox(fig, *a, **k)
    A = lambda p, q: _bw_arrow(fig, p, q, lw=1.3)
    line = lambda xs, ys, **k: fig.lines.append(Line2D(xs, ys, transform=fig.transFigure, color="black", lw=k.pop("lw", 1.3), **k))
    lab = lambda x, y, t, **k: fig.text(x, y, t, ha=k.pop("ha", "center"), va=k.pop("va", "bottom"), fontsize=k.pop("fs", 9), style="italic", color="black", **k)
    fig.text(0.5, 0.955, "Model 8: Model 7 distilled into one small RGB network", ha="center", va="center", fontsize=25, weight="bold", color="black")
    fig.text(0.5, 0.91, "Training: the frozen Model 7 (teacher) labels every 1 m pixel on the fly; a slim Paraformer (student, 26.8 M) learns from it and from NLCD.\n"
             "Deployed: the student alone, RGB only, one forward pass, no SAM 3. Results on the next slide.", ha="center", va="center", fontsize=11.5, color=MUTED, linespacing=1.25)
    # ---------------------------------------------------------------- 1  training
    fig.text(0.015, 0.858, "1   Training (offline)", ha="left", va="center", fontsize=13, weight="bold", color="black")
    _bw_box(fig, 0.015, 0.45, 0.05, 0.37, "Input", "NAIP\ntile\n1 m\nRGB", fill=LIGHT, tfs=12, bfs=10.5)
    # teacher
    _bw_box(fig, 0.085, 0.655, 0.395, 0.175, "", None, lw=1.6)
    fig.text(0.2825, 0.812, "Teacher = Model 7, frozen  (≈ 985 M parameters)", ha="center", va="center", fontsize=11, weight="bold", color="black")
    B(0.095, 0.73, 0.08, 0.06, "Base-RGB", "145.4 M"); B(0.095, 0.663, 0.08, 0.06, "SAM 3", "840 M, masks")
    B(0.215, 0.697, 0.09, 0.06, "Fusion head", "0.1 M, L1"); B(0.345, 0.697, 0.12, 0.06, "Object pooling", "one decision per SAM 3 object")
    A((0.175, 0.76), (0.215, 0.742)); A((0.175, 0.693), (0.215, 0.712)); A((0.305, 0.727), (0.345, 0.727))
    A((0.065, 0.76), (0.095, 0.76)); A((0.065, 0.693), (0.095, 0.693))
    B(0.505, 0.697, 0.085, 0.06, "Soft targets", "17 probs, 1 m", fill=LIGHT); A((0.465, 0.727), (0.505, 0.727))
    # student
    _bw_box(fig, 0.085, 0.445, 0.395, 0.175, "", None, dashed=True, lw=1.8)
    fig.text(0.2825, 0.602, "Student = Paraformer-S, trained  (26.8 M parameters)", ha="center", va="center", fontsize=11, weight="bold", color="black")
    blocks = [(0.095, 0.07, "L2HNet-S", "CNN, 3.6 M"), (0.177, 0.055, "1 × 1 proj", "0.1 M"), (0.244, 0.07, "ViT-S/16", "21.3 M"),
              (0.326, 0.06, "Decoder", "1.7 M"), (0.398, 0.07, "2 heads", "averaged")]
    for x, w, t, b in blocks: B(x, 0.497, w, 0.066, t, b, dashed=True, tfs=10.5, bfs=9)
    for (x, w, _, _), (x2, _, _, _) in zip(blocks[:-1], blocks[1:]): A((x + w, 0.53), (x2, 0.53))
    A((0.065, 0.53), (0.095, 0.53))
    line([0.13, 0.13, 0.356], [0.50, 0.468, 0.468]); A((0.356, 0.468), (0.356, 0.50)); lab(0.24, 0.462, "CNN skips", va="top", fs=8.5)
    B(0.505, 0.497, 0.085, 0.066, "Student output", "17 probs, 1 m", fill=LIGHT); A((0.468, 0.53), (0.505, 0.53))
    # loss, NLCD, gradient
    _bw_box(fig, 0.63, 0.50, 0.15, 0.255, "Loss", "\n\nKL(teacher || student)\nat every 1 m pixel\n\n+ λ · CE vs NLCD 30 m\n\nboth student heads", tfs=12, bfs=10)
    A((0.59, 0.727), (0.63, 0.70)); A((0.59, 0.53), (0.63, 0.555))
    B(0.82, 0.60, 0.085, 0.07, "NLCD label", "30 m", fill=LIGHT, tfs=11.5, bfs=10); A((0.82, 0.635), (0.78, 0.635))
    line([0.705, 0.705, 0.2825], [0.50, 0.425, 0.425], ls=(0, (4, 3)))
    fig.patches.append(matplotlib.patches.FancyArrowPatch((0.2825, 0.425), (0.2825, 0.445), transform=fig.transFigure, arrowstyle="-|>", mutation_scale=12,
                                                           color="black", lw=1.3, shrinkA=0, shrinkB=1))
    lab(0.49, 0.419, "gradient → student only", va="top", fs=9.5)
    # ---------------------------------------------------------------- 2  inference
    fig.text(0.015, 0.345, "2   Inference (deployed): the student alone", ha="left", va="center", fontsize=13, weight="bold", color="black")
    yI = 0.255
    B(0.085, 0.225, 0.075, 0.06, "Input", "NAIP RGB, 1 m", fill=LIGHT)
    B(0.195, 0.225, 0.12, 0.06, "Paraformer-S", "26.8 M, one pass")
    B(0.35, 0.225, 0.085, 0.06, "Probabilities", "17 classes, 1 m", fill=LIGHT)
    B(0.47, 0.225, 0.10, 0.06, "argmax", "→ Table S1 → 4 classes")
    B(0.605, 0.225, 0.075, 0.06, "Score", "mIoU")
    B(0.715, 0.225, 0.075, 0.06, "CCLC 1 m", "scoring only", fill=LIGHT)
    for a, b in [(0.16, 0.195), (0.315, 0.35), (0.435, 0.47), (0.57, 0.605)]: A((a, yI), (b, yI))
    A((0.715, yI), (0.68, yI))
    # ---------------------------------------------------------------- parameters box, legend, note
    _bw_box(fig, 0.82, 0.07, 0.165, 0.43, "", None, lw=1.2)
    fig.text(0.9025, 0.475, "Parameters at inference", ha="center", va="center", fontsize=11.5, weight="bold", color="black")
    rows = [("Model 7 (teacher)", "985.5 M", True), ("   Base-RGB", "145.4", False), ("   SAM 3", "840.0", False), ("   fusion head", "0.1", False),
            ("Model 8 (student)", "26.8 M", True), ("   L2HNet-S", "3.6", False), ("   ViT-S/16", "21.3", False), ("   decoder + rest", "1.8", False)]
    for i, (k, v, bold) in enumerate(rows):
        y = 0.44 - i * 0.036 - (0.02 if i >= 4 else 0)
        fig.text(0.83, y, k, ha="left", va="center", fontsize=10.5, weight="bold" if bold else "normal", color="black")
        fig.text(0.975, y, v, ha="right", va="center", fontsize=10.5, weight="bold" if bold else "normal", color="black")
    fig.text(0.9025, 0.10, "37× smaller than Model 7\n5.4× smaller than the Base", ha="center", va="center", fontsize=11, weight="bold", color="black", linespacing=1.3)
    for y, fill, dashed, t in [(0.14, LIGHT, False, "data"), (0.10, "white", False, "frozen / fixed"), (0.06, "white", True, "trained")]:
        fig.patches.append(FancyBboxPatch((0.02, y - 0.014), 0.02, 0.028, boxstyle="round,pad=0.003,rounding_size=0.006", transform=fig.transFigure,
                                          facecolor=fill, edgecolor="black", lw=1.2, ls=(0, (4, 2.5)) if dashed else "-"))
        fig.text(0.047, y, t, ha="left", va="center", fontsize=10, color="black")
    fig.text(0.17, 0.14, "Paraformer-S = the Base with every block narrower: CNN width 64 and 256-ch outputs (36.9 → 3.6 M), ViT-B/16 → ViT-S/16 (85.1 → 21.3 M), decoder 22.4 → 1.7 M.\n"
             "The teacher runs on the fly during training (nothing stored); NLCD keeps the student honest where the teacher is wrong. CCLC is used only for scoring.",
             ha="left", va="top", fontsize=10.5, color=MUTED, linespacing=1.35)
    pdf.savefig(fig); plt.close(fig)

def model9_slide(pdf):
    """Proposal, black and white, one compact slide: Model 9 = Model 7 with SAM 3 replaced by a 4.9 M mask UNet trained to copy
    SAM 3's six mask maps from RGB (label-free). Stage A trains the UNet; stage B is Model 7's design on the UNet's masks."""
    from matplotlib.lines import Line2D
    from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#e6e6e6"
    B = lambda *a, **k: _sbox(fig, *a, **k)
    A = lambda p, q: _bw_arrow(fig, p, q, lw=1.3)
    line = lambda xs, ys, **k: fig.lines.append(Line2D(xs, ys, transform=fig.transFigure, color="black", lw=k.pop("lw", 1.3), **k))
    lab = lambda x, y, t, **k: fig.text(x, y, t, ha=k.pop("ha", "center"), va=k.pop("va", "bottom"), fontsize=k.pop("fs", 9), style="italic", color="black", **k)
    darrow = lambda p, q: fig.patches.append(FancyArrowPatch(p, q, transform=fig.transFigure, arrowstyle="-|>", mutation_scale=12, color="black", lw=1.3, shrinkA=0, shrinkB=1))
    fig.text(0.5, 0.955, "Model 9: Model 7 with SAM 3 replaced by a small mask network", ha="center", va="center", fontsize=25, weight="bold", color="black")
    fig.text(0.5, 0.905, "Stage A: a 4.9 M UNet learns to reproduce SAM 3's six mask maps from RGB (SAM 3 is the teacher; no labels). Stage B: Model 7's design on the UNet's masks:\n"
             "frozen Base-RGB + predicted masks → fusion head trained on NLCD (L1) → one decision per object. Deployed: RGB only, no SAM 3. Results on the next slide.",
             ha="center", va="center", fontsize=11.5, color=MUTED, linespacing=1.25)
    # ------------------------------------------------------------- A  mask student
    fig.text(0.015, 0.855, "A   Mask student (offline, no labels)", ha="left", va="center", fontsize=13, weight="bold", color="black")
    B(0.015, 0.66, 0.05, 0.16, "Input", "RGB, 1 m", fill=LIGHT, tfs=11.5)
    B(0.10, 0.77, 0.10, 0.06, "SAM 3", "840 M, frozen"); B(0.10, 0.66, 0.10, 0.06, "Mask UNet", "4.9 M, trained", dashed=True)
    A((0.065, 0.80), (0.10, 0.80)); A((0.065, 0.69), (0.10, 0.69))
    B(0.24, 0.77, 0.095, 0.06, "6 mask maps", "targets, 1 m", fill=LIGHT); B(0.24, 0.66, 0.095, 0.06, "6 predicted maps", "1 m", fill=LIGHT)
    A((0.20, 0.80), (0.24, 0.80)); A((0.20, 0.69), (0.24, 0.69))
    B(0.375, 0.695, 0.10, 0.10, "Loss", "per-pixel BCE"); A((0.335, 0.80), (0.375, 0.77)); A((0.335, 0.69), (0.375, 0.72))
    line([0.425, 0.425, 0.15], [0.695, 0.64, 0.64], ls=(0, (4, 3))); darrow((0.15, 0.64), (0.15, 0.66)); lab(0.29, 0.633, "gradient → UNet only", va="top")
    fig.text(0.51, 0.82, "Mask UNet: 4 levels (32, 64, 128, 256 channels), 4.9 M parameters.\n"
             "Targets: SAM 3's object-mask maps for the six prompts (building, road,\nparking lot, runway, water, river) on all 582 training tiles,\n"
             "already computed for Model 8. SAM 3 is a model, not a label:\nno NLCD and no CCLC are used in stage A.", ha="left", va="top", fontsize=10.5, color=MUTED, linespacing=1.3)
    # ------------------------------------------------------------- B  Model 9
    fig.text(0.015, 0.585, "B   Model 9: Model 7 with the mask student (deployed)", ha="left", va="center", fontsize=13, weight="bold", color="black")
    yP, yM, yC = 0.505, 0.415, 0.46
    B(0.015, 0.385, 0.05, 0.15, "Input", "RGB, 1 m", fill=LIGHT, tfs=11.5)
    B(0.10, 0.475, 0.10, 0.06, "Base-RGB", "145.4 M, frozen"); B(0.10, 0.385, 0.10, 0.06, "Mask UNet", "4.9 M, frozen")
    A((0.065, yP), (0.10, yP)); A((0.065, yM), (0.10, yM))
    B(0.25, 0.43, 0.06, 0.06, "Concat", "17 + 6 = 23"); A((0.20, yP), (0.25, 0.475)); A((0.20, yM), (0.25, 0.445))
    lab(0.225, 0.495, "17 probs", fs=8.5); lab(0.225, 0.405, "6 masks", va="top", fs=8.5)
    B(0.35, 0.43, 0.10, 0.06, "Fusion head", "0.1 M, trained", dashed=True); A((0.31, yC), (0.35, yC))
    B(0.49, 0.43, 0.115, 0.06, "Object pooling", "objects from UNet masks"); A((0.45, yC), (0.49, yC))
    B(0.645, 0.43, 0.08, 0.06, "Fused logits", "17 classes, 1 m", fill=LIGHT); A((0.605, yC), (0.645, yC))
    B(0.765, 0.43, 0.10, 0.06, "argmax", "→ Table S1 → 4 classes"); A((0.725, yC), (0.765, yC))
    line([0.15, 0.15, 0.5475], [0.385, 0.365, 0.365]); A((0.5475, 0.365), (0.5475, 0.43)); lab(0.462, 0.358, "objects from the UNet masks (≥ 0.5)", va="top", fs=8.5)
    # training (NLCD) and scoring (CCLC)
    B(0.21, 0.24, 0.09, 0.06, "NLCD label", "30 m, training", fill=LIGHT); B(0.35, 0.24, 0.10, 0.06, "Training (L1)", "per-pixel CE")
    A((0.30, 0.27), (0.35, 0.27))
    line([0.685, 0.685, 0.43], [0.43, 0.335, 0.335]); A((0.43, 0.335), (0.43, 0.30))
    line([0.37, 0.37], [0.30, 0.40], ls=(0, (4, 3))); darrow((0.37, 0.40), (0.37, 0.43)); lab(0.363, 0.332, "gradient → head only", ha="right", va="center", fs=8.5)
    B(0.765, 0.24, 0.10, 0.06, "Score", "mIoU"); A((0.815, 0.43), (0.815, 0.30))
    B(0.895, 0.24, 0.09, 0.06, "CCLC 1 m", "scoring only", fill=LIGHT); A((0.895, 0.27), (0.865, 0.27))
    # ------------------------------------------------------------- parameters, legend, note
    _bw_box(fig, 0.82, 0.555, 0.165, 0.305, "", None, lw=1.2)
    fig.text(0.9025, 0.84, "Parameters at inference", ha="center", va="center", fontsize=11.5, weight="bold", color="black")
    rows = [("Model 7", "985.5 M", True), ("   Base-RGB + head", "145.5", False), ("   SAM 3", "840.0", False),
            ("Model 9", "150.4 M", True), ("   Base-RGB + head", "145.5", False), ("   mask UNet", "4.9", False)]
    for i, (k, v, bold) in enumerate(rows):
        y = 0.81 - i * 0.03 - (0.012 if i >= 3 else 0)
        fig.text(0.83, y, k, ha="left", va="center", fontsize=10.5, weight="bold" if bold else "normal", color="black")
        fig.text(0.975, y, v, ha="right", va="center", fontsize=10.5, weight="bold" if bold else "normal", color="black")
    fig.text(0.9025, 0.59, "6.6× smaller than Model 7\n(Model 8: 26.8 M, one network)", ha="center", va="center", fontsize=10.5, weight="bold", color="black", linespacing=1.3)
    for y, fill, dashed, t in [(0.14, LIGHT, False, "data"), (0.10, "white", False, "frozen / fixed"), (0.06, "white", True, "trained")]:
        fig.patches.append(FancyBboxPatch((0.02, y - 0.014), 0.02, 0.028, boxstyle="round,pad=0.003,rounding_size=0.006", transform=fig.transFigure,
                                          facecolor=fill, edgecolor="black", lw=1.2, ls=(0, (4, 2.5)) if dashed else "-"))
        fig.text(0.047, y, t, ha="left", va="center", fontsize=10, color="black")
    fig.text(0.17, 0.16, "Why: SAM 3 is 85 % of Model 7's parameters and most of its run time. A small UNet that copies its masks keeps Model 7's mechanism (masks + one decision per object)\n"
             "with the same Base and head. Risk: shadowed water and thin roads are where the copy is weakest; stage A's held-out mask IoU vs SAM 3 will show it before stage B.",
             ha="left", va="top", fontsize=10.5, color=MUTED, linespacing=1.35)
    pdf.savefig(fig); plt.close(fig)

def model10_slide(pdf):
    """Proposal, black and white, one compact slide: Model 10 'MapOT'. Label super-resolution by optimal transport: the coarse
    map gives class masses per block, the image gives segments and costs, Sinkhorn assigns labels; iterated self-labelling.
    At inference the plain RGB network alone."""
    from matplotlib.lines import Line2D
    from matplotlib.patches import FancyArrowPatch, FancyBboxPatch, Rectangle
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#e6e6e6"
    B = lambda *a, **k: _sbox(fig, *a, **k)
    A = lambda p, q: _bw_arrow(fig, p, q, lw=1.3)
    line = lambda xs, ys, **k: fig.lines.append(Line2D(xs, ys, transform=fig.transFigure, color="black", lw=k.pop("lw", 1.3), **k))
    lab = lambda x, y, t, **k: fig.text(x, y, t, ha=k.pop("ha", "center"), va=k.pop("va", "bottom"), fontsize=k.pop("fs", 9), style="italic", color="black", **k)
    darrow = lambda p, q: fig.patches.append(FancyArrowPatch(p, q, transform=fig.transFigure, arrowstyle="-|>", mutation_scale=12, color="black", lw=1.3,
                                                              ls=(0, (4, 3)), shrinkA=0, shrinkB=1))
    fig.text(0.5, 0.955, "Model 10, MapOT: label super-resolution by optimal transport", ha="center", va="center", fontsize=25, weight="bold", color="black")
    fig.text(0.5, 0.91, "The coarse map says how much of each class a block contains; the image says where it looks like; optimal transport decides which pixels get which label.\n"
             "Training: labels are re-solved every epoch from the map and the current model (self-labelling). Inference: the plain RGB network alone. Results on the next slide.",
             ha="center", va="center", fontsize=11.5, color=MUTED, linespacing=1.25)
    # ------------------------------------------------------------------ 1 training loop
    fig.text(0.015, 0.855, "1   Training: one epoch of the loop", ha="left", va="center", fontsize=13, weight="bold", color="black")
    B(0.015, 0.50, 0.05, 0.32, "Input", "NAIP\nRGB\n1 m", fill=LIGHT, tfs=11.5)
    B(0.10, 0.75, 0.13, 0.06, "Segments", "SAM 3 objects + superpixels"); lab(0.165, 0.818, "label-free, image only", fs=8.5)
    B(0.10, 0.655, 0.13, 0.06, "Paraformer-RGB  θ", "145 M, trained", dashed=True)
    B(0.10, 0.52, 0.13, 0.06, "NLCD block", "30 m class", fill=LIGHT)
    A((0.065, 0.78), (0.10, 0.78)); A((0.065, 0.685), (0.10, 0.685))
    B(0.28, 0.655, 0.12, 0.06, "Cost  C(s, k)", "−log p_θ(k | segment s)"); A((0.23, 0.685), (0.28, 0.685))
    line([0.23, 0.255, 0.255], [0.78, 0.78, 0.715]); A((0.255, 0.715), (0.28, 0.70)); lab(0.26, 0.787, "mean per segment", ha="left", fs=8.5)
    B(0.28, 0.52, 0.12, 0.06, "Class masses  m(k)", "from the map's definitions"); A((0.23, 0.55), (0.28, 0.55))
    B(0.445, 0.555, 0.14, 0.13, "Optimal transport", "\nSinkhorn, per block\nrows = segments (area)\ncols = classes (m(k))\nmin Σ P · C", tfs=12, bfs=9)
    A((0.40, 0.685), (0.445, 0.65)); A((0.40, 0.55), (0.445, 0.59))
    B(0.63, 0.585, 0.11, 0.07, "Pseudo-labels", "label(s) = argmax_k P(s, k)\n1 m, whole chip", fill=LIGHT, tfs=11.5, bfs=8.5); A((0.585, 0.62), (0.63, 0.62))
    B(0.785, 0.585, 0.08, 0.07, "CE loss", "update θ"); A((0.74, 0.62), (0.785, 0.62))
    line([0.825, 0.825, 0.083, 0.083], [0.585, 0.47, 0.47, 0.663], ls=(0, (4, 3))); darrow((0.083, 0.663), (0.10, 0.663))
    lab(0.50, 0.463, "gradient → θ;  next epoch the labels are re-solved with the new θ", va="top", fs=9)
    # masses: the small definitions table
    fig.text(0.63, 0.80, "Class masses from NLCD's own definitions", ha="left", va="center", fontsize=10.5, weight="bold", color="black")
    for i, (a, b) in enumerate([("developed, open space", "built-up 10 %, rest vegetation"), ("developed, low", "built-up 35 %"), ("developed, medium", "built-up 65 %"),
                                 ("developed, high", "built-up 90 %"), ("forest / crops / water", "that class ≥ 50 % (lower bound)")]):
        fig.text(0.63, 0.775 - i * 0.022, a, ha="left", va="center", fontsize=9, color="black"); fig.text(0.985, 0.775 - i * 0.022, b, ha="right", va="center", fontsize=9, color=MUTED)
    # ------------------------------------------------------------------ 2 worked block
    fig.text(0.015, 0.40, "2   One block, solved", ha="left", va="center", fontsize=13, weight="bold", color="black")
    ax = fig.add_axes([0.03, 0.115, 0.16, 0.255]); ax.set_xlim(0, 6); ax.set_ylim(0, 6); ax.set_xticks([]); ax.set_yticks([]); ax.set_aspect("equal")
    roofs = {(0, 0), (0, 1), (1, 0), (1, 1), (3, 4), (3, 5), (4, 4), (4, 5)}; road = {(2, j) for j in range(6)}
    for i in range(6):
        for j in range(6):
            built = (i, j) in roofs or (i, j) in road
            ax.add_patch(Rectangle((j, 5 - i), 1, 1, facecolor="#8c8c8c" if built else "white", edgecolor="black", lw=0.8, hatch="////" if built else None))
    fig.text(0.11, 0.098, "NLCD: developed, low intensity (35 % built-up)", ha="center", va="center", fontsize=9.5, color="black")
    fig.text(0.21, 0.335, "12 segments, 900 px: 2 roofs, 1 road, 9 lawn / tree superpixels.\n"
             "Mass for built-up = 0.35 × 900 = 315 px. The transport fills built-up with\n"
             "the cheapest segments first (lowest −log p for built-up): the road and the\n"
             "two roofs, 320 px, then stops. Everything else is assigned by cost to tree\n"
             "canopy or low vegetation. Hatched = built-up in the solved plan.\n"
             "A model that lowers built-up everywhere gains nothing: the masses are fixed,\n"
             "so only the ranking of segments matters. That is the 'which pixels' decision.",
             ha="left", va="top", fontsize=10, color="black", linespacing=1.35)
    # ------------------------------------------------------------------ 3 inference and notes
    fig.text(0.63, 0.40, "3   Inference (deployed)", ha="left", va="center", fontsize=13, weight="bold", color="black")
    B(0.63, 0.31, 0.07, 0.055, "Input", "RGB, 1 m", fill=LIGHT, tfs=10.5, bfs=9)
    B(0.735, 0.31, 0.12, 0.055, "Paraformer-RGB  θ", "one pass", tfs=10.5, bfs=9); A((0.70, 0.3375), (0.735, 0.3375))
    B(0.89, 0.31, 0.095, 0.055, "4-class map", "1 m", fill=LIGHT, tfs=10.5, bfs=9); A((0.855, 0.3375), (0.89, 0.3375))
    fig.text(0.63, 0.275, "No SAM 3, no superpixels, no map and no transport at test time; the same 145 M\n"
             "network as the Base (or the 26.8 M Paraformer-S), RGB only.", ha="left", va="top", fontsize=9.5, color=MUTED, linespacing=1.3)
    fig.text(0.63, 0.205, "Why it is new: Sinkhorn self-labelling exists with fixed, uniform marginals; here the\n"
             "marginals come from a coarse map and its published class definitions, the transport\n"
             "units are foundation-model objects, and the task is label super-resolution.\n"
             "Why it should work: per-pixel CE copies the block, mean-share losses scale, rule\n"
             "overlays rank by hand; MapOT ranks and learns, with nothing chosen on CCLC.\n"
             "Soft version: unbalanced transport lets a block's mass sit anywhere in its range.",
             ha="left", va="top", fontsize=9.5, color=MUTED, linespacing=1.3)
    for y, fill, dashed, t in [(0.065, LIGHT, False, "data"), (0.035, "white", True, "trained")]:
        fig.patches.append(FancyBboxPatch((0.21, y - 0.012), 0.018, 0.024, boxstyle="round,pad=0.003,rounding_size=0.006", transform=fig.transFigure,
                                          facecolor=fill, edgecolor="black", lw=1.2, ls=(0, (4, 2.5)) if dashed else "-"))
        fig.text(0.234, y, t, ha="left", va="center", fontsize=9.5, color="black")
    fig.text(0.30, 0.05, "solid white = fixed computation (segments, costs, masses, transport)", ha="left", va="center", fontsize=9.5, color="black")
    pdf.savefig(fig); plt.close(fig)

def sam3_plan_slide(pdf):
    """The simplest SAM 3 plan: a post-processing overlay on the trained Paraformer. Black and white."""
    fig = plt.figure(figsize=(16, 9)); LIGHT = "#efefef"
    fig.text(0.5, 0.95, "Next step: SAM 3 as a post-processing step", ha="center", va="center", fontsize=26, weight="bold", color="black")
    fig.text(0.5, 0.905, "No retraining. Paraformer keeps the vegetation classes; SAM 3 redraws the two weak classes, built-up and water.",
             ha="center", va="center", fontsize=14, color=MUTED)
    _bw_box(fig, 0.03, 0.34, 0.14, 0.22, "Test tile", "NAIP image\n1 m, RGB + NIR", fill=LIGHT)
    _bw_box(fig, 0.25, 0.53, 0.24, 0.19, "Paraformer (trained)", "best checkpoint, as before\n4-class map:\nbuilt-up, tree canopy, low vegetation, water")
    _bw_box(fig, 0.25, 0.18, 0.24, 0.19, "SAM 3 (frozen, no training)", "text prompts: 'building', 'road', 'water'\nreturns object masks\nwith sharp 1 m edges", dashed=True)
    _bw_box(fig, 0.57, 0.34, 0.20, 0.22, "Overlay rule", "SAM building or road  ->  built-up\nSAM water  ->  water\neverywhere else  ->  keep Paraformer")
    _bw_box(fig, 0.85, 0.34, 0.12, 0.22, "Final 1 m map", "scored against CCLC\n(Table S1), test set\nscored once", fill=LIGHT)
    _bw_arrow(fig, (0.17, 0.48), (0.25, 0.62)); _bw_arrow(fig, (0.17, 0.42), (0.25, 0.28))
    _bw_arrow(fig, (0.49, 0.62), (0.57, 0.48)); _bw_arrow(fig, (0.49, 0.28), (0.57, 0.42)); _bw_arrow(fig, (0.77, 0.45), (0.85, 0.45))
    fig.text(0.03, 0.035, "Reported as a separate row 'Paraformer + SAM 3', because SAM 3 brings knowledge from outside the dataset; the reproduction rows stay as they are. "
             "If it works, step two is to use the same masks during training instead of after it.", fontsize=12, color=MUTED, va="center")
    pdf.savefig(fig); plt.close(fig)

SAM3_DIR = os.path.join("Paraformer_hr_landcover", "runs", "sam3", "test")
VAL_CSV = os.path.join(RUNS_DIR, "val_results_tableS1.csv")              # written by sam3_select_base.py
BASE_JSON = os.path.join(RUNS_DIR, "sam3", "base_choice.json")

def sam3_base_slide(pdf, val_csv=None, base_json=None):
    """Step 1 of the SAM 3 pipeline: the base checkpoint is the one with the best val average (sam3_select_base.py).
    Left: val average of every saved checkpoint (used for the choice). Right: the same checkpoints on test (reference only)."""
    import json
    import pandas as pd
    vf, bf = val_csv or VAL_CSV, base_json or BASE_JSON
    if not (os.path.exists(vf) and os.path.exists(bf)): return 0
    df = pd.read_csv(vf); base = json.load(open(bf))
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.955, "Step 1: the base model is chosen on the val tiles", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    handles = [plt.Line2D([], [], color=col, lw=2.5, marker="o", ms=7, mec="white") for _, _, _, col in RUNS]
    handles.append(plt.Line2D([], [], ls="", marker="o", ms=15, mfc="none", mec=INK, mew=2))
    fig.legend(handles, [lab for lab, *_ in RUNS] + ["chosen base model"], loc="upper center", bbox_to_anchor=(0.5, 0.915), ncol=4,
               frameon=False, fontsize=14, labelcolor=INK)
    xmax = int(df.epoch.max())
    sel = df[(df.run == base["run"]) & (df.epoch == base["epoch"])]
    for i, (c, title) in enumerate([("val_avg_mIoU", "Val: 30 tiles, used for the choice"),
                                    ("test_avg_mIoU", "Test: 120 tiles, for reference only (not used)")]):
        ax = fig.add_axes([0.07 + i * 0.47, 0.22, 0.41, 0.56])
        for lab, short, run, col in RUNS:
            d = df[df.run == run].dropna(subset=[c]).sort_values("epoch")
            if not d.empty: ax.plot(d.epoch, d[c], "-o", color=col, lw=1.8, ms=7, mec="white", mew=1.3, zorder=3)
        if len(sel) and pd.notna(sel[c].iloc[0]):
            v = sel[c].iloc[0]
            ax.plot([base["epoch"]], [v], "o", ms=18, mfc="none", mec=INK, mew=2, zorder=4)
            ax.annotate(f"{v:.1f}", (base["epoch"], v), xytext=(0, 15), textcoords="offset points", ha="center", fontsize=14,
                        color=INK, weight="bold")
        if i == 1:
            ax.axhline(PAPER[0][1][-1], color=MUTED, ls=(0, (4, 3)), lw=1.3, zorder=1)
            ax.text(-1, PAPER[0][1][-1] + 0.4, f"Paper (Paraformer): {PAPER[0][1][-1]:.1f}", fontsize=12, color=MUTED, va="bottom")
        lo, hi = df[c].min(), df[c].max() if i == 0 else max(df[c].max(), PAPER[0][1][-1])
        ax.set_ylim(lo - 3, hi + 4); _style(ax, xmax); ax.set_xlim(-3, xmax + 4)
        ax.set_title(title, fontsize=16, color=INK, pad=8)
        ax.set_xlabel("Training epoch of the checkpoint", fontsize=14, color=MUTED)
        if i == 0: ax.set_ylabel("Average mIoU over the six states (%)", fontsize=14, color=MUTED)
    both = df.dropna(subset=["val_avg_mIoU", "test_avg_mIoU"])
    t = sel.test_avg_mIoU.iloc[0] if len(sel) else float("nan")
    lab = {run: short for _, short, run, _ in RUNS}
    note, agree = "", ""
    if len(both) > 2:
        oracle = both.loc[both.test_avg_mIoU.idxmax()]
        note = (" It is also the best of them on test." if (oracle.run, int(oracle.epoch)) == (base["run"], base["epoch"]) else
                f" For reference, the best checkpoint on test is {lab.get(oracle.run, oracle.run)} epoch {int(oracle.epoch)} ({oracle.test_avg_mIoU:.1f}).")
        agree = f" Val and test rank the checkpoints with Spearman correlation {both.val_avg_mIoU.rank().corr(both.test_avg_mIoU.rank()):.2f}."
    fig.text(0.07, 0.115, f"Chosen: {lab.get(base['run'], base['model'])} epoch {base['epoch']} (val {base['val_avg_mIoU']:.1f}, test {t:.1f})." + note,
             fontsize=14, color=INK, va="center")
    fig.text(0.07, 0.05, f"Each point is one saved checkpoint (epochs 0, 10, ..., 90, 99 of each run; {len(df)} in all), scored with the paper's Table S1 mapping."
             + agree + "\nVal has only 5 tiles per state, so its scores are noisier than test "
             "(20 per state). The val CCLC labels pick the checkpoint and the SAM 3 settings; training never sees CCLC.",
             fontsize=12, color=MUTED, va="center")
    pdf.savefig(fig); plt.close(fig)
    return 1

def sam3_settings_slide(pdf, R):
    """The val-chosen SAM 3 settings as a black-and-white flow diagram: Paraformer map -> water overlay -> built-up overlay -> final map."""
    base, ch = R["base"], R["choice"]; LIGHT = "#efefef"
    short = {run: s for _, s, run, _ in RUNS}.get(base["run"], base["model"])
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.95, "The SAM 3 settings chosen on val, as a picture", ha="center", va="center", fontsize=26, weight="bold", color="black")
    fig.text(0.5, 0.905, "Applied in this order to every tile. Chosen on the 30 val tiles; the 120 test tiles were then scored once.",
             ha="center", va="center", fontsize=14, color=MUTED)
    zoom = {1: "zoom 1x", 2: "zoom 2x", 12: "zoom 1x and 2x"}
    def sam_body(k):
        return (f"prompts: {', '.join(chr(39) + p + chr(39) for p in k['prompts'][:2])}" +
                (f",\n{', '.join(chr(39) + p + chr(39) for p in k['prompts'][2:])}" if len(k["prompts"]) > 2 else "") +
                f"\n{'object masks' if k['kind'] == 'inst' else 'per-pixel map'}, {zoom[k['scale']]}\nkeep pixels with confidence >= {k['thr10'] / 10:.1f}")
    rule = {"add": "rule 'add':\ninside SAM's {c} mask  ->  {c}\neverywhere else: keep Paraformer",
            "trim": "rule 'trim':\ninside SAM's {c} mask  ->  {c}\nParaformer's {c} outside the mask\n->  its second-choice class"}
    X = {"base": (0.03, 0.17), "water": (0.27, 0.22), "builtup": (0.56, 0.22), "final": (0.85, 0.12)}
    Y, H = 0.47, 0.25
    _bw_box(fig, *X["base"][:1], Y, X["base"][1], H, "Paraformer map",
            f"base model:\n{short}, epoch {base['epoch']}\n4 classes per pixel,\nplus its second choice", fill=LIGHT)
    for c, name, label in (("water", "1. Water overlay", "water"), ("builtup", "2. Built-up overlay", "built-up")):
        x, w = X[c]; k = ch.get(c)
        if k:
            _bw_box(fig, x, Y, w, H, name, rule[k["rule"]].format(c=label))
            _bw_box(fig, x, 0.165, w, 0.22, f"SAM 3 ({label})", sam_body(k), dashed=True)
            _bw_arrow(fig, (x + w / 2, 0.385), (x + w / 2, Y))
        else:
            _bw_box(fig, x, Y, w, H, name, "off: SAM 3 did not help on val,\nParaformer kept")
    _bw_box(fig, X["final"][0], Y, X["final"][1], H, "Final map", "1 m, 4 classes\nscored against\nCCLC (Table S1)", fill=LIGHT)
    mid = Y + H / 2
    for a, b in (("base", "water"), ("water", "builtup"), ("builtup", "final")):
        _bw_arrow(fig, (X[a][0] + X[a][1], mid), (X[b][0], mid))
    # val average after each stage, and the test result at the end
    vals = [("base", ch["val_avg_mIoU_base"], None), ("water", ch["val_avg_mIoU_after_water"], ch["val_avg_mIoU_base"]),
            ("builtup", ch["val_avg_mIoU_final"], ch["val_avg_mIoU_after_water"])]
    for k, v, prev in vals:
        x, w = X[k]
        txt = f"val {v:.1f}" + ("" if prev is None else f"  ({v - prev:+.1f})".replace("-", "−"))
        fig.text(x + w / 2, Y + H + 0.035, txt, ha="center", va="center", fontsize=15, weight="bold", color="black")
    rb, rf = R["paraformer"]["mean_over_states_mIoU"], R["paraformer_sam3"]["mean_over_states_mIoU"]
    x, w = X["final"]
    fig.text(x + w / 2, Y + H + 0.035, f"test {rb:.1f} -> {rf:.1f}", ha="center", va="center", fontsize=15, weight="bold", color="black")
    fig.text(0.03, Y + H + 0.085, "Average mIoU over the six states after each step:", fontsize=13, color=MUTED, va="center")
    fig.text(0.03, 0.065, "Object masks: SAM 3 returns one mask per object found for the prompt, each with a confidence score; masks below the threshold are dropped. "
             "Zoom 1x: the tile is cut into\n1008 px windows (SAM 3's input size). Zoom 2x: 504 px windows enlarged to 1008 px, so small buildings and roads get twice the pixels. "
             "Water goes first, then built-up,\nso a pixel both masks claim ends up built-up. Second choice = the base model's next most likely of the four classes at that pixel.",
             fontsize=12, color=MUTED, va="center", linespacing=1.4)
    pdf.savefig(fig); plt.close(fig)
    return 1

def sam3_closeup_slides(pdf, sam3_dir=None):
    """Close-up crops of SAM 3 alone vs CCLC (written by Paraformer_hr_landcover/sam3_closeups.py), two states per slide."""
    import glob
    from matplotlib.patches import Patch
    d = os.path.join(sam3_dir or SAM3_DIR, "closeups")
    order = ["de", "ny", "md", "pa", "va", "wv"]
    figs = sorted(glob.glob(os.path.join(d, "*.png")), key=lambda p: order.index(os.path.basename(p)[:2]) if os.path.basename(p)[:2] in order else 9)
    n = 0
    for i in range(0, len(figs), 2):
        fig = plt.figure(figsize=(16, 9))
        fig.text(0.5, 0.965, "Close look: SAM 3 alone against the CCLC ground truth (test tiles, no Paraformer)", ha="center", va="center",
                 fontsize=20, weight="bold", color=INK)
        fig.text(0.5, 0.928, "Val-chosen prompts, zoom and thresholds. Same tile per state as before; the 600 m crop is the window with the most "
                 "CCLC built-up and water, so there is something to compare.", ha="center", va="center", fontsize=12, color=MUTED)
        pair = figs[i:i + 2]
        for j, p in enumerate(pair):
            ax = fig.add_axes([0.01, 0.50 - j * 0.41 if len(pair) == 2 else 0.30, 0.98, 0.40]); ax.axis("off")
            ax.imshow(Image.open(p).convert("RGB"))
        fig.legend([Patch(color="#9c9c9c"), Patch(color="#00c5ff"), Patch(facecolor="white", edgecolor="#999"), Patch(color="#f2d4d4"),
                    Patch(color="#4d4d4d"), Patch(color="#eb6834"), Patch(color="#2a78d6")],
                   ["Built-up", "Water", "Other / not detected", "No data", "Agreement: same class", "SAM 3 only (false alarm)",
                    "CCLC only (missed)"], loc="lower center", bbox_to_anchor=(0.5, 0.0), ncol=7, frameon=False, fontsize=12.5, labelcolor=INK)
        pdf.savefig(fig); plt.close(fig); n += 1
    return n

POLAND_CSV = os.path.join(RUNS_DIR, "poland_zeroshot", "summary.csv")      # written by Paraformer_hr_landcover/eval_poland.py

def poland_slide(pdf):
    """Zero-shot transfer: Chesapeake-trained checkpoints scored on the paper's Poland dataset, no training on Poland."""
    import pandas as pd
    if not os.path.exists(POLAND_CSV): return 0
    df = pd.read_csv(POLAND_CSV)
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.955, "Zero-shot transfer: Chesapeake models on the Poland dataset", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    fig.text(0.5, 0.913, "No training on Poland. 280 tiles with OpenEarthMap ground truth, RGB at 0.25 / 0.5 m; classes unified with the paper's Table S2.",
             ha="center", va="center", fontsize=14, color=MUTED)
    short = {"Baseline": "Baseline ViT-B/16, epoch 40", "DINOv3 sat": "DINOv3 satellite (frozen), epoch 0", "DINOv3 web": "DINOv3 web (frozen), epoch 40"}
    def variant(r):
        return (f"{'1 m' if r.scale == '1m' else 'native'}, {'NIR from RGB' if r.nir == 'reg' else 'constant NIR'}, "
                f"{'raw colours' if r.colour == 'raw' else 'colour-matched'}")
    body = [(["Paper: Paraformer trained on Poland (ESA GLC10)", "", "55.2", "", "", "", ""], False)]
    prev = None
    for _, r in df.iterrows():
        m = next(v for k, v in short.items() if r.model.startswith(k))
        body.append(([m if m != prev else "", variant(r), f"{r.pooled_mIoU:.1f}", f"{r['IoU_built-up']:.1f}", f"{r['IoU_tree canopy']:.1f}",
                      f"{r['IoU_low vegetation']:.1f}", f"{r.IoU_water:.1f}"], True)); prev = m
    end = draw_table(fig, 0.84, ["Model (trained on Chesapeake)", "Input to the model", "mIoU", "Built-up", "Tree", "Low veg.", "Water"], body,
                     best_cols=list(range(2, 7)), col_x=[0.04, 0.33, 0.66, 0.74, 0.81, 0.885, 0.955], aligns=["left", "left"] + ["right"] * 5, row_h=0.05)
    lines = ["Why so low: (1) no NIR band in Poland, and NIR is the model's main cue for water and pavement (an RGB-based estimate explains only 44% of NIR), "
             "so water is never found;",
             "(2) darker, differently balanced colours than NAIP: on raw colours the baseline calls every pixel deciduous forest; (3) finer pixels than the 1 m it learned on.",
             "Frozen DINOv3 transfers best. The paper's 55.2 is a model trained on Poland with Poland's own 10 m labels, so it is a target, not a like-for-like comparison.",
             "mIoU = one confusion matrix over all 280 tiles. Colour-matched = each RGB band shifted and scaled per tile to the NAIP mean and std (uses no labels). "
             "1 m = tiles averaged to 1 m. Bold = best of our rows."]
    for i, t in enumerate(lines):
        fig.text(0.04, end - 0.015 - i * 0.036, t, fontsize=12.5, color=INK if i < 3 else MUTED, va="top")
    pdf.savefig(fig); plt.close(fig)
    return 1

def bands_slide(pdf):
    """Which NAIP bands each model reads, and what that means for RGB-only data such as Poland."""
    import pandas as pd
    if not (os.path.exists(POLAND_CSV) and os.path.exists(VAL_CSV)): return 0
    pol, val = pd.read_csv(POLAND_CSV), pd.read_csv(VAL_CSV)
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.955, "Which bands each model reads", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    fig.text(0.5, 0.913, "On Chesapeake every model is given all four NAIP bands: R, G, B and NIR. The two branches use them differently.",
             ha="center", va="center", fontsize=14, color=MUTED)
    spec = [("Baseline: ImageNet ViT-B/16", "vit_b16", "Baseline", "R, G, B, NIR", "the CNN's features (NIR included)", "whole model"),
            ("DINOv3 satellite, frozen", "dinov3_sat", "DINOv3 sat", "R, G, B, NIR", "R, G, B only", "CNN branch only"),
            ("DINOv3 web, frozen", "dinov3_web", "DINOv3 web", "R, G, B, NIR", "R, G, B only", "CNN branch only")]
    header = ["Model", "CNN branch reads", "Transformer branch reads", "Depends on NIR", "Chesapeake test", "Poland, best"]
    xs, al = [0.04, 0.29, 0.43, 0.63, 0.83, 0.955], ["left", "left", "left", "left", "right", "right"]
    y = 0.80
    for x, h, a in zip(xs, header, al): fig.text(x, y, h, fontsize=15, weight="bold", color=INK, va="center", ha=a)
    fig.add_artist(plt.Line2D([0.04, 0.96], [y - 0.03, y - 0.03], color=INK, lw=1.2))
    for name, bb, key, cnn, vit, dep in spec:
        y -= 0.075
        ches = val[val.backbone == bb].sort_values("val_avg_mIoU").iloc[-1]          # the val-chosen checkpoint of that run
        p = pol[pol.model.str.startswith(key)].pooled_mIoU.max()
        cells = [name, cnn, vit, dep, f"{ches.test_avg_mIoU:.1f} (epoch {int(ches.epoch)})", f"{p:.1f}"]
        for x, t, a in zip(xs, cells, al): fig.text(x, y, t, fontsize=15, color=INK, va="center", ha=a)
    fig.add_artist(plt.Line2D([0.04, 0.96], [y - 0.04, y - 0.04], color=INK, lw=1.2))
    lines = [("What this means for Poland (RGB only):", "bold", INK),
             ("Baseline: NIR enters the whole model, so a missing or estimated NIR band hurts every prediction (12 to 23 mIoU on Poland).", "normal", INK),
             ("DINOv3: its Transformer branch never used NIR, so half the model is unaffected (20 to 29 mIoU on Poland).", "normal", INK),
             ("Water: very dark in NIR, so the CNN branch most likely learned it from NIR; on RGB-only Poland water IoU stays near 0 for every model.", "normal", INK),
             ("Fix for RGB-only data: retrain with 3 input bands (image_band=3) and colour augmentation, or train on Poland itself.", "normal", INK),
             ("Chesapeake test = average of the six state mIoUs for each run's val-chosen checkpoint. Poland, best = pooled mIoU of the best input setting "
              "(see the next slides).", "normal", MUTED)]
    for i, (t, w, col) in enumerate(lines):
        fig.text(0.04, y - 0.10 - i * 0.05, t, fontsize=15 if i < 5 else 12.5, weight=w, color=col, va="center")
    pdf.savefig(fig); plt.close(fig)
    return 1

POLAND_EX = os.path.join(RUNS_DIR, "poland_zeroshot", "examples")         # written by Paraformer_hr_landcover/poland_examples.py

def poland_input_slides(pdf):
    """The three input settings explained (table + a picture of each input), then one slide per setting with an example tile."""
    import json
    import pandas as pd
    if not (os.path.exists(POLAND_CSV) and os.path.exists(os.path.join(POLAND_EX, "examples.json"))): return 0
    fit = json.load(open(os.path.join(RUNS_DIR, "poland_zeroshot", "results.json")))["nir_fit"]; c = fit["coef"]
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.955, "The input settings in the Poland table, explained", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    fig.text(0.5, 0.913, "The models were trained on NAIP: R, G, B and NIR at 1 m. Poland has only R, G, B at 0.25 / 0.5 m, so three choices had to be made.",
             ha="center", va="center", fontsize=14, color=MUTED)
    rows = [("Pixel size", "1 m", "tile averaged down to 1 m (4 x 4 or 2 x 2 pixels into one)", "the scale the models were trained on"),
            ("", "native", "the 0.25 / 0.5 m pixels as delivered", "does resampling matter?"),
            ("NIR band", "NIR from RGB", (f"NIR = {c[0]:.2f} R + {c[1]:.2f} G {'-' if c[2] < 0 else '+'} {abs(c[2]):.2f} B + {c[3]:.0f}, "
              f"fitted on Chesapeake pixels (R² {fit['r2']:.2f})").replace("-", "−"),
             "a best guess of the missing band"),
            ("", "constant NIR", f"every pixel gets {utils_nir_mean():.0f}, the NAIP average NIR", "gives the model no NIR signal at all"),
            ("Colours", "raw colours", "R, G, B as delivered", "no adaptation"),
            ("", "colour-matched", "each band shifted and scaled, per tile, to NAIP's mean and std", "removes the colour shift; no labels used")]
    xs, y = [0.04, 0.15, 0.29, 0.73], 0.845
    for x, h in zip(xs, ["Setting", "Option", "What the model receives", "Why"]):
        fig.text(x, y, h, fontsize=15, weight="bold", color=INK, va="center")
    fig.add_artist(plt.Line2D([0.04, 0.96], [y - 0.025, y - 0.025], color=INK, lw=1.2))
    for i, r in enumerate(rows):
        y -= 0.05
        if r[0] and i: fig.add_artist(plt.Line2D([0.04, 0.96], [y + 0.025, y + 0.025], color=GRID, lw=1.2))
        for x, t, w in zip(xs, r, ["bold", "normal", "normal", "normal"]):
            fig.text(x, y, t, fontsize=13.5, color=INK if x < 0.7 else MUTED, va="center", weight=w)
    fig.add_artist(plt.Line2D([0.04, 0.96], [y - 0.025, y - 0.025], color=INK, lw=1.2))
    ax = fig.add_axes([0.02, 0.03, 0.96, 0.43]); ax.axis("off")
    ax.imshow(Image.open(os.path.join(POLAND_EX, "inputs_strip.png")).convert("RGB"))
    pdf.savefig(fig); plt.close(fig); n = 1
    df = pd.read_csv(POLAND_CSV); ex = json.load(open(os.path.join(POLAND_EX, "examples.json")))
    names = [("Baseline", "Baseline"), ("DINOv3 sat", "DINOv3 satellite"), ("DINOv3 web", "DINOv3 web")]
    label = lambda s, nr, co: f"{'1 m' if s == '1m' else 'native pixels'}, {'NIR from RGB' if nr == 'reg' else 'constant NIR'}, {'raw colours' if co == 'raw' else 'colour-matched'}"
    variants = list(dict.fromkeys(zip(df.scale, df.nir, df.colour)))
    for k, (s, nr, co) in enumerate(variants, 1):
        f = os.path.join(POLAND_EX, f"variant_{s}_{nr}_{co}.png")
        if not os.path.exists(f): continue
        d = df[(df.scale == s) & (df.nir == nr) & (df.colour == co)]
        scores = ", ".join(f"{short} {d[d.model.str.startswith(key)].pooled_mIoU.iloc[0]:.1f}" for key, short in names if d.model.str.startswith(key).any())
        fig = plt.figure(figsize=(16, 9))
        fig.text(0.5, 0.962, f"Input setting {k} of {len(variants)}: {label(s, nr, co)}", ha="center", va="center", fontsize=22, weight="bold", color=INK)
        fig.text(0.5, 0.925, f"mIoU over all 280 Poland tiles: {scores}", ha="center", va="center", fontsize=15, color=INK)
        ax = fig.add_axes([0.03, 0.06, 0.94, 0.84]); ax.axis("off"); ax.imshow(Image.open(f).convert("RGB"))
        fig.text(0.5, 0.03, f"Example tile {ex['tile']} (the same in every setting): the 0.25 m tile whose ground truth has the most even mix of the four classes. "
                 "Colours: grey built-up, dark green tree canopy, light green low vegetation, blue water.", ha="center", va="center", fontsize=12, color=MUTED)
        pdf.savefig(fig); plt.close(fig); n += 1
    return n

def utils_nir_mean():
    """NAIP mean NIR used for the 'constant NIR' setting (Paraformer_hr_landcover/utils.py IMAGE_MEANS[3])."""
    m = re.search(r"IMAGE_MEANS\s*=\s*np\.array\(\[([^\]]+)\]", open(os.path.join("Paraformer_hr_landcover", "utils.py")).read())
    return float(m.group(1).split(",")[3])

def sam3_result_slides(pdf, sam3_dir=None):
    """Test results of the SAM 3 overlay (written by sam3_apply.py): a table slide, then the per-state example tiles, two per slide."""
    import json, glob
    d = sam3_dir or SAM3_DIR
    f = os.path.join(d, "results.json")
    if not os.path.exists(f): return 0
    R = json.load(open(f)); base = R["base"]; ch = R["choice"]; rb, rf = R["paraformer"], R["paraformer_sam3"]
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.955, "Step 2: SAM 3 post-processing, test results", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    fig.text(0.5, 0.91, f"Base model, chosen on val among {base.get('n_checkpoints_compared', '?')} checkpoints: {base['model']}, epoch {base['epoch']}. "
             "Same checkpoint in both rows; only the SAM 3 overlay differs.", ha="center", va="center", fontsize=14, color=MUTED)
    sgn = lambda v: f"{v:+.1f}".replace("-", "−")
    # per-state mIoU, the paper's Table 1 layout
    st_vals = lambda r: [r["per_state"][s]["mIoU"] for s in STATE_COLS] + [r["mean_over_states_mIoU"], r["pooled"]["mIoU"]]
    body = [(["Paper: Paraformer"] + [f"{v:.1f}" for v in PAPER[0][1]] + [""], False),
            (["Paraformer (our base model)"] + [f"{v:.1f}" for v in st_vals(rb)], True),
            (["Paraformer + SAM 3"] + [f"{v:.1f}" for v in st_vals(rf)], True),
            (["Change"] + [sgn(b - a) for a, b in zip(st_vals(rb), st_vals(rf))], False)]
    end = draw_table(fig, 0.835, ["mIoU (%)", "DE", "NY", "MD", "PA", "VA", "WV", "Average", "Pooled"], body, best_cols=list(range(1, 9)),
                     col_x=[0.04, 0.47, 0.53, 0.59, 0.65, 0.71, 0.77, 0.865, 0.955], aligns=["left"] + ["right"] * 8, row_h=0.055)
    # pooled IoU per class: where the change comes from
    cl_vals = lambda r: [r["pooled"]["IoU"][c] for c in ("built-up", "tree canopy", "low vegetation", "water")] + [r["pooled"]["mIoU"]]
    body = [(["Paraformer (our base model)"] + [f"{v:.1f}" for v in cl_vals(rb)], True),
            (["Paraformer + SAM 3"] + [f"{v:.1f}" for v in cl_vals(rf)], True),
            (["Change"] + [sgn(b - a) for a, b in zip(cl_vals(rb), cl_vals(rf))], False)]
    end = draw_table(fig, end - 0.03, ["IoU per class, pooled (%)", "Built-up", "Tree canopy", "Low vegetation", "Water", "mIoU"], body,
                     best_cols=list(range(1, 6)), col_x=[0.04, 0.53, 0.645, 0.79, 0.865, 0.955], aligns=["left"] + ["right"] * 5, row_h=0.055)
    def desc(c, name):
        k = ch.get(c)
        if not k: return f"{name}: off (SAM 3 did not help on val)"
        zoom = {1: "1x", 2: "2x", 12: "1x and 2x"}[k["scale"]]
        return (f"{name}: prompts {', '.join(chr(39) + p + chr(39) for p in k['prompts'])}; {'object masks' if k['kind'] == 'inst' else 'per-pixel map'}, "
                f"zoom {zoom}, confidence >= {k['thr10'] / 10:.1f}; rule '{k['rule']}'")
    lines = [("Settings chosen on the 30 val tiles; the test tiles were scored once with them:", 14, INK, "bold"),
             (desc("water", "Water"), 13, INK, "normal"), (desc("builtup", "Built-up"), 13, INK, "normal"),
             (f"Val average mIoU: base {ch['val_avg_mIoU_base']:.1f}, with the water overlay {ch['val_avg_mIoU_after_water']:.1f}, "
              f"with both overlays {ch['val_avg_mIoU_final']:.1f}.", 13, INK, "normal"),
             ("Rule 'add': SAM pixels take the class. Rule 'trim': also, the base model's pixels of that class outside SAM's mask fall back to its second choice.", 12, MUTED, "normal"),
             ("Average = mean of the six state mIoUs (the paper's Table 1 metric). Pooled = one confusion matrix over all 120 test tiles. Bold = better of our two rows.", 12, MUTED, "normal"),
             ("SAM 3 brings knowledge from outside the dataset, so the '+ SAM 3' row is not a like-for-like comparison with the paper.", 12, MUTED, "normal")]
    for i, (t, fs, col, w) in enumerate(lines):
        fig.text(0.04, end - 0.025 - i * 0.037, t, fontsize=fs, color=col, va="top", weight=w)
    pdf.savefig(fig); plt.close(fig); n = 1
    n += sam3_settings_slide(pdf, R)
    order = ["de", "ny", "md", "pa", "va", "wv"]
    figs = sorted(glob.glob(os.path.join(d, "figs", "*.png")), key=lambda p: order.index(os.path.basename(p)[:2]) if os.path.basename(p)[:2] in order else 9)
    for i in range(0, len(figs), 2):
        fig = plt.figure(figsize=(16, 9))
        fig.text(0.5, 0.965, "SAM 3 post-processing on test tiles (each state's median tile by the base model's score)", ha="center",
                 va="center", fontsize=18, weight="bold", color=INK)
        pair = figs[i:i + 2]
        for j, p in enumerate(pair):
            ax = fig.add_axes([0.02, 0.50 - j * 0.47 if len(pair) == 2 else 0.25, 0.96, 0.44]); ax.axis("off")
            ax.imshow(Image.open(p).convert("RGB"))
        pdf.savefig(fig); plt.close(fig); n += 1
    return n

def loss_slide(pdf):
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.955, "Training loss of the three Paraformer runs", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    panels = [(3, "Total loss (0.5 CE + 0.5 masked CE)"), (1, "CNN branch: cross entropy vs NLCD"),
              (2, "Transformer branch: masked cross entropy")]
    data = [(lab, col, *read_log(run)) for lab, short, run, col in RUNS]
    axes = [fig.add_axes([0.05 + i * 0.32, 0.20, 0.27, 0.57]) for i in range(3)]
    for ax, (k, title) in zip(axes, panels):
        ends = []
        for lab, col, a, _ in data:
            ax.plot(a[:, 0], a[:, k], color=col, lw=1.8, solid_capstyle="round")
            ax.plot(a[-1, 0], a[-1, k], "o", ms=6, color=col, mec="white", mew=1.5, zorder=3)   # end marker
            ends.append([a[-1, k], a[-1, 0], col])
        lo = min(a[:, k].min() for *_, a, _ in data); hi = max(a[:, k].max() for *_, a, _ in data)
        gap = 0.045 * (hi - lo); xr = max(e[1] for e in ends)
        ends.sort(key=lambda e: e[0]); placed = []
        for v, x, col in ends:                                       # push labels up until they clear the one below
            y = v if not placed else max(v, placed[-1] + gap); placed.append(y)
            ax.annotate(f"{v:.3f}", (x, v), xytext=(xr + 2.5, y), textcoords="data", va="center", fontsize=12, color=INK,
                        arrowprops=dict(arrowstyle="-", color=col, lw=0.9, shrinkA=0, shrinkB=4))
        ax.set_title(title, fontsize=16, color=INK, pad=10)
        ax.set_xlabel("Epoch", fontsize=14, color=MUTED); ax.tick_params(labelsize=12, colors=MUTED, length=0)
        ax.grid(axis="y", color=GRID, lw=0.8); ax.set_axisbelow(True)
        for sp in ("top", "right"): ax.spines[sp].set_visible(False)
        for sp in ("left", "bottom"): ax.spines[sp].set_color(GRID)
        ax.set_xlim(0, max(a[-1, 0] for *_, a, _ in data) * 1.2)
    axes[0].set_ylabel("Loss", fontsize=14, color=MUTED)
    handles = [plt.Line2D([], [], color=col, lw=2.5) for _, col, *_ in data]
    fig.legend(handles, [f"{lab}  ({int(a[-1, 0]) + 1} epochs)" for lab, _, a, _ in data], loc="upper center",
               bbox_to_anchor=(0.5, 0.915), ncol=3, frameon=False, fontsize=14, labelcolor=INK, handlelength=2.2)
    skipped = ", ".join(f"{short} {n}" for (_, short, _, _), (*_, n) in zip(RUNS, data))
    import pandas as pd
    h = pd.read_csv(os.path.join(RUNS_DIR, RUNS[0][2], "eval", "history_test.csv"))
    h = (h[h["mapping"] == "paper"] if "mapping" in h else h.iloc[0:0]).set_index("epoch")["avg_mIoU"]
    if len(h):
        lo_e, hi_e = int(h.idxmin()), int(h.idxmax())
        traj = (f"baseline test mIoU swings between {h.min():.1f} (epoch {lo_e}) and {h.max():.1f} (epoch {hi_e}) "
                f"across the {len(h)} scored checkpoints; see the next slides.")
    else:
        traj = "see the next slides."
    fig.text(0.05, 0.075, "All runs: batch 8, 224 px chips, AdamW lr 1e-4 (no plateau drop), CNN width 128, NLCD labels only. "
             "Training loss falls steadily, but test mIoU does not track it:\n" + traj, fontsize=13, color=MUTED, va="center")
    fig.text(0.05, 0.025, f"Epochs with a logged NaN loss are omitted (an all-ignored batch from one fill-value tile; weights unaffected): {skipped}.",
             fontsize=11, color=MUTED, va="center")
    pdf.savefig(fig); plt.close(fig)

PAPER = [  # Table 1 of the Paraformer paper (CVPR 2024): DE, NY, MD, PA, VA, WV, average
    ("Paper: Paraformer", [65.57, 71.43, 70.20, 60.04, 68.01, 52.62, 64.65]),
    ("Paper: L2HNet", [61.77, 68.12, 65.24, 58.52, 69.39, 55.43, 63.08]),
]
STATE_COLS = ["de", "ny", "md", "pa", "va", "wv"]
CLASS_COLS = ["built-up", "tree_canopy", "low_vegetation", "water"]

def test_rows():
    """(label, epoch, row dict) for every scored checkpoint, in run order then epoch order."""
    import pandas as pd
    out = []
    for lab, short, run, col in RUNS:
        f = os.path.join(RUNS_DIR, run, "eval", "history_test.csv")
        if os.path.exists(f):
            h = pd.read_csv(f)
            h = h[h["mapping"] == "paper"] if "mapping" in h else h.iloc[0:0]     # Table S1 rows only
            for _, r in h.sort_values("epoch").iterrows():
                out.append((lab, int(r.epoch), r))
    return out

def draw_table(fig, top, header, rows, best_cols, col_x, aligns, row_h=0.058, col_colours=None, rules_before=(), fontsize=15):
    """Plain text table. rows = [(cells, is_ours)] or [(cells, is_ours, colour)]; best_cols = columns where the best of our rows is bolded.
    col_colours: per-column text colour (None = row colour) for the header and every row; rules_before: row indices that get a thin rule above."""
    y = top
    for c, (x, h, al) in enumerate(zip(col_x, header, aligns)):
        fig.text(x, y, h, ha=al, va="center", fontsize=fontsize, weight="bold", color=(col_colours[c] if col_colours and col_colours[c] else INK))
    fig.add_artist(plt.Line2D([0.04, 0.96], [y - row_h / 2, y - row_h / 2], color=INK, lw=1.2))
    best = {}
    for c in best_cols:
        vals = [float(r[0][c]) for r in rows if r[1] and r[0][c] not in ("", None)]
        best[c] = max(vals) if vals else None
    prev_ours = None
    for i, row in enumerate(rows):
        cells, ours = row[0], row[1]; colour = row[2] if len(row) > 2 else (INK if ours else MUTED)
        y -= row_h
        if (prev_ours is not None and ours != prev_ours) or i in rules_before:          # rule between paper rows and ours, or between groups
            fig.add_artist(plt.Line2D([0.04, 0.96], [y + row_h / 2, y + row_h / 2], color=GRID, lw=1.2))
        prev_ours = ours
        for c, (x, v, al) in enumerate(zip(col_x, cells, aligns)):
            bold = ours and c in best and v not in ("", None) and float(v) == best[c]
            fig.text(x, y, v if isinstance(v, str) else f"{v:.1f}", ha=al, va="center", fontsize=fontsize,
                     weight="bold" if bold else "normal", color=(col_colours[c] if col_colours and col_colours[c] else colour))
    fig.add_artist(plt.Line2D([0.04, 0.96], [y - row_h / 2, y - row_h / 2], color=INK, lw=1.2))
    return y - row_h

def _end_labels(ax, ends, gap, x_text):
    """ends = [(value, x, colour)]; write the values at x_text, pushed apart by at least `gap`."""
    placed = []
    for v, x, col in sorted(ends):
        y = v if not placed else max(v, placed[-1] + gap); placed.append(y)
        ax.annotate(f"{v:.1f}", (x, v), xytext=(x_text, y), textcoords="data", va="center", fontsize=12, color=INK,
                    arrowprops=dict(arrowstyle="-", color=col, lw=0.9, shrinkA=0, shrinkB=4))

def _style(ax, xmax):
    ax.grid(axis="y", color=GRID, lw=0.8); ax.set_axisbelow(True)
    for sp in ("top", "right"): ax.spines[sp].set_visible(False)
    for sp in ("left", "bottom"): ax.spines[sp].set_color(GRID)
    ax.tick_params(labelsize=12, colors=MUTED, length=0)
    ticks = [t for t in (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 99) if t <= xmax]
    ax.set_xticks(ticks); ax.set_xlim(-2, max(xmax, 10) * 1.16)

def curve_slides(pdf):
    """Test mIoU against training epoch for every scored checkpoint (paper Table S1 mapping):
    one slide for the Table-1 average, one with a panel per state. Reads runs/test_results_tableS1.csv."""
    import pandas as pd
    f = os.path.join(RUNS_DIR, "test_results_tableS1.csv")
    if not os.path.exists(f): return 0
    df = pd.read_csv(f)
    if df.empty: return 0
    paper = dict(zip(["DE", "NY", "MD", "PA", "VA", "WV", "average"], PAPER[0][1]))
    xmax = int(df.epoch.max())
    handles = [plt.Line2D([], [], color=col, lw=2.5, marker="o", ms=7, mec="white") for _, _, _, col in RUNS]
    labels = [lab for lab, *_ in RUNS]
    n_done = len(df); n_all = 3 * 11
    status = "" if n_done >= n_all else f"  ·  {n_done} of {n_all} checkpoints scored so far"
    # --- slide A: the paper's Table 1 metric
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.955, "Test mIoU (%) against training epoch: average over the six states", ha="center", va="center",
             fontsize=24, weight="bold", color=INK)
    fig.legend(handles, labels, loc="upper center", bbox_to_anchor=(0.5, 0.915), ncol=3, frameon=False, fontsize=14, labelcolor=INK)
    ax = fig.add_axes([0.07, 0.15, 0.86, 0.66])
    ends = []
    for (lab, short, run, col) in RUNS:
        d = df[df.model == lab].sort_values("epoch")
        if d.empty: continue
        ax.plot(d.epoch, d.average_mIoU, "-o", color=col, lw=1.8, ms=7, mec="white", mew=1.3, zorder=3)
        ends.append((d.average_mIoU.iloc[-1], d.epoch.iloc[-1], col))
    lo = min(df.average_mIoU.min(), paper["average"]); hi = max(df.average_mIoU.max(), paper["average"])
    ax.set_ylim(lo - 4, hi + 3)
    ax.axhline(paper["average"], color=MUTED, ls=(0, (4, 3)), lw=1.3, zorder=1)
    ax.text(-1, paper["average"] + 0.5, f"Paper (Paraformer): {paper['average']:.1f}", fontsize=13, color=MUTED, va="bottom")
    _style(ax, xmax); _end_labels(ax, ends, 0.045 * (hi - lo + 7), xmax * 1.04)
    ax.set_xlabel("Training epoch of the checkpoint", fontsize=14, color=MUTED); ax.set_ylabel("Average mIoU (%)", fontsize=14, color=MUTED)
    fig.text(0.07, 0.05, "Each point is one saved checkpoint scored on all 120 test tiles with the paper's Table S1 class mapping. "
             "Average = mean of the six state mIoUs\n(the paper's Table 1 metric)." + status, fontsize=12, color=MUTED, va="center")
    pdf.savefig(fig); plt.close(fig)
    # --- slide B: one panel per state, shared y-axis
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.965, "Test mIoU (%) against training epoch, per state", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    fig.legend(handles, labels, loc="upper center", bbox_to_anchor=(0.5, 0.935), ncol=3, frameon=False, fontsize=14, labelcolor=INK)
    names = {"DE": "Delaware", "NY": "New York", "MD": "Maryland", "PA": "Pennsylvania", "VA": "Virginia", "WV": "West Virginia"}
    cols = [f"{k}_mIoU" for k in names]
    lo = min(df[cols].min().min(), min(paper[k] for k in names)); hi = max(df[cols].max().max(), max(paper[k] for k in names))
    for i, k in enumerate(names):
        ax = fig.add_axes([0.06 + (i % 3) * 0.315, 0.53 - (i // 3) * 0.43, 0.27, 0.30])
        for (lab, short, run, col) in RUNS:
            d = df[df.model == lab].sort_values("epoch")
            if not d.empty: ax.plot(d.epoch, d[f"{k}_mIoU"], "-o", color=col, lw=1.6, ms=5, mec="white", mew=1, zorder=3)
        ax.axhline(paper[k], color=MUTED, ls=(0, (4, 3)), lw=1.2, zorder=1)
        ax.text(xmax * 1.15, paper[k], f"paper {paper[k]:.1f}", fontsize=11, color=MUTED, va="center", ha="right",
                bbox=dict(facecolor="white", edgecolor="none", pad=1))
        ax.set_ylim(lo - 4, hi + 4); _style(ax, xmax); ax.set_xlim(-2, max(xmax, 10) * 1.16)
        ax.set_title(names[k], fontsize=16, color=INK, pad=6)
        if i % 3 == 0: ax.set_ylabel("mIoU (%)", fontsize=13, color=MUTED)
        if i // 3 == 1: ax.set_xlabel("Training epoch", fontsize=13, color=MUTED)
    fig.text(0.06, 0.025, "Same y-axis in every panel. Dashed line = the paper's Paraformer result for that state (Table 1). "
             "Table S1 class mapping, 20 test tiles per state." + status, fontsize=12, color=MUTED, va="center")
    pdf.savefig(fig); plt.close(fig)
    return 2

def table_selection(rows):
    """With many checkpoints per model, keep the final one and the best-on-test one (labelled) so the table fits a slide."""
    by = {}
    for lab, ep, r in rows: by.setdefault(lab, []).append((ep, r))
    if all(len(v) <= 2 for v in by.values()): return rows, False
    out = []
    for lab, items in by.items():
        final = max(items, key=lambda t: t[0]); best = max(items, key=lambda t: t[1].avg_mIoU)
        last = "final" if final[0] == 99 else "latest scored"          # epoch 99 is the last checkpoint of a 100-epoch run
        if best[0] == final[0]: out.append((f"{lab} ({last} = best)", final[0], final[1]))
        else:
            out.append((f"{lab} (best on test)", best[0], best[1])); out.append((f"{lab} ({last})", final[0], final[1]))
    return out, True

def test_state_slide(pdf, rows):
    rows, selected = table_selection(rows)
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.94, "Test set: mIoU (%) per state, 4 unified classes", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    header = ["Model", "Epoch", "DE", "NY", "MD", "PA", "VA", "WV", "Average", "Pooled", "OA"]
    col_x = [0.04, 0.45, 0.51, 0.565, 0.62, 0.675, 0.73, 0.785, 0.85, 0.905, 0.96]
    aligns = ["left"] + ["right"] * 10
    body = [([lab, ""] + [f"{v:.1f}" for v in vals] + ["", ""], False) for lab, vals in PAPER]
    for lab, ep, r in rows:
        body.append(([lab, str(ep)] + [f"{r[f'{c}_mIoU']:.1f}" for c in STATE_COLS] +
                     [f"{r.avg_mIoU:.1f}", f"{r.pooled_mIoU:.1f}", f"{r.pooled_OA:.1f}"], True))
    end = draw_table(fig, 0.82, header, body, best_cols=list(range(2, 11)), col_x=col_x, aligns=aligns)
    fig.text(0.04, end - 0.03, "Average = mean of the six state mIoUs, the paper's Table 1 metric. Pooled = one confusion matrix over all 120 test tiles. "
             "OA = overall pixel accuracy.\nOurs: trained on NLCD 30 m labels only; scored once on the CCLC 1 m ground truth of the test tiles. "
             "Bold = best of our checkpoints in that column. Paper values have no pooled or OA figures.\n"
             "Class mapping: the paper's Table S1. Epoch-5 checkpoints were scored only under our earlier barren-ignored mapping and no longer exist, so they are not shown."
             + ("\nPer model: the final (or latest scored) checkpoint and the best on the test set (an oracle choice, for reference only). "
                "Every checkpoint: the curve slides and Paraformer_hr_landcover/runs/test_results_tableS1.csv." if selected else ""),
             fontsize=13, color=MUTED, va="top")
    pdf.savefig(fig); plt.close(fig)

def test_class_slide(pdf, rows):
    rows, selected = table_selection(rows)
    fig = plt.figure(figsize=(16, 9))
    fig.text(0.5, 0.94, "Test set: IoU (%) per class, pooled over all six states", ha="center", va="center", fontsize=24, weight="bold", color=INK)
    header = ["Model", "Epoch", "Built-up", "Tree canopy", "Low vegetation", "Water", "mIoU"]
    col_x = [0.04, 0.44, 0.56, 0.68, 0.81, 0.89, 0.96]
    aligns = ["left"] + ["right"] * 6
    body = [([lab, str(ep)] + [f"{r[f'pooled_{c}']:.1f}" for c in CLASS_COLS] + [f"{r.pooled_mIoU:.1f}"], True) for lab, ep, r in rows]
    end = draw_table(fig, 0.80, header, body, best_cols=list(range(2, 7)), col_x=col_x, aligns=aligns, row_h=0.07)
    fig.text(0.04, end - 0.03, "Tree canopy and low vegetation vary little across models and epochs; built-up and water decide the ranking.\n"
             "Class mapping: the paper's Table S1 (CCLC barren -> built-up, NLCD barren land -> low vegetation). Bold = best in that column.",
             fontsize=13, color=MUTED, va="top")
    pdf.savefig(fig); plt.close(fig)

PRED_EPOCH = 50   # checkpoint whose test predictions are shown

def prediction_slides(pdf):
    """Two states per slide: NAIP | CCLC | 3 model predictions for each state's median-scoring test tile.
    Reuses Paraformer_hr_landcover/make_test_figures.py so the slides match the tile images exactly."""
    import importlib.util
    import pandas as pd
    here = os.getcwd(); os.chdir("Paraformer_hr_landcover")
    try:
        spec = importlib.util.spec_from_file_location("mtf", "make_test_figures.py")
        m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); m.EP = PRED_EPOCH
        plt.rcParams.update(FONT_RC)
        per = m.load_scores()
        if any(len(per[r]) == 0 for _, r in m.RUNS): return 0
        done = set.intersection(*[set(per[r].index) for _, r in m.RUNS])
        df = pd.read_csv("dataset/CSV_list/Chesapeake_all_test.csv")
        rows = df.set_index(df.image_fn.map(os.path.basename))
        picks = []
        for st in m.STATES:
            cand = [t for t in done if f"/{st}/" in rows.loc[t].image_fn]
            if not cand: continue
            score = {t: np.mean([per[r].loc[t].mIoU for _, r in m.RUNS]) for t in cand}
            med = np.median(list(score.values()))
            picks.append((st, min(cand, key=lambda t: abs(score[t] - med)), len(cand)))
        partial = len(done) < len(df)
        W, H, GAP_X = 0.15, 0.355, 0.18
        n = 0
        for i in range(0, len(picks), 2):
            fig = plt.figure(figsize=(16, 9))
            head = f"Test predictions, epoch {PRED_EPOCH} checkpoints: representative tile per state"
            fig.text(0.5, 0.968, head, ha="center", va="center", fontsize=22, weight="bold", color=INK)
            if partial:
                fig.text(0.5, 0.935, f"Preview: {len(done)} of {len(df)} test tiles scored by all three models so far. "
                         "Representative = the tile closest to the state's median mIoU.", ha="center", va="center", fontsize=12, color=MUTED)
            pair = picks[i:i + 2]
            for j, (st, t, nc) in enumerate(pair):
                bottom = 0.515 - j * (H + 0.07) if len(pair) == 2 else 0.30   # a lone row is centred
                axes = [fig.add_axes([0.09 + c * GAP_X, bottom, W, H]) for c in range(5)]
                m.draw_row(axes, rows.loc[t], per, fs=12)
            m.legend(fig, 0.035)
            pdf.savefig(fig); plt.close(fig); n += 1
        return n
    finally:
        os.chdir(here)

def slide(pdf, title, image=None, subtitle=None):
    fig = plt.figure(figsize=(16, 9))
    if image is None:
        fig.text(0.5, 0.58, title, ha="center", va="center", fontsize=34, weight="bold")
        if subtitle: fig.text(0.5, 0.44, subtitle, ha="center", va="center", fontsize=17, color="#444")
    else:
        fig.text(0.5, 0.955, title, ha="center", va="center", fontsize=19, weight="bold")
        ax = fig.add_axes([0.02, 0.02, 0.96, 0.89]); ax.axis("off"); ax.imshow(image)
    pdf.savefig(fig); plt.close(fig)

if __name__ == "__main__":
    figs = figures(NB); n = 1
    TMP = f"{OUT}.{os.getpid()}.tmp"                   # write to a private temp file, then swap it in atomically
    atexit.register(lambda: os.path.exists(TMP) and os.remove(TMP))
    with PdfPages(TMP) as pdf:
        slide(pdf, "Chesapeake Bay dataset: a quick look",
              subtitle="NAIP 1 m imagery  ·  NLCD 30 m labels  ·  CCLC 1 m ground truth  ·  figures from visualize_chesapeake_ny.ipynb")
        for img, caption, rows in figs:
            if rows and len(rows) > ROWS_PER_SLIDE:
                parts = split_rows(img, len(rows))
                for i, part in enumerate(parts):
                    names = ", ".join(rows[i * ROWS_PER_SLIDE:(i + 1) * ROWS_PER_SLIDE])
                    slide(pdf, f"{caption}\n{names}", part); n += 1
            else:
                slide(pdf, caption, img); n += 1
        architecture_slide(pdf); n += 1
        loss_slide(pdf); n += 1
        n += curve_slides(pdf)
        rows = test_rows()
        if rows:
            test_state_slide(pdf, rows); test_class_slide(pdf, rows); n += 2
        n += prediction_slides(pdf)
        sam3_plan_slide(pdf); n += 1          # the SAM 3 plan, then its results when they exist
        n += sam3_base_slide(pdf)
        n += sam3_result_slides(pdf)
        n += sam3_closeup_slides(pdf)
        n += poland_slide(pdf)
        n += bands_slide(pdf)
        n += poland_input_slides(pdf)
        dino_baseline_slide(pdf); n += 1      # base: the baseline, serial, as the code wires it
        n += option0_results_slide(pdf)       # base: best val / test mIoU, per class and per state
        dino_serial_slide(pdf); n += 1        # model 1: DINOv3-web in the baseline wiring
        n += option1_results_slide(pdf)       # model 1: best val / test mIoU so far, with base for reference
        dino_dual_slide(pdf); n += 1          # model 2: base + frozen DINOv3 branch, token fusion
        n += option2_results_slide(pdf)       # model 2: best val / test mIoU so far, with base and model 1 for reference
        fusion_arch_slide(pdf); n += 1        # model 3: base + SAM 3 masks, trained late fusion
        n += sam3_compare_slides(pdf)         # model 3 results: base, rule-based overlay, model 3 heads (2 slides)
        feature_fusion_slide(pdf); n += 1     # model 4: base + SAM 3 encoder features, feature-level fusion
        n += fusion_results_slide(pdf, 4)     # model 4 results (when they exist)
        model5_slide(pdf); n += 1             # model 5: base + NDVI + SAM 3 masks at 1 m, object pooling
        n += fusion_results_slide(pdf, 5)     # model 5 results
        model6_slide(pdf); n += 1             # model 6: feature-space fusion with DOFA, NDVI and SAM 3 features
        n += fusion_results_slide(pdf, 6)     # model 6 results
        model7_slide(pdf); n += 1             # model 7: model 5 on RGB only, base broken open
        n += model7_base_results_slide(pdf)   # model 7 stage 1: RGB Base checkpoints (as they are scored)
        n += fusion_results_slide(pdf, 7)     # model 7 stage 2 results (when they exist)
        model8_slide(pdf); n += 1             # model 8: model 7 distilled into a 26.8 M RGB student
        n += model8_results_slide(pdf)        # model 8 results (when they exist)
        model9_slide(pdf); n += 1             # model 9: model 7 with SAM 3 replaced by a 4.9 M mask UNet
        n += fusion_results_slide(pdf, 9)     # model 9 results (when they exist)
        model10_slide(pdf); n += 1            # model 10: MapOT, label super-resolution by optimal transport
        n += model10_results_slide(pdf)       # model 10 results (final, or the pilot until the final exists)
        n += model_compare_slide(pdf)         # all models and all SAM 3 variants, one table, last
    os.replace(TMP, OUT)
    print(f"wrote {OUT}: {n} slides from {len(figs)} figures")