File size: 82,603 Bytes
2469e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluation of whole-mapset generation by distribution matching.

Spec: reports/v10 評估設計:整組譜面的分布匹配.md. Each generated mapset (every difficulty of one song, written in one
run of the system) is treated as one more independent team of mappers for that song. Nine families of checks test,
each at the level where the property is decided, whether the system's mapsets and the human mapsets of the same
songs can be exchanged:

  F1  chart settings, per tier: distribution shape (energy distance on normal scores, Wasserstein-1 per setting)
  F2  song x tier: where the human chart falls among the system's K draws (randomized PIT)
  F3  song x tier: how much song information the draws carry (fair CRPS skill; 0 = right amounts on a random song,
      1 = another human team)
  F4  whole mapset: spread of the mapset across songs, sharing between tiers, distribution of signed tier-to-tier
      steps, density inversions between adjacent tiers
  F5  mapset x measure: rest / roll / big-note layout agreement of adjacent tiers and nesting of rests
  F6  measures of a chart: are rests in the quiet parts of the song (AUC; needs per-measure loudness)
  F7  structure of a chart: rest runs, their phase, roll length, section density contrast
  F8  song x tier: layout agreement between two draws, capped by the agreement of two independent human mapsets
  F9  novelty: share of a chart's 4-measure patterns found in one single training chart

Data format
-----------
chart       dict with 'sections' [n, >=4] (ms, ms per beat, meter, start beat, ...), 'time' (ms), 'type' (0-3 hit
            notes, 4+ roll / balloon) and 'length_beats'. Optional: 'beat' (computed from time and sections when
            missing), 'offset_ms' (added to the times to put the chart on the song's common time axis; 0 by default)
            and metadata such as 'beatmap_id', 'beatmapset_id', 'mapper', 'year'.
mapset      dict {tier: chart}, tier 0..4.
collection  {song_key: {'human': [mapset, ...], 'draws': [mapset, ...]}}. human[0] is the reference mapset: its
            tiers are the scored tiers of the song (other tiers of the draws are only counted), the timing of its
            hardest chart is the song's measure grid, and its audio is the time axis of the loudness curve. More
            human mapsets are optional (independent teams aligned with 'offset_ms'). 'draws' holds the K mapsets
            the system wrote for the song.

Every chart, human or generated, goes through the same labelling path (label_measures): notes are snapped to the
1/48-beat grid, assigned to real measures with dataset.measure_at, and a measure is active when it has a hit note,
a roll / balloon starts in it, or a roll / balloon body covers more than 10% of it (dataset.plan_active). The nine
chart settings are latent_stats.chart_settings of the resulting per-measure plan.

Zero-heavy values
-----------------
Many settings are exactly 0 for a large share of charts (no rolls, no triplets, no 1/8 notes). When at least
ZERO_HEAVY of a tier's training values are 0, a value is compared in two parts: whether it is 0, and, when it is
not, its normal score among the non-zero training values. F1 and F7 add the difference of the zero shares to the
non-zero share times the Wasserstein-1 distance of the non-zero parts, and F1's energy distance gets a 0 / 1
coordinate for each such setting. F2 breaks ties (for example a human 0 among draws that are 0) uniformly at random
(randomized PIT). F3 skips settings with fewer than F3_MIN_NONZERO non-zero training values in the tier.

Statistics
----------
Every family has one pre-chosen primary statistic and possibly more statistics; for each, larger is worse. Two
kinds:
  swap      noise floor = median of the statistic when the human / system labels are swapped at random within each
            song (all mapsets of a song exchangeable under the null); excess = statistic - floor; p = share of
            swaps at least as large.
  anchor    the statistic is already measured against a human anchor (F3: shortfall of the CRPS skill from the
            independent-human anchor; F8: draw agreement minus the human cross-mapset agreement); floor = 0;
            p = share of bootstrap replicates at or below 0.
Confidence intervals come from a song bootstrap (a song is resampled with its human mapsets and its draws); for
swap statistics each replicate subtracts its own swap floor (median of `boot_swaps` swaps with the same weights).
Anchor replicates (reference_info, one weight per pair song shared by all tiers) are drawn alongside. A statistic
passes (draft) when the upper end of the 95% CI of the pooled excess is at most its margin and no single tier (or
tier pair) has the lower end of its CI above the margin. A family passes when all its statistics pass (REPORT_ONLY
ones excepted); it does not pass when any of them fails, and it is not available when none fails but its primary
statistic cannot be computed. The gate (summary 'all_pass') passes only when every family passes and no scored
(song, tier, draw) unit lacks a valid chart (such a draw would drop out of every statistic). A family fails
when its primary p, Holm-adjusted over the families, is below alpha.

Draft margins and thresholds live in DRAFT_MARGINS and the constants below; they are frozen only after the
validation experiments of the spec (B2) pass.
"""

from __future__ import annotations

import hashlib
import pickle
import warnings
from collections import defaultdict
from pathlib import Path

import numpy as np
import torch

from .dataset import (BAR_F, DIVISORS, GAP0, GRID, SUSTAIN, _beats_at, beat_ms, measure_at, measure_span,
                      plan_active, roll_end_beats, subdiv_class)
from .gapstats import N_GAP_BINS, gap_bins
from .latent_align import best_offset, onset_f1
from .latent_stats import NAMES as SETTING_NAMES, chart_settings

# ------------------------------------------------------------------------------------------------ constants

REPO = Path(__file__).resolve().parents[2]
DEFAULT_CHARTS = REPO / "data/hfruns/runs/charts/charts_all.pkl"
DEFAULT_CATALOG = REPO / "data/catalog/taiko_beatmaps.parquet"

N_TIERS = 5
MODERN_YEAR = 2022                     # modern mapset: latest chart approved in this year or later
ERA_BANDS = ((0, 2016), (2017, 2021), (2022, 9999))
MIN_NOTES = 16                         # human charts with fewer notes are dropped (as in the design scripts)
MAX_MEASURES = 2000                    # charts spanning more measures are treated as broken
STRUCT_NAMES = ("rest_blocks_per100", "rest_block_len", "roll_len", "dens_cv")
VALUE_NAMES = tuple(SETTING_NAMES) + STRUCT_NAMES   # 9 chart settings + 4 structure values
N_SET = len(SETTING_NAMES)            # F1, F2, F3 use the 9 settings
F4_NAMES = tuple(SETTING_NAMES[:6])   # F4 uses the 6 main settings (rest, roll, triplet, eighth, big, density)
ZERO_HEAVY = 0.2                       # two-part handling when at least this share of training values is exactly 0
F3_MIN_NONZERO = 0.2                   # F3 skips (tier, setting) with fewer non-zero training values
F3_MIN_ROOM = 0.02                     # ... or with less room between the climatology and the human anchor
MIN_ANCHOR_SONGS = 30                  # fewer modern pair songs in a tier -> also use pairs within 2 years
COPY_CUT = 0.6                         # F9: a chart counts as copied when one training chart holds this share of
                                       # its distinct 4-measure patterns (draft; above every modern validation
                                       # human chart: max 0.53 in tier 0, p99 at most 0.19 per tier)
GRAM_N = 4                             # F9 pattern length in measures
GRAM_SLOTS = 12                        # F9 positions per beat
MIN_GRAMS = 8                          # F9 needs at least this many distinct patterns
RUN_BINS = 9                           # F7 rest run lengths 1..8 and 9+
MIN_SONGS = 3                          # a statistic needs at least this many songs on each side
MIN_LAYOUT = 20                        # a layout F1 (F5, F8, F8 cap) needs this many labelled measures (a + b)
MIN_OVERLAP = 16                       # a pair of charts (F8 cap and F8 draw pairs) needs this many common measures
ALIGN_MIN_F1 = 0.5                     # two teams count as lined up when their hardest charts share at least this
ALIGN_MIN_OVERLAP_MS = 30000.0         # onset F1 over a common stretch of at least this length (same-timing real
                                       # pairs never go below 0.74)
ALPHA = 0.05

TRIP_CLASSES = (DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12))
FINE_CLASS = DIVISORS.index(8)

# Draft margins: largest excess over the floor that still counts as "the same as human" (equivalence bound).
# Units: F1 energy distance and W1 in normal-score units; F2 W1 between the PIT values and the uniform; F3 skill
# shortfall (1 - skill); F4 steps / F7 W1 in normal-score units, shares and F1 / AUC / TV in their own units.
DRAFT_MARGINS = {
    "F1": {"energy": 0.02, "w1_mean": 0.05},
    "F2": {"pit_w1": 0.03},
    "F3": {"shortfall": 0.5},
    "F4": {"steps": 0.05, "inversions": 0.02, "spread": 0.10, "sharing": 0.05},
    "F5": {"rest_f1": 0.08, "roll_f1": 0.08, "big_f1": 0.08, "nesting": 0.08},   # null CI half-width ~0.05 at 395 songs
    "F6": {"auc": 0.03},
    "F7": {"run_length": 0.05, "blocks_per100": 0.10, "block_len": 0.10, "phase4": 0.05, "roll_len": 0.10,
           "dens_cv": 0.10},
    "F8": {"rest": 0.10, "rest_within_song": 0.05, "roll": 0.10, "big": 0.10},   # the rest cap alone: SD ~0.03 pooled
    "F9": {"copy_share": 0.005, "best_single": 0.05, "seen_share": 0.05},
}

# family -> (title, primary statistic, [(statistic, kind)]); kind "swap" or "anchor" (see module docstring)
FAMILIES = {
    "F1": ("chart settings per tier", "energy", [("energy", "swap"), ("w1_mean", "swap")]),
    "F2": ("human chart among the draws (PIT)", "pit_w1", [("pit_w1", "swap")]),
    "F3": ("song information (fair CRPS skill)", "shortfall", [("shortfall", "anchor")]),
    "F4": ("whole mapset: spread, sharing, steps", "steps",
           [("steps", "swap"), ("inversions", "swap"), ("spread", "swap"), ("sharing", "swap")]),
    "F5": ("adjacent-tier layout", "rest_f1",
           [("rest_f1", "swap"), ("roll_f1", "swap"), ("big_f1", "swap"), ("nesting", "swap")]),
    "F6": ("rests in quiet measures", "auc", [("auc", "swap")]),
    "F7": ("chart structure", "run_length",
           [("run_length", "swap"), ("blocks_per100", "swap"), ("block_len", "swap"), ("phase4", "swap"),
            ("roll_len", "swap"), ("dens_cv", "swap")]),
    "F8": ("draw-to-draw layout agreement", "rest",
           [("rest", "anchor"), ("rest_within_song", "swap"), ("roll", "anchor"), ("big", "anchor")]),
    "F9": ("novelty against training charts", "copy_share",
           [("copy_share", "swap"), ("best_single", "swap"), ("seen_share", "swap")]),
}
# strata of each family's vector: chart tiers or adjacent tier pairs
PAIR_FAMILIES = {"F4", "F5"}
# statistics reported but left out of the family's pass flag: the F8 roll and big caps rest on few independent
# human pairs (bootstrap SD 0.05-0.12 per tier on the real modern pairs), too wide for an equivalence margin
REPORT_ONLY = {("F8", "roll"), ("F8", "big")}


def era_band(year: int) -> int:
    """Index of the era band (<=2016, 2017-2021, 2022 and later) of an approval year."""
    for k, (lo, hi) in enumerate(ERA_BANDS):
        if lo <= year <= hi:
            return k
    return len(ERA_BANDS) - 1


# ------------------------------------------------------------------------------------------------ labelling

def _note_grid(sections, time, type_, length_beats, beat=None):
    """Notes sorted by time and snapped to the 1/48-beat grid of `sections`: (grid index, measure index, type,
    length in beats). Beats come from `beat` when given, else from the times in this timing."""
    sec = np.asarray(sections, np.float64)
    t = np.asarray(time, np.float64)
    order = np.argsort(t, kind="stable")
    ty = np.asarray(type_)[order].astype(np.int64)
    ln = np.asarray(length_beats, np.float64)[order]
    b = _beats_at(sec, t[order]) if beat is None else np.asarray(beat, np.float64)[order]
    g = np.round(b * GRID).astype(np.int64)
    return g, measure_at(sec, g / GRID), ty, ln


def label_measures(sections, time, type_, length_beats, beat=None, lo_m=None, hi_m=None) -> dict | None:
    """Per-measure labels of a chart's notes on the real measures of `sections` (the chart's own timing, or another
    chart's timing when the times have been moved into it). Measures lo_m .. hi_m - 1; by default from the first
    note's measure to the measure of the last note or roll end.

    Returns dict: lo_m, n, H [n, BAR_F] (the per-measure plan of dataset.bar_plan, vectorised), active (plan_active),
    play (hit notes), big (more than half big notes), trip (at least 30% of hits on the 1/3, 1/6, 1/12 grid), roll
    (active only through a roll / balloon), st / en (measure start / end beats), and per note: measure (relative to
    lo_m), slot (position in 1/12 beats from the measure start), type."""
    if len(time) == 0:
        return None
    sec = np.asarray(sections, np.float64)
    g, m, ty, ln = _note_grid(sec, time, type_, length_beats, beat)
    bq = g / GRID
    roll = ty >= 4
    ends = roll_end_beats(sec, bq[roll], ln[roll]) if roll.any() else np.zeros(0)
    if lo_m is None:
        lo_m = int(m.min())
    if hi_m is None:
        last = int(m.max())
        if len(ends):
            last = max(last, int(measure_at(sec, ends).max()))
        hi_m = last + 1
    n = int(hi_m - lo_m)
    if n <= 0 or n > MAX_MEASURES:
        return None
    st, en = measure_span(sec, np.arange(lo_m, hi_m))
    mlen = np.maximum(en - st, 1e-6)
    idx = m - lo_m
    ok = (idx >= 0) & (idx < n)
    hit = ty <= 3
    hk = ok & hit
    nh = np.bincount(idx[hk], minlength=n).astype(np.float64)
    div = subdiv_class(g)
    H = np.zeros((n, BAR_F), np.float32)
    H[:, 0] = nh > 0
    H[:, 1] = np.log1p(nh / mlen)
    H[:, 2] = np.bincount(idx[hk], weights=(ty[hk] >= 2).astype(float), minlength=n) / np.maximum(nh, 1)
    H[:, 3] = np.bincount(idx[ok & roll], minlength=n) > 0
    H[:, 4] = np.bincount(idx[hk], weights=np.isin(div[hk], TRIP_CLASSES).astype(float), minlength=n) / np.maximum(nh, 1)
    H[:, 5] = np.bincount(idx[hk], weights=(div[hk] >= FINE_CLASS).astype(float), minlength=n) / np.maximum(nh, 1)
    # gap histogram: gaps between consecutive hit notes, counted in the measure of the later note, normalised
    gh, mh = g[hit], idx[hit]
    if len(gh) > 1:
        gb = gap_bins(np.diff(gh) / GRID)
        later = mh[1:]
        okg = (later >= 0) & (later < n)
        G = np.zeros((n, N_GAP_BINS))
        np.add.at(G, (later[okg], gb[okg]), 1.0)
        H[:, GAP0:GAP0 + N_GAP_BINS] = G / np.maximum(G.sum(1, keepdims=True), 1)
    # roll / balloon bodies: share of each measure they cover (a start marks its measure even with zero length)
    if roll.any():
        rb = bq[roll]
        ov = np.minimum(en[None, :], ends[:, None]) - np.maximum(st[None, :], rb[:, None])
        cover = np.where(ov > 0, ov, 0.0) / mlen[None, :]
        inm = (st[None, :] <= rb[:, None]) & (rb[:, None] < en[None, :])
        cover = np.where(inm, np.maximum(cover, 1e-3), cover)
        H[:, SUSTAIN] = np.minimum(cover.sum(0), 1.0)
    play = H[:, 0] > 0.5
    active = plan_active(H)
    slot = np.round((bq - st[np.clip(idx, 0, n - 1)]) * GRAM_SLOTS).astype(np.int64)
    return {"lo_m": int(lo_m), "n": n, "H": H, "active": active, "play": play,
            "big": play & (H[:, 2] > 0.5), "trip": play & (H[:, 4] >= 0.3), "roll": active & ~play,
            "st": st, "en": en, "note_m": idx, "note_slot": slot, "note_type": ty, "note_ok": ok}


def _runs(mask: np.ndarray):
    """(start, length) arrays of the runs of True in a boolean array."""
    if not mask.any():
        return np.zeros(0, np.int64), np.zeros(0, np.int64)
    d = np.diff(np.concatenate([[0], mask.astype(np.int8), [0]]))
    s, e = np.where(d == 1)[0], np.where(d == -1)[0]
    return s, e - s


_P_MEASURE = 0x100000001B3            # multipliers of the polynomial hashes (64-bit wrap-around)
_P_GRAM = 0x9E3779B97F4A7C15


def _gram_hashes(lab: dict) -> np.ndarray:
    """Distinct 4-measure patterns of a labelled chart (rhythm and note type, positions in 1/12 beats, so tempo
    does not matter), as sorted int64 hashes. Only windows of 4 consecutive measures that all have notes count."""
    ok = lab["note_ok"]
    m, slot, ty = lab["note_m"][ok], lab["note_slot"][ok], lab["note_type"][ok]
    n = lab["n"]
    if len(m) == 0 or n < GRAM_N:
        return np.zeros(0, np.int64)
    code = (np.clip(slot, 0, 4095).astype(np.uint64) * np.uint64(16) + ty.astype(np.uint64) + np.uint64(1))
    order = np.lexsort((code, m))
    ms, cs = m[order], code[order]
    first = np.concatenate([[True], ms[1:] != ms[:-1]])
    rank = np.arange(len(ms)) - np.maximum.accumulate(np.where(first, np.arange(len(ms)), 0))
    powers = np.array([pow(_P_MEASURE, k, 1 << 64) for k in range(int(rank.max()) + 1)], np.uint64)
    h = np.zeros(n, np.uint64)
    np.add.at(h, ms, cs * powers[rank])
    has = np.bincount(ms, minlength=n) > 0
    k = n - GRAM_N + 1
    gh = np.zeros(k, np.uint64)
    okw = np.ones(k, bool)
    for i in range(GRAM_N):
        gh = gh * np.uint64(_P_GRAM) + h[i:i + k]
        okw &= has[i:i + k]
    return np.unique(gh[okw].view(np.int64))


def chart_grams(chart: dict) -> np.ndarray:
    """4-measure pattern hashes of a chart on its own timing (F9)."""
    lab = label_measures(chart["sections"], chart["time"], chart["type"], chart["length_beats"], chart.get("beat"))
    return np.zeros(0, np.int64) if lab is None else _gram_hashes(lab)


def chart_values(chart: dict) -> dict | None:
    """Per-chart values on the chart's own timing, or None when the chart has too few active or played measures.

    values      [13]: the 9 chart settings (latent_stats.chart_settings) and 4 structure values: rest runs per 100
                inside measures, mean rest-run length (measures), median roll / balloon length (beats), and the
                contrast of mean density over 8-measure sections (SD / mean).
    run_hist    [9] counts of inside rest runs of length 1..8, 9+
    phase_hist  [4] counts of rest-run starts by (start - first active measure) mod 4
    grams       distinct 4-measure pattern hashes (F9)"""
    lab = label_measures(chart["sections"], chart["time"], chart["type"], chart["length_beats"], chart.get("beat"))
    if lab is None:
        return None
    s = chart_settings(lab["H"])
    if s is None:
        return None
    act = lab["active"]
    ia = np.where(act)[0]
    inside = np.zeros(lab["n"], bool)
    inside[ia[0]: ia[-1] + 1] = True
    rest = ~act & inside
    rs, rl = _runs(rest)
    n_in = int(inside.sum())
    dens = lab["H"][inside, 1].astype(np.float64)
    k = len(dens) // 8
    secd = dens[: k * 8].reshape(k, 8).mean(1) if k >= 2 else np.array([dens.mean()])
    ty = np.asarray(chart["type"])
    rolls = np.asarray(chart["length_beats"], np.float64)[ty >= 4]
    struct = [len(rl) / max(n_in, 1) * 100.0, float(rl.mean()) if len(rl) else 0.0,
              float(np.median(rolls)) if len(rolls) else 0.0, float(secd.std() / max(secd.mean(), 1e-6))]
    return {"values": np.concatenate([s, struct]).astype(np.float64),
            "run_hist": np.bincount(np.minimum(rl, RUN_BINS) - 1, minlength=RUN_BINS)[:RUN_BINS].astype(np.float64),
            "phase_hist": np.bincount((rs - ia[0]) % 4, minlength=4).astype(np.float64),
            "grams": _gram_hashes(lab), "n_inside": n_in}


def _grid_labels(chart: dict, grid_sec: np.ndarray, grid_offset: float) -> dict | None:
    """Labels of a chart on the song's measure grid (another chart's timing): times moved by the offset difference,
    beats recomputed in the grid timing. Keeps what the layout checks need; st_ms / en_ms are on the song axis."""
    t = np.asarray(chart["time"], np.float64) + float(chart.get("offset_ms", 0.0)) - grid_offset
    lab = label_measures(grid_sec, t, chart["type"], chart["length_beats"])
    if lab is None or not lab["active"].any():
        return None
    return {"lo_m": lab["lo_m"], "n": lab["n"], "active": lab["active"], "roll": lab["roll"], "big": lab["big"],
            "st_ms": beat_ms(grid_sec, lab["st"]) + grid_offset, "en_ms": beat_ms(grid_sec, lab["en"]) + grid_offset}


def _pair_counts(a: dict, b: dict, window: str = "union") -> np.ndarray | None:
    """Layout agreement counts of two charts labelled on the same grid: [rest tp, rest a, rest b, roll tp, roll a,
    roll b, big tp, big a, big b, measures]. F1 = 2 tp / (a + b); nesting of b's rests in a's = tp / b.
    window 'union': measures from the first to the last active measure of either chart (same audio: a chart that
    starts later really rests there). 'common': from the later first active measure to the earlier last one, as in
    latent_align.compare (two mapsets may use different cuts of the song, e.g. a short version)."""
    lo = min(a["lo_m"], b["lo_m"])
    hi = max(a["lo_m"] + a["n"], b["lo_m"] + b["n"])
    n = hi - lo

    def put(lab, key):
        out = np.zeros(n, bool)
        s = lab["lo_m"] - lo
        out[s: s + lab["n"]] = lab[key]
        return out

    aa, ab = put(a, "active"), put(b, "active")
    ia, ib = np.where(aa)[0], np.where(ab)[0]
    if len(ia) == 0 or len(ib) == 0:
        return None
    lo_i, hi_i = (min(ia[0], ib[0]), max(ia[-1], ib[-1])) if window == "union" else (max(ia[0], ib[0]), min(ia[-1], ib[-1]))
    if hi_i < lo_i:
        return None
    inside = np.zeros(n, bool)
    inside[lo_i: hi_i + 1] = True
    out = []
    for xa, xb in ((~aa & inside, ~ab & inside), (put(a, "roll") & inside, put(b, "roll") & inside),
                   (put(a, "big") & inside, put(b, "big") & inside)):
        out += [(xa & xb).sum(), xa.sum(), xb.sum()]
    out.append(inside.sum())
    return np.array(out, np.float64)


# ------------------------------------------------------------------------------------------------ data helpers

def _norm_mapset(ms: dict) -> dict:
    return {int(t): c for t, c in ms.items() if c is not None}


def load_catalog(path=None) -> dict:
    """beatmap_id -> {'mapper', 'year', 'star'} from the beatmap catalog."""
    import pyarrow.parquet as pq
    cols = ["beatmap_id", "mapper_user_id", "approved_date", "star_rating"]
    out = {}
    for r in pq.read_table(Path(path or DEFAULT_CATALOG), columns=cols).to_pylist():
        out[r["beatmap_id"]] = {"mapper": r["mapper_user_id"], "year": int((r["approved_date"] or "0")[:4] or 0),
                                "star": r["star_rating"]}
    return out


def load_charts_all(path=None) -> list:
    return pickle.load(open(Path(path or DEFAULT_CHARTS), "rb"))


def _sha(x) -> int:
    return int(hashlib.sha1(str(x).encode()).hexdigest(), 16)


def _entry_mapset(entry: dict, catalog: dict | None) -> dict:
    """One chart per tier of a charts_all entry (charts with at least MIN_NOTES notes; when a tier has several
    charts, a fixed arbitrary one: the smallest sha1 of the beatmap id), with mapper and year attached."""
    by_tier = defaultdict(list)
    for c in entry["charts"]:
        if len(c["time"]) >= MIN_NOTES:
            by_tier[int(c["tier"])].append(c)
    out = {}
    for t, cs in by_tier.items():
        c = min(cs, key=lambda x: _sha(x["beatmap_id"]))
        meta = (catalog or {}).get(c["beatmap_id"], {})
        out[t] = {**c, "mapper": meta.get("mapper"), "beatmapset_id": entry["beatmapset_id"], "offset_ms": 0.0}
    return out


def _entry_year(entry: dict) -> int:
    """Approval year of the mapset's latest chart (charts_all 'year' is the approval year)."""
    return max(int(c["year"]) for c in entry["charts"])


def _mappers(ms: dict) -> set:
    return {c.get("mapper") for c in ms.values() if c.get("mapper") is not None}


def group_songs(charts_all: list) -> dict:
    """song_key -> list of charts_all entries (one entry per mapset)."""
    by = defaultdict(list)
    for s in charts_all:
        by[s.get("song_key") or str(s["beatmapset_id"])].append(s)
    return by


def _hardest_hits(ms: dict):
    c = ms[max(ms)]
    t = np.asarray(c["time"], np.float64)
    return c, t[np.asarray(c["type"]) <= 3] + float(c.get("offset_ms", 0.0))


def _same_timing(a: dict, b: dict) -> bool:
    sa, sb = np.asarray(a["sections"]), np.asarray(b["sections"])
    return sa.shape == sb.shape and np.allclose(sa[:, :2], sb[:, :2])


def _overlap_f1(ta: np.ndarray, tb: np.ndarray) -> float:
    """Onset F1 of two hit-note time lists inside their common time stretch; NaN when that stretch is shorter than
    ALIGN_MIN_OVERLAP_MS."""
    if len(ta) == 0 or len(tb) == 0:
        return np.nan
    lo, hi = max(ta.min(), tb.min()), min(ta.max(), tb.max())
    if hi - lo < ALIGN_MIN_OVERLAP_MS:
        return np.nan
    return float(onset_f1(ta[(ta >= lo) & (ta <= hi)], tb[(tb >= lo) & (tb <= hi)]))


def align_mapsets(a: dict, b: dict, align: str = "auto"):
    """Offset (ms) that moves mapset b's times (after its own offset_ms) onto mapset a's axis, and whether the pair
    is usable. 'none': same audio, offset 0, no check. 'auto': 0 when the hardest charts share their timing, else
    latent_align.best_offset on the hardest charts' hit notes; the pair is kept when the hardest charts share an
    onset F1 of at least ALIGN_MIN_F1 over a common stretch of at least 30 s (lined up) and the onset F1 of the
    whole charts is below 0.9 (higher = a likely copy, not an independent team).

    latent_align.grid_fit is not used as the alignment check: every time lies within its 20 ms tolerance of the
    1/48-beat grid at any tempo above 31 BPM, so it accepted every offset (checked on all modern pairs with offsets
    moved by 37-251 ms: grid fit 1.0 everywhere)."""
    ca, ta = _hardest_hits(a)
    cb, tb = _hardest_hits(b)
    if align == "none" or _same_timing(ca, cb):
        d = float(ca.get("offset_ms", 0.0)) - float(cb.get("offset_ms", 0.0))   # same audio: only the offsets differ
    else:
        d, _ = best_offset(ta, tb)
    if align != "none" and not _overlap_f1(ta, tb + d) >= ALIGN_MIN_F1:   # NaN (short overlap) is rejected too
        return d, False
    return d, onset_f1(ta, tb + d) < 0.9


def build_human_collection(charts_all: list, songs=None, modern_only: bool = True, catalog: dict | None = None,
                           split: str = "val", extra_mapsets: bool = True) -> dict:
    """Collection with the human mapsets of the given songs (song keys; default: every song of `split`) and empty
    draws. Modern only: mapsets whose latest chart was approved in 2022 or later. human[0] = the mapset with the
    most tiers (then the latest, then the smallest beatmapset id); other mapsets of the song that share no mapper
    with the ones already chosen and line up in time are added as independent human teams (offset_ms set).
    The test split is refused."""
    from .train import song_split
    if split == "test":
        raise ValueError("the test split is never used here")
    by = group_songs(charts_all)
    keys = sorted(k for k in by if song_split(k) == split) if songs is None else list(songs)
    out = {}
    for key in keys:
        if song_split(key) == "test":
            raise ValueError(f"song {key!r} is in the test split")
        cands = []
        for e in by.get(key, []):
            if modern_only and _entry_year(e) < MODERN_YEAR:
                continue
            ms = _entry_mapset(e, catalog)
            if ms:
                cands.append((e, ms))
        if not cands:
            continue
        cands.sort(key=lambda x: (-len(x[1]), -_entry_year(x[0]), x[0]["beatmapset_id"]))
        primary = cands[0][1]
        human, used, meta = [primary], set(_mappers(primary)), [cands[0][0]]
        if extra_mapsets:
            for e, ms in cands[1:]:
                if catalog is not None and (_mappers(ms) & used or not _mappers(ms)):
                    continue
                d, ok = align_mapsets(primary, ms)
                if not ok:
                    continue
                human.append({t: {**c, "offset_ms": float(c.get("offset_ms", 0.0)) + d} for t, c in ms.items()})
                used |= _mappers(ms)
                meta.append(e)
        out[key] = {"human": human, "draws": [],
                    "meta": {"beatmapset_ids": [e["beatmapset_id"] for e in meta],
                             "years": [_entry_year(e) for e in meta],
                             "era_band": era_band(_entry_year(meta[0]))}}
    return out


def loudness_from_rows(rows, charts_all: list, collection: dict, column: int = -2) -> dict:
    """Per-measure loudness of each song's reference audio from the planner rows (ps9 rows.pkl: per split, a list of
    (features, plan, tier, (beatmapset_id, beatmap_id, b0, song_key)); the features end with the measure's loudness
    z-score and rank within the song). Returns {song_key: {'t0', 't1', 'loud', 'beatmapset_id'}} on the song axis
    (human[0]'s own audio clock plus its offset_ms, the axis _grid_labels puts the measures on), only for songs
    whose reference mapset has rows."""
    if isinstance(rows, (str, Path)):
        rows = pickle.load(open(rows, "rb"))
    want, offset = {}, {}
    for key, e in collection.items():
        c0 = next(iter(_norm_mapset(e["human"][0]).values()))
        if c0.get("beatmapset_id") is not None:
            want[c0["beatmapset_id"]] = key
            offset[key] = float(c0.get("offset_ms", 0.0))       # one mapset, one audio: one offset for all tiers
    sections = {c["beatmap_id"]: c["sections"] for s in charts_all if s["beatmapset_id"] in want for c in s["charts"]}
    out = {}
    for split in rows:
        for feat, _, _, meta in rows[split]:
            key = want.get(meta[0])
            sec = sections.get(meta[1])
            if key is None or key in out or sec is None:
                continue
            n = len(feat)
            st, en = measure_span(sec, np.arange(n) + int(meta[2]))
            out[key] = {"t0": beat_ms(sec, st) + offset[key], "t1": beat_ms(sec, en) + offset[key],
                        "loud": np.asarray(feat[:, column], np.float64), "beatmapset_id": meta[0]}
    return out


# ------------------------------------------------------------------------------------------------ normal scores

def _ndtri(q: np.ndarray) -> np.ndarray:
    return torch.special.ndtri(torch.as_tensor(np.asarray(q, np.float64))).numpy()


def normal_scores(v: np.ndarray, ref_sorted: np.ndarray) -> np.ndarray:
    """Mid-rank of v in the sorted reference, mapped to a standard normal value (ties share their mid-rank, so a
    mass of zeros maps to one point). NaN stays NaN; an empty reference gives 0."""
    v = np.asarray(v, np.float64)
    out = np.full(v.shape, np.nan)
    ok = np.isfinite(v)
    n = len(ref_sorted)
    if n == 0:
        out[ok] = 0.0
        return out
    lo = np.searchsorted(ref_sorted, v[ok], "left")
    hi = np.searchsorted(ref_sorted, v[ok], "right")
    out[ok] = _ndtri(np.clip((lo + hi) / 2 / n, 0.5 / n, 1 - 0.5 / n))
    return out


def _zscore(V: np.ndarray, tiers: np.ndarray, ref: dict):
    """(Z, Zpos, zero): plain normal scores within tier, positive-part normal scores (against the non-zero training
    values; NaN for zeros) and the zero flags, for value columns VALUE_NAMES."""
    Z = np.full(V.shape, np.nan)
    Zp = np.full(V.shape, np.nan)
    for t in range(N_TIERS):
        r = tiers == t
        if not r.any():
            continue
        for j, name in enumerate(VALUE_NAMES):
            Z[r, j] = normal_scores(V[r, j], ref["z_ref"][t][name])
            pos = r & (V[:, j] > 0)
            Zp[pos, j] = normal_scores(V[pos, j], ref["z_ref_pos"][t][name])
    return Z, Zp, V == 0


# ------------------------------------------------------------------------------------------------ reference info

def _crps_pool(t_z: np.ndarray):
    """Sorted pool (z) with prefix sums and its half mean absolute difference 0.5 E|X - X'| (climatology)."""
    x = np.sort(t_z[np.isfinite(t_z)])
    n = len(x)
    if n == 0:
        return None
    w = 2 * np.arange(1, n + 1) - n - 1
    return {"x": x, "cs": np.concatenate([[0.0], np.cumsum(x)]), "half": float((w * x).sum() / (n * n))}


def _crps_clim(y: np.ndarray, pool: dict) -> np.ndarray:
    """Climatology CRPS of observations y against the pool: E|X - y| - 0.5 E|X - X'| (exact)."""
    x, cs = pool["x"], pool["cs"]
    n = len(x)
    out = np.full(y.shape, np.nan)
    ok = np.isfinite(y)
    k = np.searchsorted(x, y[ok], "right")
    out[ok] = (y[ok] * k - cs[k] + (cs[n] - cs[k]) - y[ok] * (n - k)) / n - pool["half"]
    return out


def build_gram_index(charts) -> dict:
    """F9 index of training charts: sorted (pattern hash, chart id) pairs."""
    hs, ids, n = [], [], 0
    for c in charts:
        g = chart_grams(c)
        if len(g):
            hs.append(g)
            ids.append(np.full(len(g), n, np.int32))
        n += 1
    if not hs:
        return {"hashes": np.zeros(0, np.int64), "ids": np.zeros(0, np.int32), "n_charts": n}
    h, i = np.concatenate(hs), np.concatenate(ids)
    o = np.argsort(h, kind="stable")
    return {"hashes": h[o], "ids": i[o], "n_charts": n}


def gram_novelty(grams: np.ndarray, index: dict):
    """(share of the chart's distinct patterns found in any training chart, largest share found in one single
    training chart); NaN when the chart has fewer than MIN_GRAMS patterns."""
    if len(grams) < MIN_GRAMS or len(index["hashes"]) == 0:
        return np.nan, np.nan
    lo = np.searchsorted(index["hashes"], grams, "left")
    hi = np.searchsorted(index["hashes"], grams, "right")
    cnt = hi - lo
    seen = float((cnt > 0).mean())
    if cnt.sum() == 0:
        return seen, 0.0
    # gather the chart ids of every match: repeat each range start and add the offsets inside the range
    starts = np.repeat(lo, cnt)
    offs = np.arange(cnt.sum()) - np.repeat(np.cumsum(cnt) - cnt, cnt)
    best = np.bincount(index["ids"][starts + offs]).max()
    return seen, float(best / len(grams))


def build_reference_from_mapsets(train_songs: dict, pairs=None, f9_charts=None, loudness=None, n_boot: int = 500,
                                 seed: int = 0, min_anchor_songs: int = MIN_ANCHOR_SONGS, align: str = "auto") -> dict:
    """Reference information for run_families.

    train_songs   {song_key: [mapset, ...]} training mapsets: normal-score maps per tier (all VALUE_NAMES), zero
                  shares, and the F3 climatology pool (anchor C) are the training charts of each tier.
    pairs         [{'song', 'a', 'b', 'tag'}] independent human mapsets of the same song (tag 'modern' or another
                  label): anchor F of F3 (0.5 * mean |z_a - z_b| per tier and setting, a song mean first) and the F8
                  cap (pooled rest / roll / big F1 of the time-aligned pair, per tier). A tier uses the 'modern'
                  pairs when they cover at least min_anchor_songs songs, else every pair.
    f9_charts     iterable of training charts for the F9 pattern index.
    loudness      {song_key: {'t0', 't1', 'loud'}} per-measure loudness on the reference audio (F6).
    Bootstrap replicates over songs (n_boot) are kept for the anchors."""
    rng = np.random.default_rng(seed)
    vals = {t: [] for t in range(N_TIERS)}
    for msets in train_songs.values():
        for ms in msets:
            for t, c in _norm_mapset(ms).items():
                rec = chart_values(c)
                if rec is not None:
                    vals[t].append(rec["values"])
    z_ref, z_ref_pos, zero_share, n_train = {}, {}, {}, {}
    for t in range(N_TIERS):
        A = np.array(vals[t]) if vals[t] else np.zeros((0, len(VALUE_NAMES)))
        n_train[t] = len(A)
        z_ref[t] = {nm: np.sort(A[:, j]) for j, nm in enumerate(VALUE_NAMES)}
        z_ref_pos[t] = {nm: np.sort(A[A[:, j] > 0, j]) for j, nm in enumerate(VALUE_NAMES)}
        zero_share[t] = {nm: float((A[:, j] == 0).mean()) if len(A) else 0.0 for j, nm in enumerate(VALUE_NAMES)}
    ref = {"value_names": VALUE_NAMES, "z_ref": z_ref, "z_ref_pos": z_ref_pos, "zero_share": zero_share,
           "n_train": n_train}

    # anchors F (F3) and the F8 cap from independent human pairs
    per = defaultdict(lambda: defaultdict(lambda: {"dz": [], "cnt": [], "tag": set()}))  # tier -> song -> data
    n_pairs_used = 0
    for p in pairs or []:
        a, b = _norm_mapset(p["a"]), _norm_mapset(p["b"])
        common = sorted(set(a) & set(b))
        if not common:
            continue
        d, aligned = align_mapsets(a, b, align)
        if not aligned:
            continue
        n_pairs_used += 1
        for t in common:
            ra, rb = chart_values(a[t]), chart_values(b[t])
            if ra is None or rb is None:
                continue
            V = np.stack([ra["values"], rb["values"]])
            Z, _, _ = _zscore(V, np.array([t, t]), ref)
            grid = np.asarray(a[t]["sections"], np.float64)
            off = float(a[t].get("offset_ms", 0.0))
            ga = _grid_labels(a[t], grid, off)
            gb = _grid_labels({**b[t], "offset_ms": float(b[t].get("offset_ms", 0.0)) + d}, grid, off)
            cnt = _pair_counts(ga, gb, "common") if ga is not None and gb is not None else None
            if cnt is not None and cnt[-1] < MIN_OVERLAP:        # too short an overlap to say anything
                cnt = None
            dd = per[t][p["song"]]
            dd["dz"].append(np.abs(Z[0, :N_SET] - Z[1, :N_SET]))
            if cnt is not None:
                dd["cnt"].append(cnt)
            dd["tag"].add(p.get("tag", "modern"))
    J = N_SET
    F_point = np.full((N_TIERS, J), np.nan)
    F_boot = np.full((n_boot, N_TIERS, J), np.nan)
    cap_point = np.full((N_TIERS, 3), np.nan)
    cap_boot = np.full((n_boot, N_TIERS, 3), np.nan)
    anchor_meta = {}
    uses = {}
    for t in range(N_TIERS):
        songs = per[t]
        modern = [s for s, v in songs.items() if "modern" in v["tag"]]
        uses[t] = modern if len(modern) >= min_anchor_songs else list(songs)
        rule = "modern" if len(modern) >= min_anchor_songs else "all_pairs"
        anchor_meta[t] = {"rule": rule, "n_songs_F": sum(bool(songs[s]["dz"]) for s in uses[t]),
                          "n_songs_cap": sum(bool(songs[s]["cnt"]) for s in uses[t]), "n_modern_songs": len(modern)}
    # Bootstrap over pair songs: one weight per song per replicate, shared by every tier. A pair song feeds the
    # anchors of all its tiers and F3 / F8 pool over tiers, so resampling each tier on its own would make the
    # pooled intervals too narrow.
    boot_songs = sorted({s for t in range(N_TIERS) for s in uses[t]})
    sidx = {s: i for i, s in enumerate(boot_songs)}
    W = (rng.multinomial(len(boot_songs), np.full(len(boot_songs), 1.0 / len(boot_songs)), size=n_boot).astype(float)
         if boot_songs else np.zeros((n_boot, 0)))

    def caps(X, w):
        """Pooled rest / roll / big F1 of pair-count rows X with row weights w."""
        den = [(w * (X[:, 3 * k + 1] + X[:, 3 * k + 2])).sum() for k in range(3)]
        return np.array([2 * (w * X[:, 3 * k]).sum() / den[k] if den[k] >= MIN_LAYOUT else np.nan for k in range(3)])

    for t in range(N_TIERS):
        songs = per[t]
        sd = [s for s in uses[t] if songs[s]["dz"]]
        sc = [s for s in uses[t] if songs[s]["cnt"]]
        if sd:
            D = np.array([np.mean(songs[s]["dz"], 0) for s in sd])
            F_point[t] = 0.5 * D.mean(0)
            Wd = W[:, [sidx[s] for s in sd]]
            tot = Wd.sum(1)
            ok = tot > 0
            F_boot[ok, t] = 0.5 * (Wd[ok] @ D) / tot[ok, None]
        if sc:
            C = np.array([np.mean(songs[s]["cnt"], 0) for s in sc])
            cap_point[t] = caps(C, np.ones(len(C)))
            Wc = W[:, [sidx[s] for s in sc]]
            for b in range(n_boot):
                cap_boot[b, t] = caps(C, Wc[b])
    ref["anchor_F"] = {"point": F_point, "boot": F_boot, "meta": anchor_meta, "n_pairs": n_pairs_used}
    ref["f8_cap"] = {"point": cap_point, "boot": cap_boot, "kinds": ("rest", "roll", "big")}
    ref["f9_index"] = build_gram_index(f9_charts) if f9_charts is not None else build_gram_index([])
    ref["loudness"] = dict(loudness or {})
    return ref


def build_reference_info(charts_all: list, catalog: dict | None = None, modern_only: bool = True, loudness=None,
                         n_boot: int = 500, seed: int = 0, min_anchor_songs: int = MIN_ANCHOR_SONGS,
                         f9_all_eras: bool = True) -> dict:
    """Reference information from charts_all: training mapsets of the train split (modern only by default) for the
    normal scores and the F3 climatology; independent mapset pairs of non-test songs (no shared mapper, aligned in
    time) for anchor F and the F8 cap, tagged 'modern' when both mapsets are modern and 'era2' when their years are
    within 2 of each other; every training chart (all eras by default: the model trains on them) for F9."""
    from .train import song_split
    catalog = catalog if catalog is not None else load_catalog()
    by = group_songs(charts_all)
    train_songs, pairs, f9 = {}, [], []
    for key, entries in by.items():
        split = song_split(key)
        if split == "test":
            continue
        mss = [(e, _entry_mapset(e, catalog)) for e in entries]
        mss = [(e, ms) for e, ms in mss if ms]
        if split == "train":
            keep = [ms for e, ms in mss if not modern_only or _entry_year(e) >= MODERN_YEAR]
            if keep:
                train_songs[key] = keep
            for e in entries:
                if f9_all_eras or _entry_year(e) >= MODERN_YEAR:
                    f9 += [c for c in e["charts"] if len(c["time"]) >= MIN_NOTES]
        for i in range(len(mss)):
            for j in range(i + 1, len(mss)):
                (ea, a), (eb, b) = mss[i], mss[j]
                if _mappers(a) & _mappers(b) or not _mappers(a) or not _mappers(b):
                    continue
                ya, yb = _entry_year(ea), _entry_year(eb)
                if min(ya, yb) >= MODERN_YEAR:
                    tag = "modern"
                elif abs(ya - yb) <= 2:
                    tag = "era2"
                else:
                    continue
                pairs.append({"song": key, "a": a, "b": b, "tag": tag})
    ref = build_reference_from_mapsets(train_songs, pairs, f9, loudness, n_boot, seed, min_anchor_songs, "auto")
    ref["meta"] = {"modern_only": modern_only, "n_train_songs": len(train_songs), "n_pairs": len(pairs),
                   "n_f9_charts": ref["f9_index"]["n_charts"]}
    return ref


# ------------------------------------------------------------------------------------------------ unit statistics

def compute_unit_stats(collection: dict) -> dict:
    """Per-chart and per-set statistics of a collection that do not depend on the reference: chart values on the
    chart's own timing, labels on the song's measure grid (human[0]'s hardest chart), layout counts of adjacent
    tiers within each mapset (F5) and of every pair of mapsets per tier (F8)."""
    U = {"songs": [], "sets": [], "charts": [], "f5": [], "f8": [], "extra_tiers": 0, "skipped_songs": []}
    for key in sorted(collection):
        e = collection[key]
        humans = [_norm_mapset(m) for m in e.get("human") or []]
        draws = [_norm_mapset(m) for m in e.get("draws") or []]
        if not humans or not humans[0]:
            U["skipped_songs"].append(key)
            continue
        tiers = sorted(humans[0])
        grid_chart = humans[0][tiers[-1]]
        grid_sec = np.asarray(grid_chart["sections"], np.float64)
        grid_off = float(grid_chart.get("offset_ms", 0.0))
        si = len(U["songs"])
        U["songs"].append({"key": key, "tiers": tiers, "n_human": len(humans), "n_draws": len(draws)})
        by_tier = defaultdict(list)                       # tier -> [(set row, grid labels)]
        for j, ms in enumerate(humans + draws):
            row = len(U["sets"])
            U["sets"].append({"song": si, "pos": j, "human": j < len(humans)})
            if j >= len(humans):
                U["extra_tiers"] += len(set(ms) - set(tiers))
            grid = {}
            for t in tiers:
                c = ms.get(t)
                rec = chart_values(c) if c is not None else None
                if rec is None:
                    continue
                gl = _grid_labels(c, grid_sec, grid_off)
                U["charts"].append({"song": si, "set": row, "tier": t, **rec, "grid": gl})
                if gl is not None:
                    grid[t] = gl
                    by_tier[t].append((row, gl))
            for t in tiers:
                if t in grid and t + 1 in grid:
                    cnt = _pair_counts(grid[t], grid[t + 1])
                    if cnt is not None:
                        U["f5"].append((row, t, cnt))
        for t, lst in by_tier.items():
            for x in range(len(lst)):
                for y in range(x + 1, len(lst)):
                    cnt = _pair_counts(lst[x][1], lst[y][1], "common")     # the window of the F8 cap
                    if cnt is not None and cnt[-1] >= MIN_OVERLAP:          # the overlap rule of the F8 cap
                        U["f8"].append((si, t, lst[x][0], lst[y][0], cnt))
    return U


# ------------------------------------------------------------------------------------------------ small statistics

def _weights(key: np.ndarray, member: np.ndarray, base: np.ndarray) -> np.ndarray:
    """Weight base[i] / (number of members sharing key[i]) for members, 0 otherwise: each key counts once."""
    if len(key) == 0:
        return np.zeros(0)
    cnt = np.bincount(key[member], minlength=int(key.max()) + 1)
    return np.where(member, base / np.maximum(cnt[key], 1), 0.0)


def _n_songs(song: np.ndarray, w: np.ndarray) -> int:
    return len(np.unique(song[w > 0]))


def _sorted_support(x: np.ndarray):
    """Order of the finite entries of x and the gaps between consecutive sorted values (fixed support for W1)."""
    idx = np.where(np.isfinite(x))[0]
    o = idx[np.argsort(x[idx], kind="stable")]
    return o, np.diff(x[o])


def _w1_sorted(wa: np.ndarray, wb: np.ndarray, o: np.ndarray, dx: np.ndarray) -> float:
    """Wasserstein-1 between two weighted samples living on the same sorted support."""
    a, b = wa[o], wb[o]
    sa, sb = a.sum(), b.sum()
    if sa <= 0 or sb <= 0:
        return np.nan
    return float((np.abs(np.cumsum(a) / sa - np.cumsum(b) / sb)[:-1] * dx).sum())


def _w1_two_part(wa: np.ndarray, wb: np.ndarray, sup: dict) -> float:
    """W1 of normal scores; for zero-heavy values: |difference of zero shares| + non-zero share x W1 of the
    positive-part normal scores."""
    if not sup["two_part"]:
        return _w1_sorted(wa, wb, *sup["plain"])
    sa, sb = wa.sum(), wb.sum()
    if sa <= 0 or sb <= 0:
        return np.nan
    za, zb = (wa * sup["zero"]).sum() / sa, (wb * sup["zero"]).sum() / sb
    pos = _w1_sorted(wa * ~sup["zero"], wb * ~sup["zero"], *sup["pos"])
    return float(abs(za - zb) + (1 - (za + zb) / 2) * (0.0 if np.isnan(pos) else pos))


def _w1_uniform(u: np.ndarray, w: np.ndarray) -> float:
    """W1 between the weighted sample u in [0, 1] and the uniform distribution: integral of |F(x) - x|."""
    if len(u) == 0 or w.sum() <= 0:
        return np.nan
    o = np.argsort(u)
    e = np.concatenate([[0.0], u[o], [1.0]])
    c = np.concatenate([[0.0], np.cumsum(w[o]) / w.sum()])
    a, b = e[:-1], e[1:]
    v = np.where(c <= a, ((b - c) ** 2 - (a - c) ** 2) / 2,
                 np.where(c >= b, ((c - a) ** 2 - (c - b) ** 2) / 2, ((c - a) ** 2 + (b - c) ** 2) / 2))
    return float(v.sum())


def _wcorr_sym(x: np.ndarray, y: np.ndarray, w: np.ndarray) -> float:
    """Weighted correlation of the pairs (x, y) taken in both orders (symmetric in the two members)."""
    xx, yy, ww = np.concatenate([x, y]), np.concatenate([y, x]), np.concatenate([w, w])
    if ww.sum() <= 0:
        return np.nan
    mx = (ww * xx).sum() / ww.sum()
    my = (ww * yy).sum() / ww.sum()
    cov = (ww * (xx - mx) * (yy - my)).sum()
    den = np.sqrt((ww * (xx - mx) ** 2).sum() * (ww * (yy - my) ** 2).sum())
    return float(cov / den) if den > 1e-12 else np.nan


def _wsd(x: np.ndarray, w: np.ndarray) -> float:
    if w.sum() <= 0:
        return np.nan
    m = (w * x).sum() / w.sum()
    return float(np.sqrt((w * (x - m) ** 2).sum() / w.sum()))


def _auc(score: np.ndarray, pos: np.ndarray) -> float:
    """P(score of a positive > score of a negative), ties counted 1/2 (Mann-Whitney with mid-ranks)."""
    n1, n0 = int(pos.sum()), int((~pos).sum())
    if n1 == 0 or n0 == 0:
        return np.nan
    _, inv, cnt = np.unique(score, return_inverse=True, return_counts=True)
    start = np.concatenate([[0], np.cumsum(cnt)[:-1]])
    mid = start + (cnt + 1) / 2.0
    r = mid[inv]
    return float((r[pos].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))


def _vec() -> np.ndarray:
    return np.full(1 + N_TIERS, np.nan)


# ------------------------------------------------------------------------------------------------ preparation

def _prepare(U: dict, ref: dict) -> dict:
    """Arrays for the fast evaluation of every family under any role assignment and song weights."""
    ctx = {"n_songs": len(U["songs"]), "song_keys": [s["key"] for s in U["songs"]]}
    S = len(U["sets"])
    ctx["set_song"] = np.array([s["song"] for s in U["sets"]], np.int64)
    ctx["set_human"] = np.array([s["human"] for s in U["sets"]], bool)
    ctx["n_human"] = np.array([s["n_human"] for s in U["songs"]], np.int64)
    ch = U["charts"]
    C = len(ch)
    ctx["ch_song"] = np.array([c["song"] for c in ch], np.int64)
    ctx["ch_set"] = np.array([c["set"] for c in ch], np.int64)
    ctx["ch_tier"] = np.array([c["tier"] for c in ch], np.int64)
    V = np.array([c["values"] for c in ch]) if C else np.zeros((0, len(VALUE_NAMES)))
    Z, Zp, Zero = _zscore(V, ctx["ch_tier"], ref)
    ctx.update(V=V, Z=Z)
    ctx["key_st"] = ctx["ch_song"] * N_TIERS + ctx["ch_tier"]
    ctx["tier_rows"] = [np.where(ctx["ch_tier"] == t)[0] for t in range(N_TIERS)]
    heavy = {t: {j: ref["zero_share"][t][nm] >= ZERO_HEAVY for j, nm in enumerate(VALUE_NAMES)}
             for t in range(N_TIERS)}
    ctx["heavy"] = heavy

    # F1 / F7: per tier, sorted supports for (two-part) W1 and the distance matrix for the energy distance
    ctx["sup"], ctx["D"] = {}, {}
    for t in range(N_TIERS):
        rows = ctx["tier_rows"][t]
        ctx["sup"][t] = {}
        for j in range(len(VALUE_NAMES)):
            sup = {"two_part": heavy[t][j], "plain": _sorted_support(Z[rows, j]), "zero": Zero[rows, j]}
            if heavy[t][j]:
                sup["pos"] = _sorted_support(np.where(Zero[rows, j], np.nan, Zp[rows, j]))
            ctx["sup"][t][j] = sup
        if len(rows):
            flags = [Zero[rows, j][:, None].astype(float) for j in range(N_SET) if heavy[t][j]]
            E = np.concatenate([Z[rows, :N_SET]] + flags, 1)
            E = np.nan_to_num(E)
            sq = (E ** 2).sum(1)
            ctx["D"][t] = np.sqrt(np.maximum(sq[:, None] + sq[None, :] - 2 * E @ E.T, 0.0))

    # F2 / F3: units = (song, tier) with the members (all mapsets of the song) padded to M columns
    units = defaultdict(list)
    for i in range(C):
        units[(ctx["ch_song"][i], ctx["ch_tier"][i])].append(i)
    ukeys = sorted(units)
    M = max((len(v) for v in units.values()), default=1)
    UR = np.full((len(ukeys), M), -1, np.int64)
    for u, k in enumerate(ukeys):
        UR[u, : len(units[k])] = units[k]
    ctx["UR"] = UR
    ctx["u_song"] = np.array([k[0] for k in ukeys], np.int64)
    ctx["u_tier"] = np.array([k[1] for k in ukeys], np.int64)
    present = UR >= 0
    UV = np.where(present[..., None], V[np.maximum(UR, 0)][..., :N_SET] if C else 0.0, np.nan)
    UZ = np.where(present[..., None], Z[np.maximum(UR, 0)][..., :N_SET] if C else 0.0, np.nan)
    ctx["LESS"] = UV[:, None, :, :] < UV[:, :, None, :]        # [u, h, m, j]: member m below member h
    ctx["EQ"] = UV[:, None, :, :] == UV[:, :, None, :]
    ctx["PD"] = np.nan_to_num(np.abs(UZ[:, None, :, :] - UZ[:, :, None, :]))   # [u, h, m, j] |z_h - z_m|
    pools = {t: [_crps_pool(normal_scores(ref["z_ref"][t][nm], ref["z_ref"][t][nm])) for nm in SETTING_NAMES]
             for t in range(N_TIERS)}
    UC = np.full(UZ.shape, np.nan)
    for t in range(N_TIERS):
        uu = ctx["u_tier"] == t
        for j in range(N_SET):
            if pools[t][j] is not None:
                UC[uu, :, j] = _crps_clim(UZ[uu, :, j], pools[t][j])
    ctx["UC"] = np.nan_to_num(UC)
    aF = ref["anchor_F"]
    ctx["F_point"], ctx["F_boot"] = aF["point"], aF["boot"]
    elig = np.zeros((N_TIERS, N_SET), bool)
    for t in range(N_TIERS):
        for j, nm in enumerate(SETTING_NAMES):
            room = (pools[t][j]["half"] if pools[t][j] is not None else 0.0) - aF["point"][t, j]
            elig[t, j] = (1 - ref["zero_share"][t][nm] >= F3_MIN_NONZERO) and np.isfinite(room) and room >= F3_MIN_ROOM
    ctx["f3_elig"] = elig
    ctx["f3_half"] = np.array([[p["half"] if p is not None else np.nan for p in pools[t]] for t in range(N_TIERS)])

    # F4: per set, normal scores of the 6 main settings and raw density per tier
    J4 = len(F4_NAMES)
    SZ = np.full((S, N_TIERS, J4), np.nan)
    SD = np.full((S, N_TIERS), np.nan)
    for i in range(C):
        SZ[ctx["ch_set"][i], ctx["ch_tier"][i]] = Z[i, :J4]
        SD[ctx["ch_set"][i], ctx["ch_tier"][i]] = V[i, SETTING_NAMES.index("density")]
    dz = SZ[:, 1:] - SZ[:, :-1]                                 # [S, 4, J4] signed steps t -> t+1
    pres = np.isfinite(dz).all(2)                               # [S, 4]
    inv = np.where(pres, (SD[:, 1:] <= SD[:, :-1]).astype(float), np.nan)
    ctx.update(SZ=SZ, f4_dz=dz, f4_pres=pres, f4_inv=inv)
    ctx["f4_sup"] = [[_sorted_support(np.where(pres[:, p], dz[:, p, j], np.nan)) for j in range(J4)]
                     for p in range(N_TIERS - 1)]
    n_t = np.isfinite(SZ[:, :, 0]).sum(1)
    ctx["f4_m3"] = n_t >= 3
    ctx["f4_mean"] = np.where(ctx["f4_m3"][:, None], _nanmean_tiers(SZ), np.nan)

    # F5 and F8 count tables
    ctx["f5_set"] = np.array([r[0] for r in U["f5"]], np.int64)
    ctx["f5_pair"] = np.array([r[1] for r in U["f5"]], np.int64)
    ctx["f5_cnt"] = np.array([r[2] for r in U["f5"]]) if U["f5"] else np.zeros((0, 10))
    ctx["f8_song"] = np.array([r[0] for r in U["f8"]], np.int64)
    ctx["f8_tier"] = np.array([r[1] for r in U["f8"]], np.int64)
    ctx["f8_a"] = np.array([r[2] for r in U["f8"]], np.int64)
    ctx["f8_b"] = np.array([r[3] for r in U["f8"]], np.int64)
    ctx["f8_cnt"] = np.array([r[4] for r in U["f8"]]) if U["f8"] else np.zeros((0, 10))
    ctx["cap_point"], ctx["cap_boot"] = ref["f8_cap"]["point"], ref["f8_cap"]["boot"]

    # F6: AUC of quietness for rest vs active measures inside each chart (songs with loudness only)
    auc = np.full(C, np.nan)
    loud = ref.get("loudness") or {}
    for i, c in enumerate(ch):
        cur = loud.get(ctx["song_keys"][c["song"]])
        g = c["grid"]
        if cur is None or g is None:
            continue
        q = -_measure_loudness(cur, g["st_ms"], g["en_ms"])
        act = g["active"]
        ia = np.where(act)[0]
        ins = np.zeros(len(act), bool)
        ins[ia[0]: ia[-1] + 1] = True
        ok = ins & np.isfinite(q)
        auc[i] = _auc(q[ok], ~act[ok])
    ctx["auc"] = auc
    ctx["n_loud_songs"] = len({ctx["song_keys"][c["song"]] for c, a in zip(ch, auc) if np.isfinite(a)})

    # F7 histograms; F9 novelty against the training index
    ctx["run_hist"] = np.array([c["run_hist"] for c in ch]) if C else np.zeros((0, RUN_BINS))
    ctx["phase_hist"] = np.array([c["phase_hist"] for c in ch]) if C else np.zeros((0, 4))
    nov = np.array([gram_novelty(c["grams"], ref["f9_index"]) for c in ch]) if C else np.zeros((0, 2))
    ctx["seen"], ctx["best"] = nov[:, 0], nov[:, 1]
    ctx["f9_sup"] = [_sorted_support(np.where(np.isin(np.arange(C), ctx["tier_rows"][t]), ctx["best"], np.nan))
                     for t in range(N_TIERS)]
    return ctx


def _nanmean_tiers(SZ: np.ndarray) -> np.ndarray:
    """Mean over the present tiers of a set ([S, tiers, J] with NaN for missing tiers)."""
    ok = np.isfinite(SZ)
    return np.where(ok, SZ, 0.0).sum(1) / np.maximum(ok.sum(1), 1)


def _measure_loudness(cur: dict, st_ms: np.ndarray, en_ms: np.ndarray, k: int = 8) -> np.ndarray:
    """Mean loudness over each measure's time span, sampled at k points; NaN outside the loudness curve."""
    x = st_ms[:, None] + (en_ms - st_ms)[:, None] * ((np.arange(k) + 0.5) / k)[None, :]
    j = np.searchsorted(cur["t0"], x, "right") - 1
    jc = np.clip(j, 0, len(cur["t0"]) - 1)
    ok = (j >= 0) & (x < cur["t1"][jc])
    cnt = ok.sum(1)
    tot = np.where(ok, cur["loud"][jc], 0.0).sum(1)
    return np.where(cnt > 0, tot / np.maximum(cnt, 1), np.nan)


# ------------------------------------------------------------------------------------------------ families

def _f1(ctx, ch_h, ch_s, wsong):
    energy, w1 = _vec(), _vec()
    for t in range(N_TIERS):
        rows = ctx["tier_rows"][t]
        if len(rows) == 0:
            continue
        base, key = wsong[ctx["ch_song"][rows]], ctx["key_st"][rows]
        wh, ws = _weights(key, ch_h[rows], base), _weights(key, ch_s[rows], base)
        song = ctx["ch_song"][rows]
        if _n_songs(song, wh) < MIN_SONGS or _n_songs(song, ws) < MIN_SONGS:
            continue
        a, b = wh / wh.sum(), ws / ws.sum()
        D = ctx["D"][t]
        energy[1 + t] = 2 * a @ D @ b - a @ D @ a - b @ D @ b
        w1[1 + t] = np.nanmean([_w1_two_part(wh, ws, ctx["sup"][t][j]) for j in range(N_SET)])
    for v in (energy, w1):
        if np.isfinite(v[1:]).any():
            v[0] = np.nanmean(v[1:])
    return {"energy": energy, "w1_mean": w1}


def _unit_roles(ctx, roles):
    UR = ctx["UR"]
    P = UR >= 0
    r = np.zeros(UR.shape, bool)
    r[P] = roles[ctx["ch_set"][UR[P]]]
    return P & r, P & ~r


def _f2(ctx, roles, wsong, rng):
    RH, RS = _unit_roles(ctx, roles)
    nS = RS.sum(1)
    below = np.einsum("um,uhmj->uhj", RS.astype(float), ctx["LESS"].astype(float))
    ties = np.einsum("um,uhmj->uhj", RS.astype(float), ctx["EQ"].astype(float))
    u = (below + (ties + 1) * rng.random(below.shape)) / (nS[:, None, None] + 1)
    valid = RH & (nS >= 1)[:, None]
    w = np.where(valid, (wsong[ctx["u_song"]] / np.maximum(RH.sum(1), 1))[:, None], 0.0)
    out = _vec()
    for k in range(1 + N_TIERS):
        sel = valid & ((ctx["u_tier"] == k - 1)[:, None] if k else True)
        if _n_songs(ctx["u_song"], (w * sel).sum(1)) < MIN_SONGS:
            continue
        out[k] = np.mean([_w1_uniform(u[..., j][sel], w[sel]) for j in range(N_SET)])
    return {"pit_w1": out}, u, valid, w


def _f3(ctx, roles, wsong, rep, per_setting=False):
    RH, RS = _unit_roles(ctx, roles)
    RSf = RS.astype(float)
    nS = RSf.sum(1)
    PD = ctx["PD"]
    t1 = np.einsum("um,uhmj->uhj", RSf, PD) / np.maximum(nS, 1)[:, None, None]
    # PD[u, h, m] holds |z_h - z_m| for every member pair, so the ensemble spread uses it with h, m both drawn
    spread = np.einsum("uh,um,uhmj->uj", RSf, RSf, PD) / np.maximum(nS * (nS - 1), 1)[:, None]
    S = t1 - 0.5 * spread[:, None, :]
    valid = RH & (nS >= 2)[:, None]
    w = np.where(valid, (wsong[ctx["u_song"]] / np.maximum(RH.sum(1), 1))[:, None], 0.0)    # [u, h]
    F = ctx["F_point"] if rep is None else ctx["F_boot"][rep % len(ctx["F_boot"])]
    Fu = F[ctx["u_tier"]]                                                                      # [u, j]
    E = ctx["f3_elig"][ctx["u_tier"]].astype(float)                                            # [u, j]
    Cw = np.einsum("uh,uhj,uj->uj", w, ctx["UC"], E)
    Sw = np.einsum("uh,uhj,uj->uj", w, S, E)
    Fw = np.einsum("uh,uj,uj->uj", w, np.nan_to_num(Fu), E)
    out = _vec()
    for k in range(1 + N_TIERS):
        sel = (ctx["u_tier"] == k - 1) if k else np.ones(len(Cw), bool)
        c, s, f = Cw[sel].sum(), Sw[sel].sum(), Fw[sel].sum()
        if c - f > 1e-9 and _n_songs(ctx["u_song"][sel], w[sel].sum(1)) >= MIN_SONGS:
            out[k] = 1 - (c - s) / (c - f)
    if not per_setting:
        return {"shortfall": out}
    sk = [(Cw[:, j].sum() - Sw[:, j].sum()) / (Cw[:, j].sum() - Fw[:, j].sum())
          if Cw[:, j].sum() - Fw[:, j].sum() > 1e-9 else np.nan for j in range(N_SET)]
    return {"shortfall": out}, sk


def _set_weights(ctx, member, wsong, pair):
    key = ctx["set_song"] * (N_TIERS - 1) + pair
    return _weights(key, member, wsong[ctx["set_song"]])


def _f4(ctx, roles, wsong):
    steps, inv, share = _vec(), _vec(), _vec()
    J4 = len(F4_NAMES)
    acc_inv = {True: [0.0, 0.0], False: [0.0, 0.0]}
    acc_xy = {True: ([], [], []), False: ([], [], [])}
    for p in range(N_TIERS - 1):
        pres = ctx["f4_pres"][:, p]
        wh = _set_weights(ctx, pres & roles, wsong, p)
        ws = _set_weights(ctx, pres & ~roles, wsong, p)
        if _n_songs(ctx["set_song"], wh) < MIN_SONGS or _n_songs(ctx["set_song"], ws) < MIN_SONGS:
            continue
        steps[1 + p] = np.nanmean([_w1_sorted(wh, ws, *ctx["f4_sup"][p][j]) for j in range(J4)])
        iv = np.nan_to_num(ctx["f4_inv"][:, p])
        inv[1 + p] = (ws * iv).sum() / ws.sum() - (wh * iv).sum() / wh.sum()
        rs = []
        for j in range(J4):
            x, y = ctx["SZ"][:, p, j], ctx["SZ"][:, p + 1, j]
            x, y = np.nan_to_num(x), np.nan_to_num(y)
            rs.append(abs(_wcorr_sym(x, y, ws) - _wcorr_sym(x, y, wh)))
        share[1 + p] = np.nanmean(rs)
        for role, w in ((True, wh), (False, ws)):
            acc_inv[role][0] += (w * iv).sum()
            acc_inv[role][1] += w.sum()
            acc_xy[role][0].append(np.nan_to_num(ctx["SZ"][:, p]))
            acc_xy[role][1].append(np.nan_to_num(ctx["SZ"][:, p + 1]))
            acc_xy[role][2].append(w)
    if np.isfinite(steps[1:]).any():
        steps[0] = np.nanmean(steps[1:])
        inv[0] = acc_inv[False][0] / acc_inv[False][1] - acc_inv[True][0] / acc_inv[True][1]
        rs = []
        for j in range(J4):
            r = {}
            for role in (True, False):
                X = np.concatenate([x[:, j] for x in acc_xy[role][0]])
                Y = np.concatenate([y[:, j] for y in acc_xy[role][1]])
                r[role] = _wcorr_sym(X, Y, np.concatenate(acc_xy[role][2]))
            rs.append(abs(r[False] - r[True]))
        share[0] = np.nanmean(rs)
    # spread of the mapset mean across songs (mapsets with at least 3 tiers)
    spread = _vec()
    m3 = ctx["f4_m3"]
    wh = _weights(ctx["set_song"], m3 & roles, wsong[ctx["set_song"]])
    ws = _weights(ctx["set_song"], m3 & ~roles, wsong[ctx["set_song"]])
    if _n_songs(ctx["set_song"], wh) >= MIN_SONGS and _n_songs(ctx["set_song"], ws) >= MIN_SONGS:
        Mx = np.nan_to_num(ctx["f4_mean"])
        lr = [abs(np.log(max(_wsd(Mx[:, j], ws), 1e-9) / max(_wsd(Mx[:, j], wh), 1e-9))) for j in range(J4)]
        spread[0] = np.mean(lr)
    return {"steps": steps, "inversions": inv, "spread": spread, "sharing": share}


def _f5(ctx, roles, wsong):
    out = {k: _vec() for k in ("rest_f1", "roll_f1", "big_f1", "nesting")}
    if len(ctx["f5_set"]) == 0:
        return out
    song = ctx["set_song"][ctx["f5_set"]]
    role = roles[ctx["f5_set"]]
    key = song * (N_TIERS - 1) + ctx["f5_pair"]
    base = wsong[song]
    wh, ws = _weights(key, role, base), _weights(key, ~role, base)
    X = ctx["f5_cnt"]
    for k in range(N_TIERS):
        sel = (ctx["f5_pair"] == k - 1) if k else np.ones(len(X), bool)
        a, b = wh * sel, ws * sel
        if _n_songs(song, a) < MIN_SONGS or _n_songs(song, b) < MIN_SONGS:
            continue
        for name, q in (("rest_f1", 0), ("roll_f1", 1), ("big_f1", 2)):
            out[name][k] = abs(_pooled_f1(X, q, b) - _pooled_f1(X, q, a))
        nest = [(w * X[:, 0]).sum() / (w * X[:, 2]).sum() if (np.sign(w) * X[:, 2]).sum() >= MIN_LAYOUT / 2 else np.nan
                for w in (a, b)]
        out["nesting"][k] = abs(nest[1] - nest[0])
    return out


def _pooled_f1(X, q, w):
    """Pooled F1 of layout kind q (0 rest, 1 roll, 2 big) over weighted pair rows; NaN when the rows (unweighted)
    hold fewer than MIN_LAYOUT labelled measures."""
    if (np.sign(w) * (X[:, 3 * q + 1] + X[:, 3 * q + 2])).sum() < MIN_LAYOUT:
        return np.nan
    return 2 * (w * X[:, 3 * q]).sum() / (w * (X[:, 3 * q + 1] + X[:, 3 * q + 2])).sum()


def _f6(ctx, ch_h, ch_s, wsong):
    out = _vec()
    ok = np.isfinite(ctx["auc"])
    key, base = ctx["key_st"], wsong[ctx["ch_song"]]
    wh, ws = _weights(key, ch_h & ok, base), _weights(key, ch_s & ok, base)
    a = np.nan_to_num(ctx["auc"])
    for k in range(1 + N_TIERS):
        sel = (ctx["ch_tier"] == k - 1) if k else np.ones(len(a), bool)
        h, s = wh * sel, ws * sel
        if _n_songs(ctx["ch_song"], h) < MIN_SONGS or _n_songs(ctx["ch_song"], s) < MIN_SONGS:
            continue
        out[k] = abs((s * a).sum() / s.sum() - (h * a).sum() / h.sum())
    return {"auc": out}


def _f7(ctx, ch_h, ch_s, wsong):
    names = {"blocks_per100": VALUE_NAMES.index("rest_blocks_per100"), "block_len": VALUE_NAMES.index("rest_block_len"),
             "roll_len": VALUE_NAMES.index("roll_len"), "dens_cv": VALUE_NAMES.index("dens_cv")}
    out = {k: _vec() for k in ("run_length", "phase4", *names)}
    acc = {"run_length": [np.zeros(RUN_BINS), np.zeros(RUN_BINS)], "phase4": [np.zeros(4), np.zeros(4)]}
    any_tier = False
    for t in range(N_TIERS):
        rows = ctx["tier_rows"][t]
        if len(rows) == 0:
            continue
        base, key = wsong[ctx["ch_song"][rows]], ctx["key_st"][rows]
        wh, ws = _weights(key, ch_h[rows], base), _weights(key, ch_s[rows], base)
        song = ctx["ch_song"][rows]
        if _n_songs(song, wh) < MIN_SONGS or _n_songs(song, ws) < MIN_SONGS:
            continue
        any_tier = True
        for name, j in names.items():
            out[name][1 + t] = _w1_two_part(wh, ws, ctx["sup"][t][j])
        for name, Hc in (("run_length", ctx["run_hist"][rows]), ("phase4", ctx["phase_hist"][rows])):
            hh, hs = wh @ Hc, ws @ Hc
            acc[name][0] += hh
            acc[name][1] += hs
            out[name][1 + t] = _tv_hist(hh, hs)
    for name in names:
        if np.isfinite(out[name][1:]).any():
            out[name][0] = np.nanmean(out[name][1:])
    for name in acc:
        if any_tier:
            out[name][0] = _tv_hist(*acc[name])
    return out


def _tv_hist(hh: np.ndarray, hs: np.ndarray) -> float:
    """Total variation distance of two count histograms. When only one side has any count (for example a system
    that never writes a rest run), the two differ completely: 1. NaN when neither side has a count."""
    if hh.sum() > 0 and hs.sum() > 0:
        return float(0.5 * np.abs(hh / hh.sum() - hs / hs.sum()).sum())
    return 1.0 if hh.sum() > 0 or hs.sum() > 0 else np.nan


def _f8(ctx, roles, wsong, rep, details=False):
    out = {k: _vec() for k in ("rest", "roll", "big", "rest_within_song")}
    if len(ctx["f8_a"]) == 0:
        return (out, {}) if details else out
    ra, rb = roles[ctx["f8_a"]], roles[ctx["f8_b"]]
    ss, hs = ~ra & ~rb, ra ^ rb
    song, tier = ctx["f8_song"], ctx["f8_tier"]
    key, base = song * N_TIERS + tier, wsong[song]
    wss, whs = _weights(key, ss, base), _weights(key, hs, base)
    X = ctx["f8_cnt"]
    cap = ctx["cap_point"] if rep is None else ctx["cap_boot"][rep % len(ctx["cap_boot"])]
    info = {}
    for q, name in enumerate(("rest", "roll", "big")):
        num, den, exc = [], [], []
        for t in range(N_TIERS):
            w = wss * (tier == t)
            agree = _pooled_f1(X, q, w)
            if _n_songs(song, w) < MIN_SONGS or not np.isfinite(agree) or not np.isfinite(cap[t, q]):
                continue
            d = (w * (X[:, 3 * q + 1] + X[:, 3 * q + 2])).sum()
            out[name][1 + t] = agree - cap[t, q]
            num.append(d * (agree - cap[t, q]))
            den.append(d)
            info[(name, t)] = (agree, cap[t, q])
        if den:
            out[name][0] = sum(num) / sum(den)
    for k in range(1 + N_TIERS):
        sel = (tier == k - 1) if k else np.ones(len(tier), bool)
        a, b = wss * sel, whs * sel
        if _n_songs(song, a) < MIN_SONGS or _n_songs(song, b) < MIN_SONGS:
            continue
        out["rest_within_song"][k] = _pooled_f1(X, 0, a) - _pooled_f1(X, 0, b)
    return (out, info) if details else out


def _f9(ctx, ch_h, ch_s, wsong):
    out = {k: _vec() for k in ("copy_share", "best_single", "seen_share")}
    ok = np.isfinite(ctx["best"])
    key, base = ctx["key_st"], wsong[ctx["ch_song"]]
    wh, ws = _weights(key, ch_h & ok, base), _weights(key, ch_s & ok, base)
    copy = (np.nan_to_num(ctx["best"]) >= COPY_CUT).astype(float)
    seen = np.nan_to_num(ctx["seen"])
    w1s = []
    for k in range(1 + N_TIERS):
        sel = (ctx["ch_tier"] == k - 1) if k else np.ones(len(copy), bool)
        h, s = wh * sel, ws * sel
        if _n_songs(ctx["ch_song"], h) < MIN_SONGS or _n_songs(ctx["ch_song"], s) < MIN_SONGS:
            continue
        out["copy_share"][k] = (s * copy).sum() / s.sum() - (h * copy).sum() / h.sum()
        out["seen_share"][k] = abs((s * seen).sum() / s.sum() - (h * seen).sum() / h.sum())
        if k:
            out["best_single"][k] = _w1_sorted(h, s, *ctx["f9_sup"][k - 1])
            w1s.append(out["best_single"][k])
    if w1s:
        out["best_single"][0] = np.nanmean(w1s)
    return out


def _evaluate(ctx, roles, wsong, rng, rep):
    """All family statistics ({family: {part: [pooled, stratum 1..5]}}) for one role assignment (True = human set)
    and one set of song weights."""
    ch_h = roles[ctx["ch_set"]]
    ch_s = ~ch_h
    return {"F1": _f1(ctx, ch_h, ch_s, wsong), "F2": _f2(ctx, roles, wsong, rng)[0],
            "F3": _f3(ctx, roles, wsong, rep), "F4": _f4(ctx, roles, wsong), "F5": _f5(ctx, roles, wsong),
            "F6": _f6(ctx, ch_h, ch_s, wsong), "F7": _f7(ctx, ch_h, ch_s, wsong), "F8": _f8(ctx, roles, wsong, rep),
            "F9": _f9(ctx, ch_h, ch_s, wsong)}


def _swap_roles(ctx, rng):
    """Random relabelling within each song: n_human of the song's mapsets, chosen uniformly, become 'human'."""
    keys = rng.random(len(ctx["set_song"]))
    order = np.lexsort((keys, ctx["set_song"]))
    ss = ctx["set_song"][order]
    first = np.concatenate([[True], ss[1:] != ss[:-1]])
    rank = np.arange(len(ss)) - np.maximum.accumulate(np.where(first, np.arange(len(ss)), 0))
    roles = np.zeros(len(ss), bool)
    roles[order] = rank < ctx["n_human"][ss]
    return roles


# ------------------------------------------------------------------------------------------------ run

def _f(x):
    """JSON-friendly float (None for NaN)."""
    x = float(x)
    return None if not np.isfinite(x) else round(x, 6)


def _holm(p: dict) -> dict:
    keys = sorted((k for k, v in p.items() if v is not None), key=lambda k: p[k])
    m, out, run = len(keys), {}, 0.0
    for i, k in enumerate(keys):
        run = max(run, min(1.0, (m - i) * p[k]))
        out[k] = run
    return out


def run_families(collection: dict, reference_info: dict, n_swap: int = 500, n_boot: int = 500, seed: int = 0,
                 units: dict | None = None, margins: dict | None = None, boot_swaps: int = 3,
                 alpha: float = ALPHA) -> dict:
    """Evaluate a collection (human mapsets and the system's draws per song) with all nine families.

    Returns a JSON-able dict: per family the primary statistic, its swap / bootstrap p, the Holm-adjusted p, 'fail'
    (adjusted p < alpha), 'pass' (draft equivalence of all its statistics), 'details' (descriptions under the real
    labels), and under 'statistics' for each: statistic, floor (swap median, or 0 for anchor statistics), swap
    median, excess, 95% CI of the excess, p, margin, pass, and the same per tier (or per adjacent tier pair for F4
    and F5) under 'by_stratum'. `units` reuses compute_unit_stats(collection); `margins` overrides
    DRAFT_MARGINS entries ({family: {part: margin}}).

    The smallest p a swap part can reach is 1 / (n_swap + 1), and 1 / (n_boot + 1) for an anchor part; Holm over
    nine families needs p <= alpha / 9, so keep n_swap and n_boot at 200 or more (500 by default)."""
    U = units if units is not None else compute_unit_stats(collection)
    mg = {f: {**DRAFT_MARGINS[f], **(margins or {}).get(f, {})} for f in DRAFT_MARGINS}
    ctx = _prepare(U, reference_info)
    rng = np.random.default_rng(seed)
    n = ctx["n_songs"]
    roles0 = ctx["set_human"].copy()
    ones = np.ones(n)
    obs = _evaluate(ctx, roles0, ones, rng, None)
    swaps = [_evaluate(ctx, _swap_roles(ctx, rng), ones, rng, None) for _ in range(n_swap)]
    boots, bfloor = [], []
    for b in range(n_boot):
        w = rng.multinomial(n, np.full(n, 1.0 / n)).astype(np.float64)
        boots.append(_evaluate(ctx, roles0, w, rng, b))
        bfloor.append([_evaluate(ctx, _swap_roles(ctx, rng), w, rng, b) for _ in range(boot_swaps)])

    fams, primary_p = {}, {}
    for fam, (title, primary, parts) in FAMILIES.items():
        pairs = fam in PAIR_FAMILIES
        labels = [f"{t}-{t + 1}" for t in range(N_TIERS - 1)] if pairs else [str(t) for t in range(N_TIERS)]
        pres = {}
        for part, kind in parts:
            o = obs[fam][part]
            sw = np.array([s[fam][part] for s in swaps]) if swaps else np.full((0, len(o)), np.nan)
            bt = np.array([s[fam][part] for s in boots]) if boots else np.full((0, len(o)), np.nan)
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", RuntimeWarning)       # all-NaN strata stay NaN
                swap_med = np.nanmedian(sw, 0) if len(sw) else np.full(len(o), np.nan)
                if kind == "swap":
                    floor = swap_med
                    bf = np.array([[s[fam][part] for s in r] for r in bfloor]) if bfloor else np.zeros((0, 1, len(o)))
                    ex_b = bt - np.nanmedian(bf, 1) if len(bt) else bt
                    p = (1 + np.sum(sw >= o, 0)) / (1 + np.sum(np.isfinite(sw), 0))
                else:
                    floor = np.zeros(len(o))
                    ex_b = bt
                    p = (1 + np.sum(bt <= 0, 0)) / (1 + np.sum(np.isfinite(bt), 0))
                lo, hi = (np.nanpercentile(ex_b, [2.5, 97.5], 0) if len(ex_b)
                          else (np.full(len(o), np.nan), np.full(len(o), np.nan)))
            exc = o - floor
            m = mg[fam][part]
            ok_pool = np.isfinite(o[0]) and np.isfinite(hi[0])
            severe = [labels[k - 1] for k in range(1, len(o)) if np.isfinite(lo[k]) and lo[k] > m]
            passed = (bool(hi[0] <= m) and not severe) if ok_pool else None

            def entry(k):
                return {"statistic": _f(o[k]), "floor": _f(floor[k]), "swap_median": _f(swap_med[k]),
                        "excess": _f(exc[k]), "ci": [_f(lo[k]), _f(hi[k])],
                        "p": _f(p[k]) if np.isfinite(o[k]) else None}
            pres[part] = {**entry(0), "floor_kind": "swap_median" if kind == "swap" else "anchor", "margin": m,
                          "pass": passed, "in_family_pass": (fam, part) not in REPORT_ONLY, "severe_strata": severe,
                          "by_stratum": {labels[k - 1]: {**entry(k), "pass": (bool(hi[k] <= m) if np.isfinite(hi[k]) else None)}
                                         for k in range(1, len(o)) if np.isfinite(o[k])}}
        prim = pres[primary]
        primary_p[fam] = prim["p"]
        part_pass = [v["pass"] for v in pres.values() if v["in_family_pass"]]
        # a failing statistic makes the family not pass even when the primary one cannot be computed (for example
        # rest statistics of a system that never rests); without a failing one, an undefined primary leaves the
        # family not available
        if any(x is False for x in part_pass):
            fpass = False
        else:
            fpass = None if prim["pass"] is None else True
        fams[fam] = {"title": title, "primary": primary, "p": prim["p"], "pass": fpass, "statistics": pres,
                     "strata": "adjacent tier pairs" if pairs else "tiers"}
    holm = _holm(primary_p)
    for fam in fams:
        fams[fam]["p_holm"] = _f(holm[fam]) if fam in holm else None
        fams[fam]["fail"] = (holm[fam] < alpha) if fam in holm else None
    fams_details = _details(ctx, U, rng)
    for fam, d in fams_details.items():
        fams[fam]["details"] = d
    counts = {"songs": n, "skipped_songs": len(U["skipped_songs"]),
              "human_sets": int(ctx["set_human"].sum()), "draw_sets": int((~ctx["set_human"]).sum()),
              "human_charts": int(ctx["set_human"][ctx["ch_set"]].sum()),
              "draw_charts": int((~ctx["set_human"][ctx["ch_set"]]).sum()),
              "missing_draw_units": _missing_draw_units(ctx, U), "extra_draw_tiers": U["extra_tiers"],
              "songs_with_loudness": ctx["n_loud_songs"]}
    avail = {f: v["pass"] for f, v in fams.items()}
    return {"config": {"n_swap": n_swap, "n_boot": n_boot, "boot_swaps": boot_swaps, "seed": seed, "alpha": alpha,
                       "margins": mg, "copy_cut": COPY_CUT, "zero_heavy": ZERO_HEAVY},
            "counts": counts, "families": fams,
            # the gate passes only when every family passes (a family that cannot be computed is not a pass) and
            # every scored unit of every draw has a valid chart: a draw without one drops out of every statistic,
            # which would be the same as discarding draws after the fact
            "summary": {"all_pass": all(v is True for v in avail.values()) and counts["missing_draw_units"] == 0,
                        "missing_draw_units": counts["missing_draw_units"],
                        "not_available": [f for f, v in avail.items() if v is None],
                        "not_passed": [f for f, v in avail.items() if v is False],
                        "failed": [f for f, v in fams.items() if v["fail"]]}}


def _missing_draw_units(ctx, U) -> int:
    """Scored (song, tier, draw) units without a valid chart."""
    have = set(zip(ctx["ch_set"].tolist(), ctx["ch_tier"].tolist()))
    miss = 0
    for row, s in enumerate(U["sets"]):
        if not s["human"]:
            miss += sum((row, t) not in have for t in U["songs"][s["song"]]["tiers"])
    return miss


def _details(ctx, U, rng) -> dict:
    """Per-setting and per-stratum descriptions under the real labels (no resampling)."""
    roles = ctx["set_human"]
    ch_h = roles[ctx["ch_set"]]
    ch_s = ~ch_h
    ones = np.ones(ctx["n_songs"])
    out = {}
    # F1: two-part W1 and zero shares per tier and setting
    f1 = {}
    for t in range(N_TIERS):
        rows = ctx["tier_rows"][t]
        if len(rows) == 0:
            continue
        key, base = ctx["key_st"][rows], ones[ctx["ch_song"][rows]]
        wh, ws = _weights(key, ch_h[rows], base), _weights(key, ch_s[rows], base)
        if wh.sum() <= 0 or ws.sum() <= 0:
            continue
        V = ctx["V"][rows]
        f1[str(t)] = {nm: {"w1": _f(_w1_two_part(wh, ws, ctx["sup"][t][j])), "two_part": bool(ctx["heavy"][t][j]),
                           "zero_share_human": _f((wh * (V[:, j] == 0)).sum() / wh.sum()),
                           "zero_share_system": _f((ws * (V[:, j] == 0)).sum() / ws.sum()),
                           "mean_human": _f((wh * V[:, j]).sum() / wh.sum()),
                           "mean_system": _f((ws * V[:, j]).sum() / ws.sum())}
                      for j, nm in enumerate(SETTING_NAMES)}
    out["F1"] = {"per_tier_setting": f1}
    # F2: bias, dispersion and outside share of the PIT per setting
    _, u, valid, w = _f2(ctx, roles, ones, rng)
    nS = _unit_roles(ctx, roles)[1].sum(1)
    f2 = {}
    for j, nm in enumerate(SETTING_NAMES):
        x, ww = u[..., j][valid], w[valid]
        if ww.sum() <= 0:
            continue
        mu = (ww * x).sum() / ww.sum()
        k = np.repeat(nS[:, None], valid.shape[1], 1)[valid]
        outside = (x < 1 / (k + 1)) | (x > k / (k + 1))
        f2[nm] = {"bias": _f(mu - 0.5), "dispersion_12var": _f(12 * (ww * (x - mu) ** 2).sum() / ww.sum()),
                  "outside": _f((ww * outside).sum() / ww.sum()), "outside_expected": _f((ww * 2 / (k + 1)).sum() / ww.sum())}
    out["F2"] = {"per_setting": f2, "note": "uniform PIT: bias 0, dispersion 1; dispersion > 1 = draws too narrow"}
    # F3: skill per setting, eligibility and anchors
    res, sk = _f3(ctx, roles, ones, None, per_setting=True)
    out["F3"] = {"skill_pooled": _f(1 - res["shortfall"][0]) if np.isfinite(res["shortfall"][0]) else None,
                 "skill_per_setting": {nm: _f(v) for nm, v in zip(SETTING_NAMES, sk)},
                 "eligible": {str(t): [nm for j, nm in enumerate(SETTING_NAMES) if ctx["f3_elig"][t, j]]
                              for t in range(N_TIERS)},
                 "anchor_F": {str(t): {nm: _f(ctx["F_point"][t, j]) for j, nm in enumerate(SETTING_NAMES)}
                              for t in range(N_TIERS)},
                 "climatology_half_spread": {str(t): {nm: _f(ctx["f3_half"][t, j]) for j, nm in enumerate(SETTING_NAMES)}
                                             for t in range(N_TIERS)}}
    # F6 / F8 / F9 descriptions
    out["F6"] = {"songs_with_loudness": ctx["n_loud_songs"],
                 "mean_auc_human": _f(np.nanmean(np.where(ch_h, ctx["auc"], np.nan))) if np.isfinite(ctx["auc"][ch_h]).any() else None,
                 "mean_auc_system": _f(np.nanmean(np.where(ch_s, ctx["auc"], np.nan))) if np.isfinite(ctx["auc"][ch_s]).any() else None}
    _, info = _f8(ctx, roles, ones, None, details=True)
    out["F8"] = {"agreement_and_cap": {f"{k[0]}_{k[1]}": {"agreement": _f(v[0]), "cap": _f(v[1])} for k, v in info.items()}}
    copies = [{"song": ctx["song_keys"][ctx["ch_song"][i]], "set": int(U["sets"][ctx["ch_set"][i]]["pos"]),
               "tier": int(ctx["ch_tier"][i]), "best_single": _f(ctx["best"][i]), "human": bool(ch_h[i])}
              for i in np.where(np.nan_to_num(ctx["best"]) >= COPY_CUT)[0]]
    out["F9"] = {"copies": copies[:200], "n_copies_system": int(sum(not c["human"] for c in copies)),
                 "n_copies_human": int(sum(c["human"] for c in copies))}
    return out