symfn 0.9.0

A modern, fast kernel for computing with symmetric functions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
//! LLT polynomials: the ribbon model, the tuple model, and the dictionary
//! between them.
//!
//! ## One family, two presentations
//!
//! **The tuple model** ([HHL] Def 3.2). A tuple `ν = (ν⁽¹⁾, …, ν⁽ʳ⁾)` of skew
//! shapes, each carrying an integer content offset; a cell's content is
//! `col − row + offset`. Reading order sorts cells by (content, component,
//! row). Two cells in *distinct* components **attack** when they share a
//! content (earlier component first) or sit on adjacent contents (later
//! component first). Then
//!
//! ```text
//!   G_ν(x; q) = Σ_{T ∈ SSYT(ν)} q^{inv(T)} x^T
//! ```
//!
//! with `inv` counting attacking pairs that are out of order.
//!
//! **The ribbon model** ([LLT] §6). Fix a level `k`. A k-ribbon tableau of
//! shape λ peels λ by horizontal k-ribbon strips; `spin` adds `(h−1)/2` per
//! ribbon and `cospin` is `s*(λ) − spin`. Four normalizations circulate, and
//! this module offers all four because the literature uses all four:
//!
//! ```text
//!   G_LT,λ  = Σ_R q^{2s(R)} x^{w(R)}                  [LT] (43)   `llt_g_lt`
//!   G̃^(k)_λ = Σ_R q^{s̃(R)} x^{w(R)}                   [LLT] (26)  `llt_gtilde`
//!   H̃^(k)_μ = G̃^(k)_{kμ}                              [LLT] (27)  `llt_h_tilde`
//!   H^(k)_μ = Σ_R q^{s(R)} x^{w(R)} = q^{s*} H̃(x;1/q) [LLT] (28)  `llt_h`
//! ```
//!
//! The Sage dictionary: `Sym.llt(k).hspin()` is [`llt_h`], `hcospin()` is
//! [`llt_h_tilde`], and `cospin()` on a partition is [`llt_gtilde`]. Sage names
//! the grading variable **t** where this module names it **q**, and `cospin()`
//! on a *tuple* is floored — it returns `q^{−min inv} G_ν` where [`llt_g`]
//! returns the raw inv grading. `scripts/check_llt.py` and
//! `scripts/check_bindings.py` hold the crate to it.
//!
//! ## The conventions in circulation
//!
//! The two models agree, but not on the nose, and every trap below is silent —
//! it returns a wrong-by-a-twist answer rather than an error. Each is pinned by
//! a test.
//!
//! - **The min-inv floor.** The dictionary is
//!   `q^{−min inv} G_{k-quotient(λ)} = G̃^(k)_λ`, offsets zero. The floor is
//!   *forced*: λ = (2,2,2) at k = 2 has 2-quotient `((1), (1,1))` and
//!   `min inv = 1`, which no offset choice removes. [`llt_g`] therefore
//!   exposes the **raw** inv grading and [`llt_min_inv`] beside it, rather
//!   than quietly normalizing. λ = (2,2) is *not* a witness — its quotient
//!   `((1), (1))` has floor 0 — and reading it as one breaks the convention
//!   gate, which depends on that zero. Both halves are pinned by
//!   `the_min_inv_floor_is_forced`.
//! - **The tilde collision.** [HHL] writes `G̃` for the *spin*-flavored
//!   function; [LLT] writes `G̃` for the *cospin* one. Reading [HHL]'s
//!   remark-shaped `q^e G(1/q)` as the quotient dictionary gives the wrong
//!   answer; the direct floored equality above is the law.
//! - **Tuples lose absolute spin.** λ = (1,1,1,1) at k = 2 has one ribbon
//!   tableau with `s* = 1`, while its 2-quotient is two single cells with
//!   `max inv = min inv = 0`. No statistic of the tuple recovers `s*`, so the
//!   spin-graded `H` is exposed on the **partition-plus-level** side only.
//! - **The shuffle-world reversal** ([DA] Remark 2.2).
//!   [`SkewTuple::from_area`] lists the runs of a Dyck path in **reverse row
//!   order**; with any other order [HHL]'s attacking inversions stop agreeing
//!   with [HRW] `dinv` pointwise.
//! - **Two graphs per path.** [`DecoratedGraph::unit_interval`] (the
//!   cell-below-path rule of [CM]/[AS]) and [`DecoratedGraph::from_area`] (the
//!   dinv-faithful one) are *different graphs*: `a = (0,0)` has no cell below
//!   the path but its two rows form a primary dinv pair. Both are real objects
//!   and each has its own job here.
//!
//! ## The routes
//!
//! **R1**, [`llt_g`] — standard fillings bucketed by descent set, [HHL] (82).
//! The reference engine, and the one that emits the fundamental
//! quasisymmetric expansion ([`llt_fundamental`]) as a by-product. Cost is
//! `#SYT(ν)` for *all* monomials at once, where direct semistandard
//! enumeration pays one walk per content.
//!
//! **R2**, [`llt_gtilde`] and friends — β-number ribbon strips on the abacus.
//! The engine for the ribbon side, decomposed by runner: a bead moves `+k`, so
//! it never leaves its residue class, and a horizontal strip is a choice of
//! *prefix of a maximal block* on each runner independently. That is what
//! keeps this out of the `C(rows, m)` subset enumeration the naive reading
//! suggests — for λ = (kn) the subset count is `C(kn, n)` where the block count
//! is one.
//!
//! **R3**, [`llt_kl_column`] — [KMS] Fock-space straightening. Emits a whole
//! *column* of the Schur-expansion table (one λ, every shape μ), which is the
//! transpose of what tableau enumeration produces, and whose entries are
//! parabolic affine Kazhdan–Lusztig polynomials ([LT] Thm 4.2).
//!
//! ## Range
//!
//! Over a fixed-width `C` this family refuses rather than wrapping past its
//! wall (`docs/policies/failure.md`, R3), and **this is the one `(q,t)` family
//! in the crate whose wall a caller reaches cheaply** — so it is a measured
//! degree rather than a projection, and it is the one that earned an
//! escalation ladder. Through the Python boundary the single-shape entry
//! points escalate: the fixed-width pass reports, and the same generic code
//! re-runs over `BigInt`, so a caller there has no wall at all. A Rust caller
//! choosing `C = i128` still meets the degrees below.
//!
//! [`llt_h`] at μ = 1ⁿ overflows `i128` at the degrees below, and the
//! arithmetic wall arrives before any runtime obstacle:
//!
//! ```text
//!   k = 2   n = 124        k = 4   n = 71
//!   k = 3   n = 87
//! ```
//!
//! The wall falls as `k` rises: a larger ribbon level packs more coefficient
//! into the same degree. At k = 3 the widest coefficient is 127 bits at n = 86
//! and the next degree overflows in the accumulation, so this bounds the
//! *answers*, not merely an intermediate.
//!
//! The table entry points are stopped by runtime long before this:
//! [`llt_h_table`] gains ~2.6 bits per degree and would reach 127 bits near
//! n ≈ 54, and [`llt_gtilde_table`] ~2.5 near n ≈ 55, against tables that stop
//! finishing around n = 17–20. Range here is therefore a statement about the
//! *entry point*, not about the family.
//!
//! Degrees, slopes and the harness are in `docs/record/failure-and-overflow.md`
//! (`examples/probe_qt_walls.rs`).
//!
//! ## References
//!
//! - **[LLT]** Lascoux, Leclerc, Thibon, *Ribbon tableaux, Hall–Littlewood
//!   functions, quantum affine algebras and unipotent varieties*,
//!   [arXiv:q-alg/9512031](https://arxiv.org/abs/q-alg/9512031) — spin (15),
//!   cospin (24)–(25), `G̃` (26), `H̃` (27), `H` (28); Thm 6.6; Ex 6.8.
//! - **[LT]** Leclerc, Thibon, *Littlewood–Richardson coefficients and
//!   Kazhdan–Lusztig polynomials*,
//!   [arXiv:math/9809122](https://arxiv.org/abs/math/9809122) — the
//!   spin-generating `G` (their (43)), Ex 4.1, Lemma 6.5 (β-set strips).
//! - **[KMS]** Kashiwara, Miwa, Stern, *Decomposition of q-deformed Fock
//!   spaces*, [arXiv:q-alg/9508006](https://arxiv.org/abs/q-alg/9508006) — the
//!   **normative** straightening rules (43)/(45). [LLT] §7's printing of the
//!   same rules carries two misprints.
//! - **[HHL]** Haglund, Haiman, Loehr, *A combinatorial formula for Macdonald
//!   polynomials*, [arXiv:math/0409538](https://arxiv.org/abs/math/0409538) —
//!   Def 3.2 (the tuple model), the standardization identity (82), and
//!   `H̃_μ = Σ_D q^{−a} t^{maj} G_{ν(μ,D)}`.
//! - **[DA]** D'Adderio, *e-positivity of vertical strip LLT polynomials*,
//!   [arXiv:1906.02633](https://arxiv.org/abs/1906.02633) — Remark 2.2 (the
//!   tuple reversal), Ex 5.6.
//! - **[AS]** Alexandersson, Sulzgruber, *A combinatorial expansion of
//!   vertical-strip LLT polynomials in the basis of elementary symmetric
//!   functions*, [arXiv:2004.09198](https://arxiv.org/abs/2004.09198) — the
//!   orientation/e-expansion formula, Ex 6.1.
//! - **[CM]** Carlsson, Mellit, *A proof of the shuffle conjecture*,
//!   [arXiv:1508.06239](https://arxiv.org/abs/1508.06239) — Prop 3.5, the
//!   chromatic bridge.
//! - **[AP]** Alexandersson, Panova, *LLT polynomials, chromatic quasisymmetric
//!   functions and graphs with cycles*,
//!   [arXiv:1705.10353](https://arxiv.org/abs/1705.10353) — Def 16 (the
//!   decorated-graph presentation), Lemma 47 (the chromatic bridge, with
//!   [CM] Prop 3.5), and Conj 25 on unicellular e-positivity.
//!
//! `docs/record/llt.md` carries the measured record: the ladders, the
//! profiling, and the formula-by-formula verification against Sage.
//!
//! [LLT]: https://arxiv.org/abs/q-alg/9512031
//! [LT]: https://arxiv.org/abs/math/9809122
//! [KMS]: https://arxiv.org/abs/q-alg/9508006
//! [HHL]: https://arxiv.org/abs/math/0409538
//! [DA]: https://arxiv.org/abs/1906.02633
//! [AP]: https://arxiv.org/abs/1705.10353
//! [AS]: https://arxiv.org/abs/2004.09198
//! [CM]: https://arxiv.org/abs/1508.06239
//! [HRW]: https://arxiv.org/abs/1509.07058

// Every `as` in this module converts a *cell coordinate, component index, or
// q-exponent* — bounded by |λ|, by the number of components, and by the ribbon
// level respectively, all `u32` where they are stored. None of them carries a
// coefficient, and none can: coefficients here are `QtPoly<C>` over a generic
// `C: Ring`, and a generic parameter cannot be `as`-cast at all. That is what
// makes a module-level allow safe where a per-site one would normally be
// required — a value-carrying narrowing cannot be written in this module
// without first introducing a concrete integer coefficient
// (`docs/policies/failure.md`, R5).
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]

use std::collections::{BTreeMap, HashMap};

use crate::coeff::{QAlgebra, Ring};
use crate::partition::Partition;
use crate::qt::QtPoly;
use crate::sym::{Monomial, PowerSum, Schur, SymFn};

// ============================================================== the tuple model

/// One cell of a [`SkewTuple`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Cell {
    comp: u32,
    row: i32,
    col: i32,
    /// `col − row + offset`, the classical content.
    content: i32,
}

/// A tuple of skew shapes with content offsets — the \[HHL\] Def 3.2 object.
///
/// Permuting the components changes `G_ν`: two cells on one content attack in
/// the order earlier component first, and the reversed pair does not. Row and
/// column are signed because the ribbons [`htilde_by_llt`] builds start at
/// column 0 and run left.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SkewTuple {
    cells: Vec<Cell>,
    /// Content offset per component, kept so [`conjugate`](Self::conjugate) can
    /// rebuild.
    offsets: Vec<i32>,
    /// Where each cell sits in reading order (content ↑, component ↑, row ↑).
    reading: Vec<u32>,
    /// Attacking pairs `(a, b)`, `a` earlier than `b` in reading order.
    attack: Vec<(u32, u32)>,
    /// `T[a] ≤ T[b]`: the right neighbor inside a component.
    weak: Vec<(u32, u32)>,
    /// `T[a] < T[b]`: the neighbor one row down inside a component.
    strict: Vec<(u32, u32)>,
    /// Bit `b` of `attack_mask[a]` iff `(a, b)` attacks. The standard-filling
    /// walk's `inv` delta is one `popcount` against the assigned set, where the
    /// adjacency-list form was a pointer chase and a loop — and that walk is
    /// nearly all of the by-path shuffle refinement (`docs/record/llt.md`).
    attack_mask: Vec<u64>,
    /// Bit `p` of `pred_mask[c]` iff `p` is an immediate predecessor of `c`
    /// under weak+strict. A cell is available exactly when
    /// `pred_mask[c] & !assigned == 0`, which replaces the in-degree counters
    /// and the `avail` stack with two bit ops.
    pred_mask: Vec<u64>,
}

impl SkewTuple {
    /// From explicit cell sets: `(cells, offset)` per component, cells as
    /// `(row, col)` in any integer coordinates.
    ///
    /// The general constructor — semistandardness is read off cell *adjacency*
    /// (right neighbor weak, next row down strict), so any set of cells works
    /// and skew shapes are just the common case.
    ///
    /// # Panics
    ///
    /// Panics if the components hold more than [`MAX_CELLS`] cells in total —
    /// the width of the `u64` attack masks, a representation limit rather than
    /// a mathematical one.
    pub fn from_cells(comps: &[(Vec<(i32, i32)>, i32)]) -> Self {
        let mut cells = Vec::new();
        let mut offsets = Vec::with_capacity(comps.len());
        for (k, (cs, off)) in comps.iter().enumerate() {
            offsets.push(*off);
            for &(row, col) in cs {
                cells.push(Cell {
                    comp: k as u32,
                    row,
                    col,
                    content: col - row + off,
                });
            }
        }
        let n = cells.len();

        // Reading order. Ties in content are broken by component then row, and
        // that tie-break is what makes [HHL]'s standardization an identity
        // rather than a convention — see `syt_buckets`.
        let mut order: Vec<u32> = (0..n as u32).collect();
        order.sort_by_key(|&i| {
            let c = cells[i as usize];
            (c.content, c.comp, c.row)
        });
        let mut reading = vec![0u32; n];
        for (pos, &i) in order.iter().enumerate() {
            reading[i as usize] = pos as u32;
        }

        // Attacking pairs, between distinct components only.
        //
        // The bit masks below cap a tuple at 64 cells. That is the same cap
        // `syt_buckets`'s descent mask already imposed, so it is not a new
        // limit — but it is now enforced at construction, and says so.
        assert!(
            n <= MAX_CELLS,
            "a SkewTuple holds at most {MAX_CELLS} cells, got {n}; this is a \
             representation limit, not a mathematical one"
        );
        let mut attack = Vec::new();
        let mut attack_mask = vec![0u64; n];
        for a in 0..n {
            for b in 0..n {
                let (x, y) = (cells[a], cells[b]);
                let attacks = (y.content == x.content && x.comp < y.comp)
                    || (y.content == x.content + 1 && y.comp < x.comp);
                if attacks {
                    attack.push((a as u32, b as u32));
                    attack_mask[a] |= 1u64 << b;
                }
            }
        }

        // Semistandardness covers, by adjacency inside a component.
        let index: HashMap<(u32, i32, i32), u32> = cells
            .iter()
            .enumerate()
            .map(|(i, c)| ((c.comp, c.row, c.col), i as u32))
            .collect();
        let mut weak = Vec::new();
        let mut strict = Vec::new();
        let mut pred_mask = vec![0u64; n];
        for (i, c) in cells.iter().enumerate() {
            if let Some(&j) = index.get(&(c.comp, c.row, c.col + 1)) {
                weak.push((i as u32, j));
                pred_mask[j as usize] |= 1u64 << i;
            }
            if let Some(&j) = index.get(&(c.comp, c.row + 1, c.col)) {
                strict.push((i as u32, j));
                pred_mask[j as usize] |= 1u64 << i;
            }
        }

        SkewTuple {
            cells,
            offsets,
            reading,
            attack,
            weak,
            strict,
            attack_mask,
            pred_mask,
        }
    }

    /// From skew shapes `outer/inner`, one content offset each.
    ///
    /// # Panics
    ///
    /// Panics if `skews` and `offsets` differ in length, if any `inner ⊄
    /// outer`, or if the shapes hold more than [`MAX_CELLS`] cells between
    /// them.
    pub fn from_skews(skews: &[(Partition, Partition)], offsets: &[i32]) -> Self {
        assert_eq!(skews.len(), offsets.len(), "one offset per component");
        let comps: Vec<(Vec<(i32, i32)>, i32)> = skews
            .iter()
            .zip(offsets)
            .map(|((outer, inner), &off)| {
                assert!(
                    outer.contains(inner),
                    "a skew shape needs inner ⊆ outer: {inner} ⊄ {outer}"
                );
                let cells = (0..outer.len())
                    .flat_map(|r| (inner.part(r)..outer.part(r)).map(move |c| (r as i32, c as i32)))
                    .collect();
                (cells, off)
            })
            .collect();
        Self::from_cells(&comps)
    }

    /// From straight shapes, one content offset each.
    ///
    /// # Panics
    ///
    /// Panics if `shapes` and `offsets` differ in length, or if the shapes hold
    /// more than [`MAX_CELLS`] cells between them.
    pub fn from_partitions(shapes: &[Partition], offsets: &[i32]) -> Self {
        let skews: Vec<(Partition, Partition)> = shapes
            .iter()
            .map(|s| (s.clone(), Partition::default()))
            .collect();
        Self::from_skews(&skews, offsets)
    }

    /// The k-quotient of λ with **offsets zero** — the verified normal form of
    /// the quotient dictionary.
    ///
    /// `None` when λ has no k-ribbon tableaux (nonempty k-core), which is
    /// exactly when the dictionary has nothing to say. Note what the caller
    /// still owes: `G` of this tuple carries a forced `q^{min inv}` floor that
    /// `G̃^(k)_λ` does not — see [`llt_min_inv`] and the module docs.
    pub fn quotient(lambda: &Partition, k: u32) -> Option<Self> {
        if !lambda.has_empty_k_core(k) {
            return None;
        }
        let shapes = lambda.k_quotient(k);
        let offsets = vec![0i32; shapes.len()];
        Some(Self::from_partitions(&shapes, &offsets))
    }

    /// The vertical-strip tuple of a Dyck path given by its area sequence.
    ///
    /// Components are the maximal `+1`-runs of the area sequence, each a single
    /// column; row `i`'s cell sits at content `−a_i`. Components are listed in
    /// **reverse row order** (\[DA\] Remark 2.2) — the one order under which
    /// \[HHL\] attacking inversions and \[HRW\] `dinv` agree pointwise, not
    /// merely in total.
    pub fn from_area(area: &[u32]) -> Self {
        let n = area.len();
        let mut comps: Vec<(Vec<(i32, i32)>, i32)> = Vec::new();
        let mut start = 0usize;
        for i in 1..=n {
            if i == n || area[i] != area[i - 1] + 1 {
                let cells = (start..i).map(|r| ((r - start) as i32, 0i32)).collect();
                comps.push((cells, -(area[start] as i32)));
                start = i;
            }
        }
        comps.reverse();
        Self::from_cells(&comps)
    }

    /// The conjugate tuple: transpose every component, negate every offset,
    /// reverse the component order.
    ///
    /// The shape the ω-duality law wants,
    /// `G_{ν'}(x; q) = q^{A(ν)} ω G_ν(x; 1/q)` with `A(ν)` the attacking-pair
    /// count. Offset negation is the law that keeps contents negated
    /// cell-for-cell; it is verified at offset 0 (see the ω-duality test) and
    /// is the only extension of that consistent with `content ↦ −content`.
    pub fn conjugate(&self) -> Self {
        let ncomps = self.offsets.len();
        let mut comps: Vec<(Vec<(i32, i32)>, i32)> = (0..ncomps)
            .map(|k| (Vec::new(), -self.offsets[k]))
            .collect();
        for c in &self.cells {
            comps[c.comp as usize].0.push((c.col, c.row));
        }
        comps.reverse();
        Self::from_cells(&comps)
    }

    /// `A(ν)`, the number of attacking pairs — the twist in the ω-duality law.
    pub fn attacking_pairs(&self) -> usize {
        self.attack.len()
    }

    /// The number of cells, i.e. the degree of `G_ν`.
    pub fn size(&self) -> usize {
        self.cells.len()
    }

    /// The number of components.
    pub fn components(&self) -> usize {
        self.offsets.len()
    }

    /// Standard fillings bucketed by descent set: `(mask, counts by inv)`.
    ///
    /// \[HHL\] (82) is `G_ν = Σ_{S ∈ SYT(ν)} q^{inv(S)} Q_{n,D(S)}`, so these
    /// buckets *are* the fundamental quasisymmetric expansion. Bit `i−1` of
    /// `mask` is set iff `i` is a descent, meaning `i+1` sits earlier than `i`
    /// in reading order.
    ///
    /// ## Why this is written in bit masks
    ///
    /// This walk is the module's hot spot: sampling `nabla_e_by_path(9)` puts
    /// nearly every sample in it, with the area enumeration, the tuple
    /// construction and the allocator sharing what is left
    /// (`docs/record/llt.md`). So the inner loop is where the module's headline
    /// number lives, and it is written accordingly:
    ///
    /// - **Availability** is `pred_mask[c] & !assigned == 0`. The textbook form
    ///   keeps in-degree counters and an `avail` stack, and pays a decrement
    ///   loop plus a stack splice on the way down *and* on the way back up; two
    ///   bit ops replace all of it, and nothing is allocated or undone.
    /// - **The `inv` delta** is `(attack_mask[c] & assigned).count_ones()`.
    ///   Assigning the value `s` to `c` can only complete attacking pairs `(c,
    ///    b)` with `b` already filled — an unfilled `b` gets a larger value and
    ///   is counted from its own side — so the delta is a popcount where the
    ///   adjacency-list form was a pointer chase and a loop.
    /// - **The descent bit** compares against the previous value's position
    ///   only, so it rides down the recursion as a `u32` instead of an array.
    ///
    /// The leaf goes through [`Sink`], monomorphized, so that the flat-table
    /// and hash-map accumulators below cost the same as writing either one
    /// inline.
    fn syt_buckets(&self) -> Vec<(u64, Vec<u128>)> {
        self.syt_buckets_within(FLAT_TABLE_BUDGET)
    }

    /// [`syt_buckets`](Self::syt_buckets) with the flat table's size budget
    /// exposed, so a test can drive the same tuple down both sinks.
    fn syt_buckets_within(&self, budget: usize) -> Vec<(u64, Vec<u128>)> {
        let n = self.cells.len();
        if n == 0 {
            return vec![(0u64, vec![1u128])];
        }
        let width = self.attack.len() + 1; // inv ≤ #attacking pairs
        let masks = 1usize << (n - 1);
        // A hash per leaf was 6% of the R1 profile, and there are `#SYT` leaves.
        // Direct-indexing the descent mask removes it outright, but the table is
        // `2^{n−1} × width`, so it is only taken when that fits a fixed budget —
        // past which the map is the honest fallback rather than a memory cliff.
        // Saturating is the *correct* comparison here, not a concession: a
        // product that overflows `usize` is one that exceeds the budget, and
        // saturation routes it to the fallback exactly as the true value would
        // (R4). `checked_mul` would say the same thing more loudly for no gain.
        let mut out = if masks.saturating_mul(width) <= budget {
            let mut sink = FlatSink {
                table: vec![0u128; masks * width],
                width,
            };
            self.walk(n, &mut sink);
            sink.table
                .chunks(width)
                .enumerate()
                .filter(|(_, row)| row.iter().any(|&c| c != 0))
                .map(|(mask, row)| (mask as u64, row.to_vec()))
                .collect()
        } else {
            let mut sink = MapSink {
                buckets: Default::default(),
            };
            self.walk(n, &mut sink);
            sink.buckets.into_iter().collect::<Vec<_>>()
        };
        out.sort_unstable_by_key(|e| e.0);
        out
    }

    fn walk<S: Sink>(&self, n: usize, sink: &mut S) {
        let all = if n == 64 { u64::MAX } else { (1u64 << n) - 1 };
        self.walk_rec(1, n, all, 0, 0, 0, 0, sink);
    }

    #[allow(clippy::too_many_arguments)]
    fn walk_rec<S: Sink>(
        &self,
        step: usize,
        n: usize,
        all: u64,
        assigned: u64,
        prev_pos: u32,
        inv: u32,
        mask: u64,
        sink: &mut S,
    ) {
        if step > n {
            sink.hit(mask, inv);
            return;
        }
        let mut cand = all & !assigned;
        while cand != 0 {
            let c = cand.trailing_zeros();
            cand &= cand - 1;
            let cell = c as usize;
            if self.pred_mask[cell] & !assigned != 0 {
                continue;
            }
            let delta = (self.attack_mask[cell] & assigned).count_ones();
            let pos = self.reading[cell];
            let bit = if step >= 2 && pos < prev_pos {
                1u64 << (step - 2)
            } else {
                0
            };
            self.walk_rec(
                step + 1,
                n,
                all,
                assigned | 1u64 << c,
                pos,
                inv + delta,
                mask | bit,
                sink,
            );
        }
    }

    /// `(min inv, max inv)` over standard fillings, without building the
    /// buckets.
    ///
    /// The floor and ceiling are wanted far more often than the whole
    /// expansion — the quotient dictionary needs the floor on every shape it
    /// sweeps — and the walk that produces them need not accumulate anything.
    fn inv_range(&self) -> (u32, u32) {
        if self.cells.is_empty() {
            return (0, 0);
        }
        let mut sink = RangeSink {
            lo: u32::MAX,
            hi: 0,
        };
        self.walk(self.cells.len(), &mut sink);
        (sink.lo.min(sink.hi), sink.hi)
    }
}

/// Where the standard-filling walk deposits a leaf. Monomorphized per
/// accumulator, so the walk pays no dispatch for having three of them.
trait Sink {
    fn hit(&mut self, mask: u64, inv: u32);
}

/// Direct-indexed `(mask, inv)` counts — one add, no hashing.
struct FlatSink {
    table: Vec<u128>,
    width: usize,
}

impl Sink for FlatSink {
    #[inline]
    fn hit(&mut self, mask: u64, inv: u32) {
        self.table[mask as usize * self.width + inv as usize] += 1;
    }
}

/// The largest flat descent-mask table [`SkewTuple::syt_buckets`] will build,
/// in `u128` entries. Past it the map fallback takes over.
const FLAT_TABLE_BUDGET: usize = 1 << 20;

/// The fallback for tuples whose descent-mask table would not fit.
///
/// [`hit`](Sink::hit) runs once per standard filling, so the per-key hash the
/// flat table exists to avoid is paid on every leaf here. The key is a bare
/// `u64`, which is what [`crate::fasthash`] is for: SipHash was a third of the
/// runtime on the tuples that land here (`docs/record/llt.md`).
struct MapSink {
    buckets: crate::fasthash::Map<u64, Vec<u128>>,
}

impl Sink for MapSink {
    fn hit(&mut self, mask: u64, inv: u32) {
        let counts = self.buckets.entry(mask).or_default();
        if counts.len() <= inv as usize {
            counts.resize(inv as usize + 1, 0);
        }
        counts[inv as usize] += 1;
    }
}

/// Just the extremes, for [`llt_min_inv`] / [`llt_max_inv`].
struct RangeSink {
    lo: u32,
    hi: u32,
}

impl Sink for RangeSink {
    #[inline]
    fn hit(&mut self, _mask: u64, inv: u32) {
        self.lo = self.lo.min(inv);
        self.hi = self.hi.max(inv);
    }
}

/// The mask of descent positions a monomial `x^μ` tolerates: bit `s−1` for each
/// proper partial sum `s` of μ.
///
/// `[x^μ] Q_{n,D} = 1` exactly when `D` is contained in this set, so the
/// monomial expansion is a subset filter over the buckets.
fn partial_sum_mask(mu: &Partition) -> u64 {
    let mut mask = 0u64;
    let mut acc = 0u32;
    for &p in mu.parts().iter().take(mu.len().saturating_sub(1)) {
        acc += p;
        mask |= 1u64 << (acc - 1);
    }
    mask
}

/// `G_ν(x; q)` in the monomial basis, in the **raw** inv grading.
///
/// The floor is not divided out: `min_T inv(T)` can be positive and callers
/// that want the cospin normalization must divide by `q^{llt_min_inv(ν)}`
/// themselves. That is deliberate — the floor is real data about ν (see the
/// module docs), and hiding it is how the quotient dictionary gets misread.
pub fn llt_g<C: Ring>(nu: &SkewTuple) -> Monomial<QtPoly<C>> {
    let buckets = nu.syt_buckets();
    let mut out = Monomial::zero();
    for mu in crate::partitions_of(nu.size() as u32) {
        crate::interrupt::poll();
        let allowed = partial_sum_mask(&mu);
        let mut poly = QtPoly::zero();
        for (mask, counts) in &buckets {
            if mask & !allowed != 0 {
                continue;
            }
            for (inv, c) in counts.iter().enumerate() {
                if *c != 0 {
                    poly.add_term(inv as u32, 0, C::from_u128(*c));
                }
            }
        }
        out.add_term(mu, poly);
    }
    out
}

/// `min_T inv(T)` over semistandard fillings — the forced `q`-floor of the
/// tuple model.
///
/// Read off the standard fillings, which is legitimate because standardization
/// preserves `inv` (\[HHL\] (82)): every semistandard filling has a standard
/// one with the same `inv`, and standard fillings are themselves semistandard,
/// so the two minima coincide.
pub fn llt_min_inv(nu: &SkewTuple) -> u32 {
    nu.inv_range().0
}

/// `max_T inv(T)`, by the same argument as [`llt_min_inv`].
pub fn llt_max_inv(nu: &SkewTuple) -> u32 {
    nu.inv_range().1
}

/// The **fundamental quasisymmetric** expansion of `G_ν`, as
/// `(composition, coefficient)` pairs sorted by composition.
///
/// The buckets of \[HHL\] (82) read directly: a descent set `D ⊆ [n−1]` is the
/// composition of `n` whose partial sums are `D`. The crate has no QSym type
/// and does not need one for this — the compositions carry their own meaning
/// and nothing here multiplies them.
pub fn llt_fundamental<C: Ring>(nu: &SkewTuple) -> Vec<(Vec<u32>, QtPoly<C>)> {
    let n = nu.size() as u32;
    let mut out = Vec::new();
    for (mask, counts) in nu.syt_buckets() {
        crate::interrupt::poll();
        let mut comp = Vec::new();
        let mut prev = 0u32;
        for i in 1..n {
            if mask >> (i - 1) & 1 == 1 {
                comp.push(i - prev);
                prev = i;
            }
        }
        if n > 0 {
            comp.push(n - prev);
        }
        let mut poly = QtPoly::zero();
        for (inv, c) in counts.iter().enumerate() {
            if *c != 0 {
                poly.add_term(inv as u32, 0, C::from_u128(*c));
            }
        }
        out.push((comp, poly));
    }
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

// ============================================================= the ribbon model

/// An abacus state: bit `b` is set iff `b` is a β-number of the **conjugate**
/// shape.
///
/// `u128` because the whole-degree work at `k·n ≈ 60` needs β-numbers up to
/// `ℓ(λ) + λ₁`, and because every operation the strip enumeration performs —
/// occupancy, the `+k` move, the crossing count — is then a bit op.
type Abacus = u128;

/// The highest β-number this representation holds.
const ABACUS_BITS: u32 = 128;

/// The abacus of λ with `rows` beads.
fn abacus_of(lambda: &Partition, rows: usize) -> Abacus {
    let conj = lambda.conjugate();
    let beta = conj.beta_numbers(rows);
    let top = beta.first().copied().unwrap_or(0);
    assert!(
        top < ABACUS_BITS,
        "β-number {top} does not fit a {ABACUS_BITS}-bit abacus"
    );
    beta.iter().fold(0u128, |acc, &b| acc | 1u128 << b)
}

/// The shape whose conjugate's β-numbers are the set bits of `beta`.
fn shape_of(beta: Abacus) -> Partition {
    let rows = beta.count_ones() as usize;
    let mut desc = Vec::with_capacity(rows);
    let mut b = beta;
    while b != 0 {
        let top = ABACUS_BITS - 1 - b.leading_zeros();
        desc.push(top);
        b &= !(1u128 << top);
    }
    Partition::from_beta_numbers(&desc).conjugate()
}

/// Is the shape of `beta` contained in the shape of `target`?
///
/// Containment of partitions is elementwise domination of β-numbers at equal
/// bead counts, and conjugation preserves containment, so this reads the two
/// bitmasks without materializing either partition. The strip walk calls it
/// once per candidate strip, which makes it the pruning hot path.
///
/// **Only the differing bits are visited.** For equal-size bead sets,
/// `β(ν)_j ≤ β(λ)_j` for every `j` is the same as
/// `|ν ∩ [x,∞)| ≤ |λ ∩ [x,∞)|` for every threshold `x`, and that count
/// difference only changes at a position where the two disagree. So walking
/// `beta ^ target` from the top with a running `+1` for target-only and `−1`
/// for beta-only, and failing the moment it goes negative, decides containment
/// in `popcount(beta ^ target)` steps — two per moved bead — where marching
/// both bead lists in lockstep took one step per bead. At k = 3, n = 13 that is
/// 2 iterations instead of 39 for a weight-1 strip.
fn abacus_contained(beta: Abacus, target: Abacus) -> bool {
    debug_assert_eq!(beta.count_ones(), target.count_ones());
    let mut d = beta ^ target;
    let mut acc = 0i32;
    while d != 0 {
        let b = ABACUS_BITS - 1 - d.leading_zeros();
        d &= !(1u128 << b);
        if target >> b & 1 == 1 {
            acc += 1;
        } else {
            acc -= 1;
            if acc < 0 {
                return false;
            }
        }
    }
    true
}

/// Reusable buffers for the strip enumeration.
///
/// [`for_each_strip_up`] runs once per (state, weight) in the ribbon walk, and
/// allocating its runner, block and suffix-sum vectors per call put `malloc`
/// and `free` between them above `strip_rec` itself in the R2 profile
/// (`docs/record/llt.md`). Blocks are `(offset, len)` into one flat bead vector
/// rather than a `Vec<Vec<u32>>`, so a call touches three buffers and allocates
/// nothing.
#[derive(Default)]
struct StripScratch {
    /// Bead positions grouped by runner, ascending within each runner.
    beads: Vec<u32>,
    /// `(offset into beads, length)` per maximal block.
    blocks: Vec<(u32, u32)>,
    /// Suffix sums of block lengths, for the weight pruning.
    room: Vec<u32>,
    /// `bits ≡ r (mod k)` per runner, rebuilt only when `k` changes — which is
    /// once per walk, since a walk has one level.
    runner_masks: Vec<Abacus>,
    /// The `k` `runner_masks` was built for. `0` is never a valid level, so a
    /// default scratch always rebuilds.
    runner_k: u32,
}

/// Every horizontal k-ribbon strip of weight `m` that can be **added** to
/// `beta`, as `(new state, spin_LT)`.
///
/// `spin_LT` is the integral spin `Σ (h−1) = 2·s` of \[LT\], which is what
/// keeps the walk in ℤ; the halvings to \[LLT\]'s `s` and `s̃` happen once at
/// the end, in [`regrade`].
///
/// The enumeration is decomposed by runner (\[LT\] Lemma 6.5 read on the
/// abacus). A bead moves `+k`, so it stays in its residue class. Within a
/// runner, moving a set of beads up one slot each keeps them distinct exactly
/// when the set is a **prefix of a maximal block** of occupied slots. Move any
/// bead with an occupied slot above it and the two collide; a maximal block's
/// top always has room. So a strip is one prefix length per block, and
/// the weights add. The naive reading of the same lemma enumerates all
/// `C(rows, m)` subsets and filters; for λ = (kn) that is `C(kn, n)` candidates
/// where this is one.
///
/// Crossings — the unmoved beads a moving bead passes — come out as `k−1`
/// popcounts: an unmoved bead lies strictly between `B` and `B+k` iff it sits
/// at `B+i` for some `0 < i < k`.
// Reached only from the tests since the R2 profiling work moved the live path
// elsewhere, and kept for two reasons: it is a second, independent enumerator
// for the strip lemma, and its doc carries the block-prefix derivation that
// keeps this out of the `C(rows, m)` subset enumeration.
#[allow(dead_code)]
fn for_each_strip_up(
    beta: Abacus,
    k: u32,
    m: u32,
    sc: &mut StripScratch,
    visit: &mut impl FnMut(Abacus, u32),
) {
    collect_blocks(beta, k, sc);
    // How many beads the remaining blocks can still supply, for pruning.
    sc.room.clear();
    sc.room.resize(sc.blocks.len() + 1, 0);
    for i in (0..sc.blocks.len()).rev() {
        sc.room[i] = sc.room[i + 1] + sc.blocks[i].1;
    }
    strip_rec(beta, k, &sc.beads, &sc.blocks, &sc.room, 0, m, 0, m, visit);
}

/// The maximal blocks of `beta`, per runner, into `sc`.
///
/// Driven off `beta & runner_mask[r]`, so it visits the `rows` occupied
/// positions rather than every position up to the top bead. The abacus runs at
/// roughly half density, and this was 7% of the R2 profile
/// (`docs/record/llt.md`).
fn collect_blocks(beta: Abacus, k: u32, sc: &mut StripScratch) {
    if sc.runner_k != k {
        sc.runner_masks.clear();
        for r in 0..k {
            let mut mask: Abacus = 0;
            let mut g = r;
            while g < ABACUS_BITS {
                mask |= 1u128 << g;
                g += k;
            }
            sc.runner_masks.push(mask);
        }
        sc.runner_k = k;
    }
    sc.beads.clear();
    sc.blocks.clear();
    for r in 0..k as usize {
        let mut b = beta & sc.runner_masks[r];
        let mut start = sc.beads.len() as u32;
        let mut len = 0u32;
        let mut prev: Option<u32> = None;
        while b != 0 {
            let g = b.trailing_zeros();
            b &= b - 1;
            if prev.is_some_and(|p| g != p + k) {
                sc.blocks.push((start, len));
                start = sc.beads.len() as u32;
                len = 0;
            }
            sc.beads.push(g);
            len += 1;
            prev = Some(g);
        }
        if len > 0 {
            sc.blocks.push((start, len));
        }
    }
}

/// Every horizontal k-ribbon strip from `beta` of **every** weight `1 … max_w`,
/// as `(weight, new state, spin_LT)`.
///
/// The same block tree as [`for_each_strip_up`], but the weight falls out at
/// the leaf instead of being fixed in advance. That matters because the ribbon
/// walk wants every weight from each state: asking one weight at a time
/// re-collected the blocks and re-walked all the shared internal nodes, once
/// per weight. `strip_rec` was 70% of the R2 profile once the allocator was
/// dealt with (`docs/record/llt.md`), and this is where most of it came from.
fn for_each_strip_any(
    beta: Abacus,
    k: u32,
    max_w: u32,
    sc: &mut StripScratch,
    visit: &mut impl FnMut(u32, Abacus, u32),
) {
    collect_blocks(beta, k, sc);
    strip_any_rec(beta, k, &sc.beads, &sc.blocks, 0, 0, max_w, 0, visit);
}

#[allow(clippy::too_many_arguments)]
fn strip_any_rec(
    beta: Abacus,
    k: u32,
    beads: &[u32],
    blocks: &[(u32, u32)],
    bi: usize,
    w: u32,
    max_w: u32,
    moved: Abacus,
    visit: &mut impl FnMut(u32, Abacus, u32),
) {
    if bi == blocks.len() {
        if w >= 1 {
            let unmoved = beta & !moved;
            let shifted = moved << k;
            debug_assert_eq!(shifted & unmoved, 0, "a block prefix never collides");
            let mut cross = 0u32;
            for i in 1..k {
                cross += ((moved << i) & unmoved).count_ones();
            }
            visit(w, unmoved | shifted, (k - 1) * w - cross);
        }
        return;
    }
    let (off, len) = blocks[bi];
    let top = len.min(max_w - w);
    let mut mv = moved;
    for j in 0..=top {
        if j > 0 {
            mv |= 1u128 << beads[(off + len - j) as usize];
        }
        strip_any_rec(beta, k, beads, blocks, bi + 1, w + j, max_w, mv, visit);
    }
}

#[allow(clippy::too_many_arguments)]
// The recursion behind `for_each_strip_up`, and dead exactly when it is.
#[allow(dead_code)]
fn strip_rec(
    beta: Abacus,
    k: u32,
    beads: &[u32],
    blocks: &[(u32, u32)],
    room: &[u32],
    bi: usize,
    remaining: u32,
    moved: Abacus,
    m: u32,
    visit: &mut impl FnMut(Abacus, u32),
) {
    if remaining > room[bi] {
        return;
    }
    if bi == blocks.len() {
        if remaining == 0 {
            let unmoved = beta & !moved;
            let shifted = moved << k;
            debug_assert_eq!(shifted & unmoved, 0, "a block prefix never collides");
            let mut cross = 0u32;
            for i in 1..k {
                cross += ((moved << i) & unmoved).count_ones();
            }
            visit(unmoved | shifted, (k - 1) * m - cross);
        }
        return;
    }
    let (off, len) = blocks[bi];
    let top = len.min(remaining);
    let mut mv = moved;
    for j in 0..=top {
        if j > 0 {
            // The top `j` beads of a block are its last `j` entries, and the
            // loop adds them one at a time from the top down.
            mv |= 1u128 << beads[(off + len - j) as usize];
        }
        strip_rec(
            beta,
            k,
            beads,
            blocks,
            room,
            bi + 1,
            remaining - j,
            mv,
            m,
            visit,
        );
    }
}

/// One node of the weight walk: which shapes are reachable, and with what spin.
///
/// [`crate::fasthash`]'s hasher rather than SipHash: keys are a single small
/// structured integer and there are a great many of them, which is the exact
/// case that module was extracted for.
type States<C> = crate::fasthash::Map<Abacus, QtPoly<C>>;

/// The k-ribbon tableau walk, in the \[LT\] spin grading.
///
/// Builds up from the empty shape by horizontal strips of **weakly decreasing**
/// weight, so the weight word of a leaf is a partition and the recursion tree
/// is the partition trie — every weight *prefix* is walked once and shared by
/// all the partitions extending it. That sharing is what the whole-degree
/// entry points are for: `μ = (n)` is 94–100% of a degree in the incumbent
/// (`docs/record/llt.md`) precisely because per-shape morphisms
/// recompute what a trie shares.
///
/// `target` prunes to chains through subshapes of one λ, which is exact —
/// a chain to λ never leaves `⊆ λ`.
struct RibbonWalk<'a, C: Ring> {
    k: u32,
    target: Option<Abacus>,
    weight: Vec<u32>,
    out: HashMap<Partition, Monomial<QtPoly<C>>>,
    /// The shape to keep, when only one is wanted.
    keep: Option<&'a Partition>,
}

impl<C: Ring> RibbonWalk<'_, C> {
    fn step(&mut self, states: &States<C>, remaining: u32, max_w: u32, sc: &mut StripScratch) {
        if remaining == 0 {
            let weight = Partition::from_sorted(self.weight.clone());
            for (state, poly) in states {
                let shape = shape_of(*state);
                if let Some(keep) = self.keep {
                    if &shape != keep {
                        continue;
                    }
                }
                self.out
                    .entry(shape)
                    .or_insert_with(Monomial::zero)
                    .add_term(weight.clone(), poly.clone());
            }
            return;
        }
        // Copied out so the visit closure below does not borrow `self`, which
        // the scratch buffer and the recursive call both need.
        let (k, target) = (self.k, self.target);
        // Every next weight from one walk per state, bucketed by weight, rather
        // than one walk per (state, weight) — see `for_each_strip_any`. The cost
        // is holding `wmax` layer maps at once instead of one; the levels
        // where `wmax` is large are the shallow ones, which have few states, so
        // the peak is set by the deep narrow levels either way.
        let wmax = max_w.min(remaining);
        let mut next: Vec<States<C>> = vec![States::default(); wmax as usize + 1];
        for (state, poly) in states {
            for_each_strip_any(*state, k, wmax, sc, &mut |w, nb, spin| {
                if let Some(t) = target {
                    if !abacus_contained(nb, t) {
                        return;
                    }
                }
                next[w as usize]
                    .entry(nb)
                    .or_insert_with(QtPoly::zero)
                    .add_shifted(poly, (spin, 0), false);
            });
        }
        for w in (1..=wmax).rev() {
            if next[w as usize].is_empty() {
                continue;
            }
            self.weight.push(w);
            let level = std::mem::take(&mut next[w as usize]);
            self.step(&level, remaining - w, w, sc);
            self.weight.pop();
        }
    }
}

/// The highest β-number a walk can reach, asserted to fit.
///
/// `β_j = conj(ν)_j + rows − 1 − j`, so the top β is `ℓ(ν) + rows − 1`, and a
/// move adds `k` on top of that. The two entry points know different things
/// about `ℓ(ν)`:
///
/// - the **pruned** walk stays inside one λ, so `ℓ(ν) ≤ ℓ(λ)` and the bound is
///   `ℓ(λ) + λ₁ + k` — for a one-row λ that is barely more than `λ₁`;
/// - the **unpruned** walk visits every shape of the degree, where the only
///   bound on `ℓ(ν)` is the size.
///
/// Worth separating rather than taking the loose bound for both: `H^(5)_{(13)}`
/// is a 65-cell one-row shape needing 71 bits, and the loose bound rejects it
/// at 135.
fn assert_abacus_fits(top_beta: u32, what: &str) {
    assert!(
        top_beta < ABACUS_BITS,
        "{what} needs β-numbers up to {top_beta}, past this abacus's \
         {ABACUS_BITS} bits"
    );
}

/// The top β-number the **pruned** walk on λ at level `k` will need.
///
/// Public because the Python boundary refuses past this wall rather than
/// letting the panic [`llt_g_lt`] documents reach the caller as a
/// `PanicException` (`docs/policies/failure.md`, R2). The boundary calls this
/// rather than restating the expression, so a change here reaches it and the
/// note above on why the two walks cannot share a bound stays in one place.
pub fn abacus_reach(lambda: &Partition, k: u32) -> u32 {
    lambda.len() as u32 + lambda.part(0).max(1) + k
}

/// The top β-number the **unpruned** whole-degree walk at level `k` will need.
///
/// It visits every shape of size `k·n` and so can only use the size as its
/// bound on `ℓ(ν)`.
pub fn abacus_reach_table(n: u32, k: u32) -> u32 {
    let size = k * n;
    size + size + k
}

/// The abacus width [`abacus_reach`] and [`abacus_reach_table`] are measured
/// against.
pub const ABACUS_REACH_LIMIT: u32 = ABACUS_BITS;

/// The most cells a [`SkewTuple`] can hold, a representation limit of the
/// `u64` attack masks rather than a mathematical one.
pub const MAX_CELLS: usize = 64;

/// The edges [`llt_e_expansion`] orients itself: the weak ones, as unordered
/// pairs, that are not also strict. The pairs come back sorted and
/// deduplicated.
///
/// The sum it drives is `2^{free.len()}` terms, so the count is what a caller
/// needs to know before committing — and what the Python boundary refuses on,
/// rather than letting the assert below reach Sage as a `PanicException`.
pub fn free_edges(g: &DecoratedGraph) -> Vec<(u32, u32)> {
    let mut free: Vec<(u32, u32)> = g
        .weak
        .iter()
        .map(|&(u, v)| (u.min(v), u.max(v)))
        .filter(|e| !g.strict.contains(e))
        .collect();
    free.sort_unstable();
    free.dedup();
    free
}

/// The ceiling on [`free_edges`], set by the `u32` orientation mask.
pub const MAX_FREE_EDGES: usize = 32;

/// `Σ_R q^{spin_LT(R)} x^{w(R)}` over k-ribbon tableaux of shape λ — the \[LT\]
/// (43) grading `q^{2s}`.
///
/// The rawest of the four normalizations, and the one the Fock route
/// ([`llt_kl_column`]) is pinned against. Zero when λ has no k-ribbon tableaux.
///
/// # Panics
///
/// Panics if `k == 0`, and if the abacus this shape needs is wider than
/// [`ABACUS_REACH_LIMIT`] — [`abacus_reach`] is that requirement, exposed so a
/// caller can ask before committing rather than discover it here.
///
/// A λ with no k-ribbon tableaux is an *answer* (zero), not a panic.
pub fn llt_g_lt<C: Ring>(lambda: &Partition, k: u32) -> Monomial<QtPoly<C>> {
    assert!(k >= 1, "a ribbon level needs k ≥ 1");
    let n = lambda.size();
    if !n.is_multiple_of(k) || !lambda.has_empty_k_core(k) {
        return Monomial::zero();
    }
    if n == 0 {
        return Monomial::monomial(Partition::default(), <QtPoly<C> as Ring>::one());
    }
    let rows = lambda.part(0).max(1) as usize;
    assert_abacus_fits(
        abacus_reach(lambda, k),
        &format!("the shape {lambda} at level {k}"),
    );
    let target = abacus_of(lambda, rows);
    let empty = abacus_of(&Partition::default(), rows);
    let mut walk = RibbonWalk::<C> {
        k,
        target: Some(target),
        weight: Vec::new(),
        out: HashMap::new(),
        keep: Some(lambda),
    };
    let mut start: States<C> = States::default();
    start.insert(empty, <QtPoly<C> as Ring>::one());
    let r = n / k;
    walk.step(&start, r, r, &mut StripScratch::default());
    walk.out.remove(lambda).unwrap_or_else(Monomial::zero)
}

/// Which of \[LLT\]'s halvings to apply to a `spin_LT`-graded expansion.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Grading {
    /// `s̃ = (s* − spin)/2` — \[LLT\] (24)–(26)'s cospin.
    Cospin,
    /// `s = spin/2` — \[LLT\] (28)'s spin.
    Spin,
}

/// Halve the `spin_LT` grading into \[LLT\]'s `s` or `s̃`.
///
/// Integrality is an assertion, not a hope: cospin is an integer on every
/// shape (\[LLT\] (25)), and spin is an integer on the shapes `kμ` that `H`
/// is defined on but *not* in general — a shape with odd total `spin_LT` has
/// half-integral spin and \[LLT\] (28) carries a `q^{1/2}`. Asking for
/// [`Grading::Spin`] there is a caller error and says so.
fn regrade<C: Ring>(f: &Monomial<QtPoly<C>>, how: Grading) -> Monomial<QtPoly<C>> {
    let smax = f
        .terms()
        .values()
        .filter_map(|p| p.degrees())
        .map(|(a, _)| a)
        .max()
        .unwrap_or(0);
    let mut out = Monomial::zero();
    for (mu, p) in f.terms() {
        crate::interrupt::poll();
        let mut np = QtPoly::zero();
        for (&(a, b), c) in p.terms() {
            let e = match how {
                Grading::Cospin => smax - a,
                Grading::Spin => a,
            };
            assert!(
                e % 2 == 0,
                "{how:?} of {mu} is half-integral (spin_LT {a}, s* {smax}): this \
                 shape's grading carries a q^(1/2)"
            );
            np.add_term(e / 2, b, c.clone());
        }
        out.add_term(mu.clone(), np);
    }
    out
}

/// `G̃^(k)_λ(x; q)`, the **cospin** generating function of \[LLT\] (26), in the
/// monomial basis.
///
/// Zero when λ has no k-ribbon tableaux. `k = 1` gives `s_λ`; a shape `kμ`
/// gives `H̃^(k)_μ` (\[LLT\] (27), and [`llt_h_tilde`]).
pub fn llt_gtilde<C: Ring>(lambda: &Partition, k: u32) -> Monomial<QtPoly<C>> {
    let raw = llt_g_lt::<C>(lambda, k);
    if raw.is_zero() {
        return raw;
    }
    regrade(&raw, Grading::Cospin)
}

/// `H̃^(k)_μ = G̃^(k)_{kμ}` (\[LLT\] (27)).
pub fn llt_h_tilde<C: Ring>(mu: &Partition, k: u32) -> Monomial<QtPoly<C>> {
    llt_gtilde(&scale(mu, k), k)
}

/// `H^(k)_μ = Σ_R q^{s(R)} x^{w(R)} = q^{s*} H̃^(k)_μ(x; 1/q)` (\[LLT\] (28)).
///
/// Exposed on the **partition-plus-level** side only, and that is a
/// mathematical fact rather than an API choice: the k-quotient tuple of a shape
/// does not determine `s*` (λ = (1,1,1,1) at k = 2 is the smallest witness), so
/// there is no honest `H` of a bare tuple.
///
/// `H^(1)_μ = s_μ`, and for `k` past \[LLT\] Thm 6.6's bound this is the
/// Hall–Littlewood `Q'_μ` — the k-interpolation between the two.
///
/// # Panics
///
/// Panics if `k == 0`, or if the abacus the shape kμ needs is wider than
/// [`ABACUS_REACH_LIMIT`].
pub fn llt_h<C: Ring>(mu: &Partition, k: u32) -> Monomial<QtPoly<C>> {
    let raw = llt_g_lt::<C>(&scale(mu, k), k);
    if raw.is_zero() {
        return raw;
    }
    regrade(&raw, Grading::Spin)
}

/// `kμ = (kμ₁, kμ₂, …)`.
fn scale(mu: &Partition, k: u32) -> Partition {
    Partition::from_sorted(mu.parts().iter().map(|&p| k * p).collect())
}

/// `H^(k)_μ` for **every** μ ⊢ n — the unit the incumbent's walls are measured
/// in (`docs/record/llt.md`).
pub fn llt_h_table<C: Ring>(n: u32, k: u32) -> Vec<(Partition, Monomial<QtPoly<C>>)> {
    crate::partitions_of(n)
        .into_iter()
        .map(|mu| {
            let f = llt_h::<C>(&mu, k);
            (mu, f)
        })
        .collect()
}

/// `m_ν` in the spin basis `H^(k)`, for every ν ⊢ n: the inverse of
/// [`llt_h_table`], as rows `(ν, {μ: c_μ})` with `m_ν = Σ_μ c_μ H^(k)_μ`.
///
/// Rows come in the order of [`partitions_of`](crate::partitions_of), each
/// keyed by μ in the element order with no zeros. This is the direction Sage's
/// `llt(k).hspin()` fills by a generic inverse over `ℚ(t)`
/// (`docs/record/python-and-sage-interop.md`).
///
/// The monomial table itself is not triangular — `H^(3)_{21}` has `q·m_3`
/// above `m_{21}` and `(q+2)·m_{111}` below it — but its **Schur** expansion
/// is: `s(H^(k)_μ)` is supported on λ ⊵ μ with `[s_μ] H^(k)_μ = 1`. So
/// `s_μ = H_μ − Σ_{λ ▷ μ} [s_λ]H_μ · s_λ` solves every `s_μ` from shapes
/// already solved, without dividing, and `m_ν = Σ_λ [s_λ]m_ν · s_λ` finishes
/// the job with the inverse Kostka numbers. The answer stays in `ℤ[q]`.
///
/// \[LLT\] does not state the triangularity for general `k`: its Thm 6.6
/// gives it past the bound below, where `H^(k)_μ` is `Q'_μ`, and its Ex 6.8
/// shows it at μ = (3,2,1,1) for k = 2, 3, 4. So it is checked on every row
/// here rather than assumed.
///
/// `k = 1` gives the inverse Kostka matrix, since `H^(1)_μ = s_μ`; past
/// \[LLT\] Thm 6.6's bound it is `m → Q'` for Hall–Littlewood `Q'`.
///
/// ```
/// use symfn::{monomial_in_llt_h_table, Partition, QtPoly};
///
/// let table = monomial_in_llt_h_table::<i64>(4, 2);
/// let (_, m22) = table.iter().find(|(nu, _)| *nu == Partition::new([2, 2])).unwrap();
/// assert_eq!(m22[&Partition::new([2, 1, 1])], QtPoly::term(0, 0, -1) - QtPoly::q());
/// assert!(!m22.contains_key(&Partition::new([3, 1])));
/// ```
///
/// So at level 2, `m_22 = H_1111 − (1+q)·H_211 + (1+q)·H_22 − (q²+q³)·H_4`,
/// with no `H_31`. Hall–Littlewood `Q'` has `(q²+q³)·Q'_31` and
/// `−(1+q+q²+q³)·Q'_211` there, and the cospin basis `H̃` needs `1/q`, so the
/// pin tells the spin inverse apart from both.
///
/// # Panics
///
/// Panics if `k == 0`, or if an abacus the shapes kμ need is wider than
/// [`ABACUS_REACH_LIMIT`], as [`llt_h`] does. Panics if some `s(H^(k)_μ)` has
/// a term on a shape that does not come before μ in lexicographic order, or
/// a diagonal coefficient other than 1. Every case checked satisfies both
/// (`docs/record/python-and-sage-interop.md`), and an answer built on a
/// violation would be wrong without any sign of it.
pub fn monomial_in_llt_h_table<C: Ring>(
    n: u32,
    k: u32,
) -> Vec<(Partition, BTreeMap<Partition, QtPoly<C>>)> {
    h_inverse_and_star::<C>(n, k).0
}

/// [`monomial_in_llt_h_table`], with `s*_μ` beside it in
/// [`partitions_of`](crate::partitions_of) order.
///
/// `s*_μ` is the top `q`-degree of `H^(k)_μ`, which the walk below already has
/// in hand and [`monomial_in_llt_h_tilde_table`] would otherwise pay a second
/// fill for.
fn h_inverse_and_star<C: Ring>(
    n: u32,
    k: u32,
) -> (Vec<(Partition, BTreeMap<Partition, QtPoly<C>>)>, Vec<u32>) {
    use crate::convert::ToSchur;
    let parts = crate::memo::partitions_cached(n);
    let index: HashMap<&Partition, usize> = parts.iter().enumerate().map(|(i, p)| (p, i)).collect();
    let one = <QtPoly<C> as Ring>::one();

    // `in_h[j]` is `s_{parts[j]}` in the H basis, keyed by index. `parts` is
    // lex-descending and λ ⊵ μ implies λ ≥ μ lexicographically, so every
    // shape a row needs has a smaller index and is solved before it.
    let mut in_h: Vec<BTreeMap<usize, QtPoly<C>>> = Vec::with_capacity(parts.len());
    let mut star: Vec<u32> = Vec::with_capacity(parts.len());
    for (j, mu) in parts.iter().enumerate() {
        crate::interrupt::poll();
        let h = llt_h::<C>(mu, k);
        star.push(
            h.terms()
                .values()
                .filter_map(|p| p.degrees())
                .map(|(a, _)| a)
                .max()
                .unwrap_or(0),
        );
        let mut acc: BTreeMap<usize, QtPoly<C>> = BTreeMap::new();
        acc.insert(j, one.clone());
        let mut diagonal = false;
        for (lambda, c) in h.to_schur().terms() {
            let i = index[lambda];
            if i == j {
                assert!(
                    *c == one,
                    "[s_{mu}] H^({k})_{mu} is not 1; the substitution would divide"
                );
                diagonal = true;
                continue;
            }
            assert!(
                i < j,
                "H^({k})_{mu} has s_{lambda}, which does not come before {mu} lexicographically"
            );
            for (&l, v) in &in_h[i] {
                acc.entry(l)
                    .or_insert_with(QtPoly::zero)
                    .add_assign(&c.mul(v).neg());
            }
        }
        assert!(diagonal, "H^({k})_{mu} has no s_{mu} term");
        acc.retain(|_, v| !v.is_zero());
        in_h.push(acc);
    }

    let rows = parts
        .iter()
        .map(|nu| {
            crate::interrupt::poll();
            let mut out: BTreeMap<Partition, QtPoly<C>> = BTreeMap::new();
            for (lambda, c) in Monomial::monomial(nu.clone(), one.clone())
                .to_schur()
                .terms()
            {
                for (&l, v) in &in_h[index[lambda]] {
                    out.entry(parts[l].clone())
                        .or_insert_with(QtPoly::zero)
                        .add_assign(&c.mul(v));
                }
            }
            out.retain(|_, v| !v.is_zero());
            (nu.clone(), out)
        })
        .collect();
    (rows, star)
}

/// `m_ν` in the cospin basis `H̃^(k)`, for every ν ⊢ n: the inverse of
/// [`llt_h_tilde`], as rows `(ν, shift, {μ: c_μ})` with
/// `m_ν = q^{−shift} Σ_μ c_μ H̃^(k)_μ`.
///
/// The shift is what makes the row plain data: the true coefficients are
/// Laurent in `q` — `H̃^(k)_μ` has `q^{s*_μ}` on its Schur diagonal, so the
/// inverse divides by it — and `QtPoly` carries no negative exponent. Each row
/// is scaled by the smallest power of `q` that clears its own denominators, so
/// `shift` varies from row to row and at least one `c_μ` has a nonzero
/// constant term. Rows come in the order of
/// [`partitions_of`](crate::partitions_of), each keyed by μ in the element
/// order with no zeros.
///
/// This is \[LLT\] (28) read backwards. `H^(k)_μ(x; q) = q^{s*_μ} H̃^(k)_μ(x; 1/q)`,
/// so substituting `q → 1/q` in [`monomial_in_llt_h_table`]'s row for ν turns
/// each spin coefficient `c_μ(q)` into `q^{−s*_μ} c_μ(1/q)` against `H̃^(k)_μ`.
/// No second inverse is taken: the cospin table is the spin one reversed, and
/// the triangularity the spin walk checks is the only thing either relies on.
///
/// ```
/// use symfn::{monomial_in_llt_h_tilde_table, Partition, QtPoly};
///
/// let table = monomial_in_llt_h_tilde_table::<i64>(4, 2);
/// let (_, shift, m22) = table.iter().find(|(nu, _, _)| *nu == Partition::new([2, 2])).unwrap();
/// assert_eq!(*shift, 3);
/// let mut minus_q_minus_q2 = QtPoly::term(1, 0, -1);
/// minus_q_minus_q2.add_term(2, 0, -1);
/// assert_eq!(m22[&Partition::new([2, 1, 1])], minus_q_minus_q2);
/// assert!(!m22.contains_key(&Partition::new([3, 1])));
/// ```
///
/// So at level 2,
/// `q³·m_22 = q·H̃_1111 − (q+q²)·H̃_211 + (1+q)·H̃_22 − (1+q)·H̃_4`. The spin
/// row at the same place is `−(1+q)·H_211` with no shift at all, so the pin
/// tells the two families apart.
///
/// # Panics
///
/// Panics as [`monomial_in_llt_h_table`] does, on the same walk.
pub fn monomial_in_llt_h_tilde_table<C: Ring>(
    n: u32,
    k: u32,
) -> Vec<(Partition, u32, BTreeMap<Partition, QtPoly<C>>)> {
    let (rows, star) = h_inverse_and_star::<C>(n, k);
    let parts = crate::memo::partitions_cached(n);
    let index: HashMap<&Partition, usize> = parts.iter().enumerate().map(|(i, p)| (p, i)).collect();

    // `c_μ(q) H_μ(q) = q^{−s*_μ} c_μ(1/q) H̃_μ(q)`, and `c_μ(1/q)` reaches
    // `q^{−deg c_μ}`, so this entry needs `q^{depth}` to clear.
    let depth =
        |mu: &Partition, p: &QtPoly<C>| star[index[mu]] + p.degrees().map(|(a, _)| a).unwrap_or(0);
    rows.into_iter()
        .map(|(nu, row)| {
            crate::interrupt::poll();
            let shift = row.iter().map(|(mu, p)| depth(mu, p)).max().unwrap_or(0);
            let out = row
                .iter()
                .map(|(mu, p)| {
                    let s = star[index[mu]];
                    let mut rev = QtPoly::zero();
                    for (&(a, b), c) in p.terms() {
                        rev.add_term(shift - s - a, b, c.clone());
                    }
                    (mu.clone(), rev)
                })
                .collect();
            (nu, shift, out)
        })
        .collect()
}

/// `G̃^(k)_λ` for **every** λ ⊢ kn with empty k-core, from a single walk.
///
/// The unpruned form of [`llt_gtilde`]: one pass over the weight trie visits
/// every shape of the degree at once, where the pruned walk pays per shape.
/// Which is cheaper depends on the degree — the shapes of `k·n` outnumber the
/// `p(n)` shapes `kμ` that [`llt_h_table`] wants, but they share every chain —
/// so both exist and `the_two_walks_agree` holds them together.
///
/// # Panics
///
/// Panics if `k == 0`, or if the whole-degree abacus exceeds
/// [`ABACUS_REACH_LIMIT`]. This walk is unpruned and so can only bound `ℓ(ν)`
/// by the degree, which is why [`abacus_reach_table`] is a separate and much
/// coarser bound than [`abacus_reach`].
pub fn llt_gtilde_table<C: Ring>(n: u32, k: u32) -> Vec<(Partition, Monomial<QtPoly<C>>)> {
    assert!(k >= 1, "a ribbon level needs k ≥ 1");
    if n == 0 {
        return vec![(
            Partition::default(),
            Monomial::monomial(Partition::default(), <QtPoly<C> as Ring>::one()),
        )];
    }
    let size = k * n;
    let rows = size as usize;
    assert_abacus_fits(
        abacus_reach_table(n, k),
        &format!("every shape of size {size} at level {k}"),
    );
    let empty = abacus_of(&Partition::default(), rows);
    let mut walk = RibbonWalk::<C> {
        k,
        target: None,
        weight: Vec::new(),
        out: HashMap::new(),
        keep: None,
    };
    let mut start: States<C> = States::default();
    start.insert(empty, <QtPoly<C> as Ring>::one());
    walk.step(&start, n, n, &mut StripScratch::default());
    let mut out: Vec<(Partition, Monomial<QtPoly<C>>)> = walk
        .out
        .into_iter()
        .map(|(shape, f)| {
            let g = regrade(&f, Grading::Cospin);
            (shape, g)
        })
        .collect();
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

/// `G̃^(k)_λ` in the **Schur** basis.
///
/// The row of the Schur-expansion table at λ. [`llt_kl_column`] produces the
/// transposed object — one Schur index, every shape — and the two are worth
/// having separately because the sweeps want different slices.
pub fn llt_schur<C: Ring>(lambda: &Partition, k: u32) -> Schur<QtPoly<C>> {
    use crate::convert::ToSchur;
    llt_gtilde::<C>(lambda, k).to_schur()
}

// ================================================= the shuffle-side refinement

/// `∇e_n = Σ_D t^{area(D)} G_D(x; q)`: the by-path Schur refinement of the
/// shuffle theorem, as `(area sequence, G_D)` pairs.
///
/// Every `G_D` is Schur-positive, so this is `∇e_n` written as a positive sum
/// of positive pieces — the decomposition `docs/record/dyck-paths.md` records,
/// and one no package emits.
///
/// Standardizing labeled paths has no dinv-invariant tie-break, but
/// standardizing *tuple fillings* does, and \[HHL\] (82) makes it an identity
/// rather than a convention — so each `G_D` costs `#SYT` of its tuple instead
/// of one enumeration per content. The valley side of the Delta conjecture
/// stays out: `Val` is not an LLT statistic, and [`crate::dyck`] keeps it.
pub fn nabla_e_by_path<C: Ring>(n: u32) -> Vec<(Vec<u32>, Monomial<QtPoly<C>>)> {
    let mut out = Vec::new();
    for_each_area(n as usize, &mut |area| {
        let g = llt_g::<C>(&SkewTuple::from_area(area));
        let areasum: u32 = area.iter().sum();
        let mut scaled = Monomial::zero();
        for (mu, poly) in g.terms() {
            scaled.add_term(mu.clone(), poly.shift_t(areasum));
        }
        out.push((area.to_vec(), scaled));
    });
    out
}

/// Every area sequence of size `n`: `a₁ = 0` and `a_i ≤ a_{i−1} + 1`.
///
/// The same enumeration as [`crate::dyck`]'s, kept local because this module
/// needs the sequence and that one needs it labeled.
fn for_each_area(n: usize, visit: &mut impl FnMut(&[u32])) {
    fn rec(n: usize, area: &mut Vec<u32>, visit: &mut impl FnMut(&[u32])) {
        if area.len() == n {
            visit(area);
            return;
        }
        let top = if area.is_empty() {
            0
        } else {
            area[area.len() - 1] + 1
        };
        for a in 0..=top {
            area.push(a);
            rec(n, area, visit);
            area.pop();
        }
    }
    let mut area = Vec::with_capacity(n);
    rec(n, &mut area, visit);
}

// ======================================================== the graph presentation

/// A decorated graph: the coloring presentation of a vertical-strip LLT
/// polynomial (\[AP\] Def 16, \[DA\] §2.2).
///
/// Vertices are `0 … n−1`. A **weak** edge is an ordered pair `(u, v)` whose
/// *ascents* are counted: a coloring κ contributes `q` for it when
/// `κ(u) < κ(v)`. A **strict** edge `(u, v)` — always with `u < v` — instead
/// *constrains*: `κ(u) < κ(v)` or the coloring does not count at all. Strict
/// edges never contribute to the statistic.
///
/// The two constructors build genuinely different graphs from the same Dyck
/// path and the module docs say why; do not reach for one expecting the other.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DecoratedGraph {
    n: u32,
    weak: Vec<(u32, u32)>,
    strict: Vec<(u32, u32)>,
}

impl DecoratedGraph {
    /// From explicit edge sets. Strict edges must run `u < v`, and the two sets
    /// must be disjoint as unordered pairs.
    ///
    /// Disjointness is checked because it is the invariant [`llt_graph`] relies
    /// on to skip the strict edges when counting ascents. An edge that is both
    /// would be constrained *and* counted, and the statistic would silently
    /// gain a `q` per strict edge.
    ///
    /// # Panics
    ///
    /// Panics if a strict edge is not oriented `u < v`, if any endpoint is
    /// outside `0..n`, or if an edge appears in both sets as an unordered pair.
    pub fn new(n: u32, weak: &[(u32, u32)], strict: &[(u32, u32)]) -> Self {
        assert!(
            strict.iter().all(|&(u, v)| u < v),
            "a strict edge is oriented u < v: κ(u) < κ(v) is the constraint"
        );
        assert!(
            weak.iter().chain(strict).all(|&(u, v)| u < n && v < n),
            "edges must land inside 0..n"
        );
        let unordered = |&(u, v): &(u32, u32)| (u.min(v), u.max(v));
        assert!(
            weak.iter()
                .map(unordered)
                .all(|e| !strict.iter().map(unordered).any(|s| s == e)),
            "an edge is either weak (counted) or strict (constraining), never both"
        );
        DecoratedGraph {
            n,
            weak: weak.to_vec(),
            strict: strict.to_vec(),
        }
    }

    /// The **dinv-faithful** graph of a Dyck path.
    ///
    /// Weak edges are the \[HRW\] dinv pairs, oriented so that an ascent *is* a
    /// dinv: primary (`a_x = a_y`, `x < y`) as `(x, y)`, secondary
    /// (`a_x = a_y + 1`, `x < y`) as `(y, x)`. Strict edges are consecutive
    /// same-run rows, where labels must strictly increase up a column. The two
    /// sets are disjoint: a same-run pair is never a dinv pair.
    ///
    /// This is *not* [`unit_interval`](Self::unit_interval). `a = (0,0)` has no
    /// cell below its path, and so no edge there, but its two rows do form a
    /// primary dinv pair.
    pub fn from_area(area: &[u32]) -> Self {
        let n = area.len();
        let mut weak = Vec::new();
        for x in 0..n {
            for y in (x + 1)..n {
                if area[x] == area[y] {
                    weak.push((x as u32, y as u32));
                } else if area[x] == area[y] + 1 {
                    weak.push((y as u32, x as u32));
                }
            }
        }
        let strict: Vec<(u32, u32)> = (1..n)
            .filter(|&i| area[i] == area[i - 1] + 1)
            .map(|i| ((i - 1) as u32, i as u32))
            .collect();
        DecoratedGraph {
            n: n as u32,
            weak,
            strict,
        }
    }

    /// The **unit interval graph** of a Dyck path by the cell-below-path rule
    /// of \[CM\] §3 / \[AS\] §2.6: an edge `{j, i}`, `j < i`, exactly when
    /// `j ≥ i − a_i`.
    ///
    /// No strict edges — this is the unicellular case. It is the presentation
    /// the chromatic bridge consumes, and the generator of the unit-interval
    /// corpus; see [`from_area`](Self::from_area) for the other graph.
    pub fn unit_interval(area: &[u32]) -> Self {
        let n = area.len();
        let mut weak = Vec::new();
        for i in 0..n {
            for j in (i.saturating_sub(area[i] as usize))..i {
                weak.push((j as u32, i as u32));
            }
        }
        DecoratedGraph {
            n: n as u32,
            weak,
            strict: Vec::new(),
        }
    }

    /// The number of vertices, which are `0 … n−1`; a coloring assigns a
    /// value to each of them.
    pub fn order(&self) -> u32 {
        self.n
    }

    /// Every coloring of content μ obeying the strict constraints, visited with
    /// its ascent count.
    fn for_each_coloring(&self, mu: &Partition, visit: &mut impl FnMut(&[u32])) {
        let n = self.n as usize;
        let nvals = mu.len();
        let mut counts: Vec<u32> = mu.parts().to_vec();
        let mut kappa: Vec<u32> = Vec::with_capacity(n);
        self.color_rec(n, nvals, &mut counts, &mut kappa, visit);
    }

    fn color_rec(
        &self,
        n: usize,
        nvals: usize,
        counts: &mut [u32],
        kappa: &mut Vec<u32>,
        visit: &mut impl FnMut(&[u32]),
    ) {
        let v = kappa.len();
        if v == n {
            visit(kappa);
            return;
        }
        for j in 0..nvals {
            if counts[j] == 0 {
                continue;
            }
            let c = j as u32 + 1;
            // Strict edges run u < v, so the constraint on the vertex being
            // assigned is always against an already-colored endpoint.
            let ok = self
                .strict
                .iter()
                .all(|&(a, b)| b as usize != v || kappa[a as usize] < c);
            if !ok {
                continue;
            }
            counts[j] -= 1;
            kappa.push(c);
            self.color_rec(n, nvals, counts, kappa, visit);
            kappa.pop();
            counts[j] += 1;
        }
    }

    fn ascents(&self, kappa: &[u32]) -> u32 {
        self.weak
            .iter()
            .filter(|&&(a, b)| kappa[a as usize] < kappa[b as usize])
            .count() as u32
    }
}

/// `G_Γ(x; q) = Σ_κ q^{asc(κ)} x^κ` over the colorings of a decorated graph,
/// in the monomial basis.
///
/// The third presentation of the vertical-strip LLTs, and the one the chromatic
/// bridge and the \[AS\] e-expansion both speak. Equal to
/// `llt_g(SkewTuple::from_area(a))` when the graph is
/// [`DecoratedGraph::from_area(a)`](DecoratedGraph::from_area).
pub fn llt_graph<C: Ring>(g: &DecoratedGraph) -> Monomial<QtPoly<C>> {
    let mut out = Monomial::zero();
    for mu in crate::partitions_of(g.n) {
        let mut poly = QtPoly::zero();
        g.for_each_coloring(&mu, &mut |kappa| {
            poly.add_term(g.ascents(kappa), 0, C::one());
        });
        out.add_term(mu, poly);
    }
    out
}

/// `X_Γ(x; q) = (q−1)^{−n} G_Γ[x(q−1); q]` — the Shareshian–Wachs chromatic
/// quasisymmetric function of Γ, from its LLT polynomial (\[CM\] Prop 3.5,
/// \[AP\] Lemma 47).
///
/// The plethysm is a p-basis twist, `p_r ↦ (q^r − 1) p_r`, and the division by
/// `(q−1)^n` is exact — a remainder would mean the input was not a coloring
/// generating function of the right degree.
///
/// Γ should carry the \[CM\] presentation — natural orientation, no strict
/// edges, as [`DecoratedGraph::unit_interval`] builds — for the output to be
/// the chromatic function of the graph rather than of a decorated relative of
/// it. Isolated vertices are part of the graph and must be counted in `n`;
/// dropping them is a classic way to get a plausible wrong answer.
///
/// # Panics
///
/// Panics if `(q−1)ⁿ` does not divide the twisted expansion exactly. That is
/// not a capacity wall — it says the input was not a coloring generating
/// function of degree `n`, which for the presentations named above cannot
/// happen, so reaching it means Γ was built some other way.
pub fn chromatic_from_llt<C: QAlgebra>(g: &DecoratedGraph) -> Monomial<QtPoly<C>> {
    use crate::convert::{FromSchur, ToSchur};
    let n = g.n;
    let f: Monomial<QtPoly<C>> = llt_graph(g);
    let p: PowerSum<QtPoly<C>> = PowerSum::from_schur(&f.to_schur());
    let mut twisted: PowerSum<QtPoly<C>> = PowerSum::zero();
    for (rho, c) in p.terms() {
        let mut factor = <QtPoly<C> as Ring>::one();
        for &r in rho.parts() {
            // q^r − 1
            let mut term: QtPoly<C> = QtPoly::term(r, 0, C::one());
            term.add_term(0, 0, C::one().neg());
            factor = factor.mul(&term);
        }
        twisted.add_term(rho.clone(), c.mul(&factor));
    }
    let mut divisor = <QtPoly<C> as Ring>::one();
    let mut qm1: QtPoly<C> = QtPoly::term(1, 0, C::one());
    qm1.add_term(0, 0, C::one().neg());
    for _ in 0..n {
        divisor = divisor.mul(&qm1);
    }
    let mut out: PowerSum<QtPoly<C>> = PowerSum::zero();
    for (rho, c) in twisted.terms() {
        let q = c
            .divide_exact(&divisor)
            .expect("(q−1)^n must divide the twisted expansion exactly");
        out.add_term(rho.clone(), q);
    }
    Monomial::from_schur(&out.to_schur())
}

/// The \[AS\] **e-expansion** of `Ĝ_Γ(x; q+1)`: `Σ_θ q^{asc(θ)} e_{λ(θ)}` over
/// orientations of the free (non-strict) edges.
///
/// Returns one `(λ, coefficient)` pair per partition, sorted by λ.
///
/// Blocks come from the highest vertex reachable along strict and *ascending*
/// edges; the block sizes are the partition. By \[DA\]'s theorem the
/// coefficients are non-negative, so this is **certified positive output**
/// rather than a conjecture to check. The test asserts positivity here, and
/// only *records* it for the Schur side of [`nabla_e_by_path`].
///
/// Weak edges are read as unordered pairs `{min, max}`: \[AS\]'s formula
/// orients the edges itself, so the input's orientation is not consulted. Cost
/// is `2^{#free edges}`.
///
/// # Panics
///
/// Panics if [`free_edges`] returns [`MAX_FREE_EDGES`] or more, the ceiling set
/// by the `u32` orientation mask. Since the sum is `2^{free}` terms, a caller
/// wanting to know before committing asks `free_edges(g).len()` — which is why
/// that function is public.
pub fn llt_e_expansion<C: Ring>(g: &DecoratedGraph) -> Vec<(Partition, QtPoly<C>)> {
    let n = g.n as usize;
    let strict: Vec<(u32, u32)> = g.strict.clone();
    let free = free_edges(g);
    assert!(
        free.len() < MAX_FREE_EDGES,
        "the orientation sum is 2^{} terms",
        free.len()
    );

    let mut acc: HashMap<Partition, QtPoly<C>> = HashMap::new();
    for mask in 0u32..(1u32 << free.len()) {
        let mut adj: Vec<Vec<u32>> = vec![Vec::new(); n];
        for &(u, v) in &strict {
            adj[u as usize].push(v);
        }
        let mut asc = 0u32;
        for (i, &(u, v)) in free.iter().enumerate() {
            if mask >> i & 1 == 1 {
                adj[u as usize].push(v);
                asc += 1;
            }
        }
        // Highest reachable vertex along strict + ascending edges.
        let mut blocks: HashMap<u32, u32> = HashMap::new();
        for u in 0..n {
            let mut seen = vec![false; n];
            let mut stack = vec![u as u32];
            seen[u] = true;
            let mut best = u as u32;
            while let Some(w) = stack.pop() {
                best = best.max(w);
                for &z in &adj[w as usize] {
                    if !seen[z as usize] {
                        seen[z as usize] = true;
                        stack.push(z);
                    }
                }
            }
            *blocks.entry(best).or_insert(0) += 1;
        }
        let lambda = Partition::new(blocks.values().copied());
        acc.entry(lambda)
            .or_insert_with(QtPoly::zero)
            .add_term(asc, 0, C::one());
    }
    let mut out: Vec<(Partition, QtPoly<C>)> = acc.into_iter().collect();
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

// =============================================== the [HHL] Macdonald assembly

/// `H̃_μ(x; q, t) = Σ_D q^{−a(D)} t^{maj(D)} G_{ν(μ,D)}(x; q)` — the \[HHL\]
/// decomposition, in the monomial basis.
///
/// Returns `m_∅` with coefficient 1 for the empty partition.
///
/// The fourth route to `H̃` in this crate, and the only one that is positively
/// graded at every intermediate step: Macdonald positivity *is* LLT
/// positivity, and this is where that becomes a computation rather than a
/// slogan. The other three live in [`crate::qtkostka`] and must agree with it.
///
/// `D` ranges over subsets of the non-bottom cells of μ, so this is
/// `2^{|μ|−μ₁}` LLT evaluations — a reference route, not a fast one.
///
/// `a(D)` is negative in the exponent, and [`QtPoly`] exponents are unsigned,
/// so the accumulation carries a uniform `q^{Σ arms}` and divides it out at the
/// end. The division is exact; a remainder would mean the offset was too small.
///
/// # Panics
///
/// Panics if that division leaves a remainder — a bug in the offset, not an
/// input the caller can pick. Also on the [`MAX_CELLS`] wall, since each `D`
/// builds a [`SkewTuple`] holding `|μ|` cells.
pub fn htilde_by_llt<C: Ring>(mu: &Partition) -> Monomial<QtPoly<C>> {
    let k = mu.part(0);
    if k == 0 {
        return Monomial::monomial(Partition::default(), <QtPoly<C> as Ring>::one());
    }
    let conj = mu.conjugate();
    // Candidate descent cells (i, j), 1-based, every cell not in the bottom row
    // of its column.
    let cand: Vec<(u32, u32)> = (1..=k)
        .flat_map(|j| (2..=conj.part((j - 1) as usize)).map(move |i| (i, j)))
        .collect();
    let arm = |(i, j): (u32, u32)| mu.part((i - 1) as usize) - j;
    let leg = |(i, j): (u32, u32)| conj.part((j - 1) as usize) - i;
    let offset: u32 = cand.iter().map(|&c| arm(c)).sum();

    let mut acc: Monomial<QtPoly<C>> = Monomial::zero();
    for mask in 0u64..(1u64 << cand.len()) {
        let d: Vec<(u32, u32)> = (0..cand.len())
            .filter(|i| mask >> i & 1 == 1)
            .map(|i| cand[i])
            .collect();
        let a: u32 = d.iter().map(|&c| arm(c)).sum();
        let maj: u32 = d.iter().map(|&c| leg(c) + 1).sum();

        let comps: Vec<(Vec<(i32, i32)>, i32)> = (1..=k)
            .map(|j| {
                let size = conj.part((j - 1) as usize);
                let des: Vec<u32> = d
                    .iter()
                    .filter(|&&(_, jj)| jj == j)
                    .map(|&(i, _)| i)
                    .collect();
                (ribbon_from_descents(size, &des), 0)
            })
            .collect();
        let g = llt_g::<C>(&SkewTuple::from_cells(&comps));
        for (nu, poly) in g.terms() {
            acc.terms_mut()
                .entry(nu.clone())
                .or_insert_with(<QtPoly<C> as Ring>::zero)
                .add_shifted(poly, (offset - a, maj), false);
        }
    }
    acc.terms_mut().retain(|_, c| !c.is_zero());

    let divisor: QtPoly<C> = QtPoly::term(offset, 0, C::one());
    let mut out = Monomial::zero();
    for (nu, poly) in acc.terms() {
        out.add_term(
            nu.clone(),
            poly.divide_exact(&divisor)
                .expect("the q-offset must divide out exactly"),
        );
    }
    out
}

/// The ribbon component of the \[HHL\] decomposition: `size` cells on
/// consecutive contents, turning a corner at every descent.
///
/// Cell contents run `−1, −2, …` downward in this crate's convention (`col −
/// row`), which is [HHL]'s `row − col` negated; the descent set says which
/// steps go up rather than left.
fn ribbon_from_descents(size: u32, des: &[u32]) -> Vec<(i32, i32)> {
    if size == 0 {
        return Vec::new();
    }
    let mut cells = vec![(1i32, 0i32)];
    for c in 2..=size {
        let (r, cc) = *cells.last().expect("cells is seeded with the first cell");
        if des.contains(&c) {
            cells.push((r + 1, cc));
        } else {
            cells.push((r, cc - 1));
        }
    }
    cells
}

// ================================================ R3: the Fock straightening

/// A wedge: a sequence of integers, strictly decreasing once straightened.
type Wedge = Vec<i32>;

/// Normal-ordered wedges with their coefficients in the \[KMS\] variable `v`.
type Straightened<C> = crate::fasthash::Map<Wedge, QtPoly<C>>;

/// `−v · p`, in one pass: shift the `v` exponents by one and negate.
///
/// `p.mul(&QtPoly::q()).neg()` is the same value through two allocations and
/// the general merge, and this is the inner loop of the straightening ladder —
/// which `examples/profile_llt.rs` put at 63% allocator before this and the
/// in-place wedge walk (`docs/record/llt.md`).
fn neg_v_times<C: Ring>(p: &QtPoly<C>) -> QtPoly<C> {
    let mut out = <QtPoly<C> as Ring>::zero();
    out.add_shifted(p, (1, 0), true);
    out
}

/// `(v² − 1) · p`, in one pass, for the same reason.
fn v2_minus_one_times<C: Ring>(p: &QtPoly<C>) -> QtPoly<C> {
    let mut out = <QtPoly<C> as Ring>::zero();
    out.add_shifted(p, (2, 0), false);
    out.add_shifted(p, (0, 0), true);
    out
}

/// \[KMS\] (43)/(45): normal-order a wedge, accumulating into `out`.
///
/// The rules, with `i = (m−l) mod k`:
///
/// ```text
///   u_l ∧ u_m = −u_m ∧ u_l                                  when l ≡ m (mod k)
///   u_l ∧ u_m = −v u_m∧u_l + (v²−1)( u_{m−i}∧u_{l+i}
///               − v u_{m−k}∧u_{l+k} + v² u_{m−k−i}∧u_{l+k+i} + ⋯ )   otherwise
/// ```
///
/// offsets `i, k, k+i, 2k, 2k+i, …` truncated at `2a < m − l`. \[LLT\] §7
/// prints the same rules with two misprints; \[KMS\] is what this implements,
/// and the dictionary to the ribbon side is `q = −v` — pinned by the multi-term
/// Kazhdan–Lusztig entries, which single monomials cannot separate from the
/// mirrored laws.
///
/// **Written in place.** Each branch changes only the two positions `i, i+1`,
/// so it mutates, recurses and restores rather than cloning the wedge. Cloning
/// per branch made this route **63% allocator** under
/// `examples/profile_llt.rs`: `malloc` and `free` together outweighed the
/// straightening itself by three to one (`docs/record/llt.md`). The offset
/// ladder is generated on the fly for the same reason — the candidate offsets
/// `i, k, k+i, 2k, …` are already sorted and already distinct, so building,
/// sorting and filtering a `Vec` of them per ascent bought nothing.
fn straighten<C: Ring>(w: &mut [i32], coeff: &QtPoly<C>, k: u32, out: &mut Straightened<C>) {
    if coeff.is_zero() {
        return;
    }
    for i in 0..w.len().saturating_sub(1) {
        if w[i] == w[i + 1] {
            return; // a repeated index kills the wedge
        }
        if w[i] < w[i + 1] {
            let (l, m) = (w[i], w[i + 1]);
            let diff = (m - l) as u32;
            w[i] = m;
            w[i + 1] = l;
            if diff.is_multiple_of(k) {
                straighten(w, &coeff.neg(), k, out);
            } else {
                straighten(w, &neg_v_times(coeff), k, out);
                let mut term = v2_minus_one_times(coeff);
                let im = diff % k;
                let mut a = im;
                // The offsets i, k, k+i, 2k, 2k+i, … in order, without a Vec:
                // already sorted and already distinct, so building one bought
                // nothing.
                while 2 * a < diff {
                    w[i] = m - a as i32;
                    w[i + 1] = l + a as i32;
                    straighten(w, &term, k, out);
                    term = neg_v_times(&term); // the (−v)^t ladder
                    a = if a.is_multiple_of(k) {
                        a + im
                    } else {
                        a - im + k
                    };
                }
            }
            w[i] = l;
            w[i + 1] = m;
            return;
        }
    }
    // Most leaves land on a wedge already seen — that accumulation is what
    // the route is for — so probe before paying for the key.
    if let Some(slot) = out.get_mut(&*w) {
        slot.add_assign(coeff);
    } else {
        out.insert(w.to_vec(), coeff.clone());
    }
}

/// `V_m`, the `h_m`-shaped boson: add `k` to a multiset of `m` positions, then
/// straighten.
///
/// The multiset walk is incremental for the same reason [`straighten`] is: one
/// buffer, `+k` on the way down and `−k` on the way back up, instead of a fresh
/// wedge per multiset.
fn v_op<C: Ring>(wedges: &Straightened<C>, m: u32, k: u32) -> Straightened<C> {
    let mut out: Straightened<C> = Straightened::default();
    let mut buf: Wedge = Vec::new();
    for (wedge, coeff) in wedges {
        buf.clear();
        buf.extend_from_slice(wedge);
        boson_rec(&mut buf, 0, m as usize, k, coeff, &mut out);
    }
    out.retain(|_, c| !c.is_zero());
    out
}

/// Every `m`-multiset of positions, applied to `buf` in place.
fn boson_rec<C: Ring>(
    buf: &mut [i32],
    lo: usize,
    m: usize,
    k: u32,
    coeff: &QtPoly<C>,
    out: &mut Straightened<C>,
) {
    if m == 0 {
        straighten(buf, coeff, k, out);
        return;
    }
    for j in lo..buf.len() {
        buf[j] += k as i32;
        boson_rec(buf, j, m - 1, k, coeff, out);
        buf[j] -= k as i32;
    }
}

/// One **column** of the Schur-expansion table: `⟨μ + ρ| S_λ |ρ⟩` for every
/// shape μ ⊢ k|λ|, in the \[KMS\] variable `v`.
///
/// Shapes with a zero coefficient are dropped. Returns `[(∅, 1)]` when λ is
/// empty.
///
/// The transpose of what tableau enumeration gives. One straightening run at
/// fixed λ produces the coefficient of `s_λ` in `G_LT,μ` for *every* μ at once,
/// and those coefficients are parabolic affine Kazhdan–Lusztig polynomials
/// (\[LT\] Thm 4.2, Varagnolo–Vasserot) — computed by exact straightening with
/// no Hecke algebra in sight.
///
/// The variable is `v`, occupying [`QtPoly`]'s `q` slot; the ribbon side's
/// grading is recovered at **`q = −v`**. That dictionary is the one thing here
/// no single monomial can pin, and the module's test range includes the
/// multi-term degree-4 entries that do.
///
/// # Panics
///
/// Panics if `k == 0`. This route straightens wedges rather than walking an
/// abacus, so [`llt_g_lt`]'s reach wall is not one of its failure modes.
pub fn llt_kl_column<C: Ring>(lambda: &Partition, k: u32) -> Vec<(Partition, QtPoly<C>)> {
    use crate::convert::FromSchur;
    assert!(k >= 1, "a ribbon level needs k ≥ 1");
    let deg = lambda.size();
    if deg == 0 {
        return vec![(Partition::default(), <QtPoly<C> as Ring>::one())];
    }
    let rows = (k * deg) as usize;
    let rho: Wedge = (0..rows as i32).rev().collect();

    // κ: s_λ in the h-basis, one determinant row per λ.
    let s: Schur<i64> = Schur::monomial(lambda.clone(), 1);
    let h = crate::sym::Homogeneous::from_schur(&s);

    let mut acc: HashMap<Wedge, QtPoly<C>> = HashMap::new();
    for (nu, c) in h.terms() {
        let mut wedges: Straightened<C> = Straightened::default();
        wedges.insert(rho.clone(), QtPoly::term(0, 0, C::from_i64(*c)));
        for &part in nu.parts() {
            wedges = v_op(&wedges, part, k);
        }
        for (w, cc) in wedges {
            acc.entry(w)
                .or_insert_with(<QtPoly<C> as Ring>::zero)
                .add_assign(&cc);
        }
    }

    let mut out = Vec::new();
    for mu in crate::partitions_of(k * deg) {
        if mu.len() > rows {
            continue;
        }
        let key: Wedge = (0..rows).map(|j| mu.part(j) as i32 + rho[j]).collect();
        if let Some(c) = acc.get(&key) {
            if !c.is_zero() {
                out.push((mu, c.clone()));
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::coeff::Rational;
    use crate::convert::{FromSchur, ToSchur};
    use crate::sym::Elementary;

    type Q = QtPoly<i64>;

    fn part(v: &[u32]) -> Partition {
        Partition::new(v.iter().copied())
    }

    fn q_pow(e: u32) -> Q {
        QtPoly::term(e, 0, 1)
    }

    fn poly(terms: &[(u32, i64)]) -> Q {
        let mut p = QtPoly::zero();
        for &(e, c) in terms {
            p.add_term(e, 0, c);
        }
        p
    }

    fn tuple(shapes: &[&[u32]]) -> SkewTuple {
        let shapes: Vec<Partition> = shapes.iter().map(|s| part(s)).collect();
        let offsets = vec![0i32; shapes.len()];
        SkewTuple::from_partitions(&shapes, &offsets)
    }

    /// The map fallback is only reached by tuples too large to run in a test
    /// suite, so the budget is driven to zero instead: same tuples, same
    /// answers, the other sink. Without this the fallback's only coverage is
    /// the cases nobody can afford to check.
    ///
    /// Compared on trimmed rows, because the two sinks disagree on trailing
    /// zeros and always have: the flat table pads every row to `A(ν) + 1`,
    /// while the map grows a row only to the largest `inv` it saw. Both
    /// consumers skip zero counts, so the length is not part of the value —
    /// which is exactly the claim being pinned here.
    #[test]
    fn both_syt_bucket_sinks_agree_up_to_trailing_zeros() {
        fn trim(b: Vec<(u64, Vec<u128>)>) -> Vec<(u64, Vec<u128>)> {
            b.into_iter()
                .map(|(mask, mut counts)| {
                    while counts.last() == Some(&0) {
                        counts.pop();
                    }
                    (mask, counts)
                })
                .collect()
        }
        for shapes in [
            &[&[2u32, 1][..], &[2, 1][..]][..],
            &[&[3, 2][..], &[2][..]][..],
            &[&[2, 2][..], &[2, 1][..], &[1][..]][..],
            &[&[3, 1, 1][..]][..],
        ] {
            let nu = tuple(shapes);
            assert_eq!(
                trim(nu.syt_buckets()),
                trim(nu.syt_buckets_within(0)),
                "sinks disagree on {shapes:?}"
            );
        }
    }

    /// Direct semistandard enumeration, sharing nothing with the descent
    /// buckets: fill cells in index order, check the covers, read off `x^μ`.
    fn g_direct(nu: &SkewTuple) -> Monomial<Q> {
        let n = nu.size();
        let mut out = Monomial::zero();
        for mu in crate::partitions_of(n as u32) {
            let nvals = mu.len();
            let mut counts: Vec<u32> = mu.parts().to_vec();
            let mut filling: Vec<u32> = Vec::with_capacity(n);
            let mut acc = QtPoly::zero();
            fill_rec(nu, n, nvals, &mut counts, &mut filling, &mut acc);
            out.add_term(mu, acc);
        }
        out
    }

    fn fill_rec(
        nu: &SkewTuple,
        n: usize,
        nvals: usize,
        counts: &mut [u32],
        filling: &mut Vec<u32>,
        acc: &mut Q,
    ) {
        let cell = filling.len();
        if cell == n {
            let inv = nu
                .attack
                .iter()
                .filter(|&&(a, b)| filling[a as usize] > filling[b as usize])
                .count() as u32;
            acc.add_term(inv, 0, 1);
            return;
        }
        for j in 0..nvals {
            if counts[j] == 0 {
                continue;
            }
            let v = j as u32 + 1;
            // Each disjunct is one way the edge is *violated*, so the negation
            // sits outside the whole search rather than on each clause: "no
            // weak edge objects to v here". De Morgan of the per-clause form.
            let ok_weak = !nu.weak.iter().any(|&(x, y)| {
                let (x, y) = (x as usize, y as usize);
                (y == cell && filling[x] > v) || (x == cell && y < cell && v > filling[y])
            });
            let ok_strict = !nu.strict.iter().any(|&(x, y)| {
                let (x, y) = (x as usize, y as usize);
                (y == cell && filling[x] >= v) || (x == cell && y < cell && v >= filling[y])
            });
            if ok_weak && ok_strict {
                counts[j] -= 1;
                filling.push(v);
                fill_rec(nu, n, nvals, counts, filling, acc);
                filling.pop();
                counts[j] += 1;
            }
        }
    }

    /// Divide out the `q^{min inv}` floor — the cospin normalization of the
    /// tuple model.
    fn floored(f: &Monomial<Q>, floor: u32) -> Monomial<Q> {
        let divisor = q_pow(floor);
        let mut out = Monomial::zero();
        for (mu, p) in f.terms() {
            out.add_term(mu.clone(), p.divide_exact(&divisor).expect("floor divides"));
        }
        out
    }

    /// **The convention gate.** One attacking pair, and the line that dies if
    /// reading order, the attack rule, or the inv orientation drifts.
    #[test]
    fn the_convention_gate() {
        let g: Monomial<Q> = llt_g(&tuple(&[&[1], &[1]]));
        assert_eq!(g.coeff(&part(&[2])), poly(&[(0, 1)]), "m_2");
        assert_eq!(g.coeff(&part(&[1, 1])), poly(&[(0, 1), (1, 1)]), "m_11");
        assert_eq!(g.terms().len(), 2);
    }

    /// R1 against direct semistandard enumeration, on straight and skew tuples.
    /// This is the identity that makes \[HHL\] (82) an identity rather than a
    /// convention, so it is checked on everything else's behalf.
    #[test]
    fn standardization_agrees_with_direct_enumeration() {
        let straight: &[&[&[u32]]] = &[
            &[&[2], &[1]],
            &[&[1, 1], &[1]],
            &[&[2, 1], &[1]],
            &[&[1], &[1], &[1]],
            &[&[2], &[2]],
            &[&[2, 1], &[2]],
        ];
        for shapes in straight {
            let nu = tuple(shapes);
            assert_eq!(llt_g::<i64>(&nu), g_direct(&nu), "{shapes:?}");
        }
        let skews: &[&[(&[u32], &[u32])]] = &[
            &[(&[2, 1], &[1]), (&[1], &[])],
            &[(&[2, 2], &[1]), (&[2], &[1])],
        ];
        for sk in skews {
            let shapes: Vec<(Partition, Partition)> =
                sk.iter().map(|(o, i)| (part(o), part(i))).collect();
            let nu = SkewTuple::from_skews(&shapes, &vec![0i32; sk.len()]);
            assert_eq!(llt_g::<i64>(&nu), g_direct(&nu), "{sk:?}");
        }
    }

    /// Contents are the model's content: shifting one component's offset must
    /// move the answer, or the offsets are not being read at all.
    #[test]
    fn content_offsets_are_load_bearing() {
        let shapes = [part(&[1]), part(&[1])];
        let a: Monomial<Q> = llt_g(&SkewTuple::from_partitions(&shapes, &[0, 0]));
        let b: Monomial<Q> = llt_g(&SkewTuple::from_partitions(&shapes, &[0, 5]));
        assert_ne!(a, b);
    }

    /// `q = 1` collapses the tuple model to a product of skew Schur functions.
    /// Checked against [`crate::skew_lr`], which shares no code with this.
    #[test]
    fn at_q_one_it_is_a_product_of_skew_schurs() {
        let cases: &[&[(&[u32], &[u32])]] = &[
            &[(&[2, 1], &[]), (&[1], &[])],
            &[(&[2, 2], &[1]), (&[2, 1], &[])],
            &[(&[3, 1], &[1]), (&[2], &[]), (&[1, 1], &[])],
        ];
        for sk in cases {
            let shapes: Vec<(Partition, Partition)> =
                sk.iter().map(|(o, i)| (part(o), part(i))).collect();
            let nu = SkewTuple::from_skews(&shapes, &vec![0i32; sk.len()]);
            let got: Schur<i64> = {
                let g: Monomial<Q> = llt_g(&nu);
                let mut at_one: Monomial<i64> = Monomial::zero();
                for (mu, p) in g.terms() {
                    at_one.add_term(mu.clone(), p.eval(&1, &1));
                }
                at_one.to_schur()
            };
            let mut want: Schur<i64> = Schur::monomial(Partition::default(), 1);
            for (o, i) in &shapes {
                let mut factor: Schur<i64> = Schur::zero();
                for (nu, c) in crate::skew_lr::expand_skew_shared(o, i).iter() {
                    factor.add_term(nu.clone(), *c as i64);
                }
                want = want.mul(&factor);
            }
            assert_eq!(got, want, "{sk:?} at q = 1");
        }
    }

    /// **The quotient dictionary**, the law that ties the two models: `q^{−min
    /// inv} G_{k-quotient(λ)} = G̃^(k)_λ`, offsets zero. Swept over every
    /// empty-core shape of the small degrees, and the sweep must *contain*
    /// shapes with a nonzero floor or it is not testing the floor.
    #[test]
    fn the_quotient_dictionary_is_the_floored_tuple() {
        let mut floors = 0;
        let mut shapes = 0;
        for k in 2..=3u32 {
            for n in [k, 2 * k, 3 * k] {
                for lambda in crate::partitions_of(n) {
                    let Some(nu) = SkewTuple::quotient(&lambda, k) else {
                        continue;
                    };
                    if nu.size() == 0 {
                        continue;
                    }
                    shapes += 1;
                    let floor = llt_min_inv(&nu);
                    if floor > 0 {
                        floors += 1;
                    }
                    let got = floored(&llt_g::<i64>(&nu), floor);
                    let want: Monomial<Q> = llt_gtilde(&lambda, k);
                    assert_eq!(got, want, "λ = {lambda}, k = {k}, floor {floor}");
                }
            }
        }
        assert!(shapes >= 40, "the sweep shrank to {shapes} shapes");
        assert!(
            floors > 0,
            "no shape in the sweep has a nonzero min-inv floor, so the floor is \
             untested — λ = (2,2,2) at k = 2 is the smallest witness"
        );
    }

    /// The floor is *forced*, and the smallest witness deserves its own line:
    /// λ = (2,2,2) at k = 2 has 2-quotient `((1), (1,1))` and `min inv = 1`.
    ///
    /// ⚠️ λ = (2,2) is the near miss, and was written down as the witness
    /// twice before being checked: its 2-quotient is `((1), (1))`, whose `G`
    /// is `m₂ + (1+q)m₁₁` — floor 0, which is what the convention gate above
    /// depends on, so the two claims were never consistent. Both directions
    /// are asserted below. The floored shapes at k = 2 through |λ| = 8 are
    /// (2,2,2), (4,2,2), (3,3,2), (2,2,2,2) and (2,2,2,1,1); the law itself
    /// is unaffected.
    #[test]
    fn the_min_inv_floor_is_forced() {
        let nu = SkewTuple::quotient(&part(&[2, 2, 2]), 2).expect("empty 2-core");
        assert_eq!(
            part(&[2, 2, 2]).k_quotient(2),
            vec![part(&[1]), part(&[1, 1])]
        );
        assert_eq!(llt_min_inv(&nu), 1);
        // And the spec's stated witness really does have no floor.
        let flat = SkewTuple::quotient(&part(&[2, 2]), 2).expect("empty 2-core");
        assert_eq!(llt_min_inv(&flat), 0);
    }

    /// Tuples lose absolute spin: λ = (1,1,1,1) at k = 2 has `s* = 1` while its
    /// quotient's inv range is a single point. No tuple statistic can recover
    /// the spin grading, which is why `llt_h` takes a partition and a level.
    #[test]
    fn tuples_lose_absolute_spin() {
        let lambda = part(&[1, 1, 1, 1]);
        let raw: Monomial<Q> = llt_g_lt(&lambda, 2);
        let smax = raw
            .terms()
            .values()
            .filter_map(|p| p.degrees())
            .map(|(a, _)| a)
            .max()
            .unwrap();
        assert_eq!(smax, 2, "spin_LT of the one tableau, i.e. s* = 1");
        let nu = SkewTuple::quotient(&lambda, 2).unwrap();
        assert_eq!(llt_min_inv(&nu), llt_max_inv(&nu));
    }

    /// **\[LLT\] Ex 6.8(i)**: `G̃_{(3,3,3,2,1)}` at k = 3, in m and in s.
    #[test]
    fn llt_example_68i() {
        let g: Monomial<Q> = llt_gtilde(&part(&[3, 3, 3, 2, 1]), 3);
        assert_eq!(g.coeff(&part(&[3, 1])), poly(&[(0, 1)]));
        assert_eq!(g.coeff(&part(&[2, 2])), poly(&[(0, 1), (1, 1)]));
        assert_eq!(g.coeff(&part(&[2, 1, 1])), poly(&[(0, 2), (1, 2), (2, 1)]));
        assert_eq!(
            g.coeff(&part(&[1, 1, 1, 1])),
            poly(&[(0, 3), (1, 5), (2, 3), (3, 1)])
        );
        assert_eq!(g.terms().len(), 4);

        let s = g.to_schur();
        assert_eq!(s.coeff(&part(&[3, 1])), poly(&[(0, 1)]));
        assert_eq!(s.coeff(&part(&[2, 2])), poly(&[(1, 1)]));
        assert_eq!(s.coeff(&part(&[2, 1, 1])), poly(&[(1, 1), (2, 1)]));
        assert_eq!(s.coeff(&part(&[1, 1, 1, 1])), poly(&[(3, 1)]));
        assert_eq!(s.terms().len(), 4);
    }

    /// **\[LLT\] Ex 6.8(ii)**: `H^(2)_{3211}` in the Schur basis.
    #[test]
    fn llt_example_68ii() {
        let h: Monomial<Q> = llt_h(&part(&[3, 2, 1, 1]), 2);
        let s = h.to_schur();
        let want: &[(&[u32], &[(u32, i64)])] = &[
            (&[3, 2, 1, 1], &[(0, 1)]),
            (&[3, 2, 2], &[(1, 1)]),
            (&[3, 3, 1], &[(1, 1)]),
            (&[4, 1, 1, 1], &[(1, 1)]),
            (&[4, 2, 1], &[(1, 1), (2, 1)]),
            (&[4, 3], &[(2, 1)]),
            (&[5, 1, 1], &[(2, 1)]),
            (&[5, 2], &[(3, 1)]),
        ];
        for (nu, terms) in want {
            assert_eq!(s.coeff(&part(nu)), poly(terms), "s_{nu:?}");
        }
        assert_eq!(s.terms().len(), want.len());
    }

    /// **\[LT\] Ex 4.1**: the same shape in the spin-generating (43) grading.
    #[test]
    fn lt_example_41() {
        let g: Monomial<Q> = llt_g_lt(&part(&[3, 3, 3, 2, 1]), 3);
        let s = g.to_schur();
        assert_eq!(s.coeff(&part(&[3, 1])), poly(&[(7, 1)]));
        assert_eq!(s.coeff(&part(&[2, 2])), poly(&[(5, 1)]));
        assert_eq!(s.coeff(&part(&[2, 1, 1])), poly(&[(3, 1), (5, 1)]));
        assert_eq!(s.coeff(&part(&[1, 1, 1, 1])), poly(&[(1, 1)]));
    }

    /// `k = 1`: one-ribbons are cells, spin is zero, `G̃^(1)_λ = s_λ`.
    #[test]
    fn level_one_is_the_schur_function() {
        for n in 0..=6u32 {
            for lambda in crate::partitions_of(n) {
                let got: Schur<Q> = llt_schur(&lambda, 1);
                let want: Schur<Q> = Schur::monomial(lambda.clone(), <Q as Ring>::one());
                assert_eq!(got, want, "G̃^(1)_{lambda}");
            }
        }
    }

    /// **\[LLT\] (28)**, internally: `H = q^{s*} G̃(1/q)` on the shapes where
    /// the spin grading is integral.
    #[test]
    fn h_is_the_cospin_flip() {
        for k in 2..=3u32 {
            for n in 0..=4u32 {
                for mu in crate::partitions_of(n) {
                    let cos: Monomial<Q> = llt_h_tilde(&mu, k);
                    let h: Monomial<Q> = llt_h(&mu, k);
                    let sstar = cos
                        .terms()
                        .values()
                        .filter_map(|p| p.degrees())
                        .map(|(a, _)| a)
                        .max()
                        .unwrap_or(0);
                    let mut flipped: Monomial<Q> = Monomial::zero();
                    for (nu, p) in cos.terms() {
                        let mut np = QtPoly::zero();
                        for (&(a, b), c) in p.terms() {
                            np.add_term(sstar - a, b, *c);
                        }
                        flipped.add_term(nu.clone(), np);
                    }
                    assert_eq!(flipped, h, "H^({k})_{mu} = q^s* H̃(1/q)");
                }
            }
        }
    }

    /// **\[LLT\] Thm 6.6**: at large level the spin ribbon function *is*
    /// Hall–Littlewood `Q'_μ`. Checked against [`crate::hl`] in-crate — two
    /// entirely different recursions landing on the same polynomial.
    #[test]
    fn large_level_is_hall_littlewood() {
        for n in 0..=4u32 {
            for mu in crate::partitions_of(n) {
                let k = mu.len().max(1) as u32;
                let got: Schur<Q> = llt_h::<i64>(&mu, k).to_schur();
                // `hl` grades in t; this module grades in q. Same polynomial,
                // different slot.
                let want_t: Schur<Q> = crate::hl::hall_littlewood(&mu);
                let mut want: Schur<Q> = Schur::zero();
                for (nu, p) in want_t.terms() {
                    let mut np = QtPoly::zero();
                    for (&(a, b), c) in p.terms() {
                        assert_eq!(a, 0, "Hall–Littlewood lives in t alone");
                        np.add_term(b, 0, *c);
                    }
                    want.add_term(nu.clone(), np);
                }
                assert_eq!(got, want, "H^({k})_{mu} vs Q'_{mu}");
            }
        }
    }

    /// The inverse table undoes the forward one: `Σ_μ c_μ H_μ`, expanded back
    /// to monomials, is `m_ν`. This shares the forward table with the
    /// function under test, so `the_inverse_at_large_level_is_hall_littlewood`
    /// is the check that shares no mathematics with it.
    #[test]
    fn the_inverse_table_undoes_the_h_table() {
        for k in 1..=4u32 {
            for n in 0..=6u32 {
                let h: HashMap<Partition, Monomial<Q>> =
                    llt_h_table::<i64>(n, k).into_iter().collect();
                for (nu, row) in monomial_in_llt_h_table::<i64>(n, k) {
                    let mut back: Monomial<Q> = Monomial::zero();
                    for (mu, c) in &row {
                        for (lambda, v) in h[mu].terms() {
                            back.add_term(lambda.clone(), c.mul(v));
                        }
                    }
                    let want = Monomial::monomial(nu.clone(), <Q as Ring>::one());
                    assert_eq!(back, want, "m_{nu} at k={k}");
                }
            }
        }
    }

    /// **\[LLT\] Thm 6.6**, inverted: at `k ≥ n` every `H^(k)_μ` of degree n
    /// is `Q'_μ`, so the inverse table is `m → Q'`, which [`crate::hl`]
    /// reaches through the Kostka–Foulkes matrix and no ribbon walk.
    #[test]
    fn the_inverse_at_large_level_is_hall_littlewood() {
        for n in 1..=5u32 {
            for (nu, got) in monomial_in_llt_h_table::<i64>(n, n) {
                let s: Schur<Q> =
                    Monomial::<Q>::monomial(nu.clone(), <Q as Ring>::one()).to_schur();
                // `hl` grades in t; this module grades in q.
                let want: BTreeMap<Partition, Q> = crate::hl::schur_to_hall_littlewood_qp(&s)
                    .into_iter()
                    .map(|(mu, p)| {
                        let mut np = QtPoly::zero();
                        for (&(a, b), c) in p.terms() {
                            assert_eq!(a, 0, "Hall–Littlewood lives in t alone");
                            np.add_term(b, 0, *c);
                        }
                        (mu, np)
                    })
                    .collect();
                assert_eq!(got, want, "m_{nu} at k={n}");
            }
        }
    }

    /// The cospin inverse undoes [`llt_h_tilde`]: `Σ_μ c_μ H̃_μ` is
    /// `q^{shift} m_ν`. The forward table here comes through the cospin
    /// regrading of `llt_gtilde`, while the inverse is built from the spin
    /// walk, so the two sides meet only at \[LLT\] (28).
    #[test]
    fn the_cospin_inverse_table_undoes_the_h_tilde_table() {
        for k in 1..=4u32 {
            for n in 1..=6u32 {
                let h: HashMap<Partition, Monomial<Q>> = crate::partitions_of(n)
                    .into_iter()
                    .map(|mu| {
                        let f = llt_h_tilde::<i64>(&mu, k);
                        (mu, f)
                    })
                    .collect();
                for (nu, shift, row) in monomial_in_llt_h_tilde_table::<i64>(n, k) {
                    let mut back: Monomial<Q> = Monomial::zero();
                    for (mu, c) in &row {
                        for (lambda, v) in h[mu].terms() {
                            back.add_term(lambda.clone(), c.mul(v));
                        }
                    }
                    let want =
                        Monomial::monomial(nu.clone(), QtPoly::term(shift, 0, <i64>::from(1u8)));
                    assert_eq!(back, want, "m_{nu} at k={k}");

                    // The shift is the smallest one that clears the row, so
                    // some coefficient survives setting q to 0.
                    assert!(
                        row.values().any(|p| p.terms().any(|(&(a, _), _)| a == 0)),
                        "the row at {nu}, k={k} is divisible by q: the shift is not minimal"
                    );
                }
            }
        }
    }

    /// **ω-duality**: `G_{ν'}(x; q) = q^{A(ν)} ω G_ν(x; 1/q)`.
    #[test]
    fn omega_duality() {
        for shapes in [
            &[&[1u32][..], &[1]][..],
            &[&[2], &[1]],
            &[&[2, 1], &[1]],
            &[&[2], &[2]],
        ] {
            let nu = tuple(shapes);
            let a = nu.attacking_pairs() as u32;
            let lhs: Schur<Q> = llt_g::<i64>(&nu.conjugate()).to_schur();
            // ω on the Schur basis transposes the index; the q-flip is
            // q^A · p(1/q), which is exactly reversing each coefficient.
            let g: Schur<Q> = llt_g::<i64>(&nu).to_schur();
            let mut rhs: Schur<Q> = Schur::zero();
            for (lambda, p) in g.terms() {
                let mut np = QtPoly::zero();
                for (&(e, b), c) in p.terms() {
                    assert!(e <= a, "the flip must stay polynomial");
                    np.add_term(a - e, b, *c);
                }
                rhs.add_term(lambda.conjugate(), np);
            }
            assert_eq!(lhs, rhs, "{shapes:?}");
        }
    }

    /// The three vertical-strip presentations must agree **pointwise per
    /// path**, not merely in total: the reverse-run tuple, the dinv model, and
    /// the coloring model on the dinv-faithful graph.
    #[test]
    fn the_three_vertical_strip_models_agree() {
        for n in 0..=6usize {
            for_each_area(n, &mut |area| {
                let from_tuple: Monomial<Q> = llt_g(&SkewTuple::from_area(area));
                let from_graph: Monomial<Q> = llt_graph(&DecoratedGraph::from_area(area));
                assert_eq!(from_tuple, from_graph, "area {area:?}");
                assert_eq!(from_tuple, dinv_model(area), "area {area:?}");
            });
        }
    }

    /// `Σ_labelings q^{dinv} x^ℓ` straight from \[HRW\], sharing nothing with
    /// either model under test.
    fn dinv_model(area: &[u32]) -> Monomial<Q> {
        let n = area.len();
        let mut out = Monomial::zero();
        for mu in crate::partitions_of(n as u32) {
            let nvals = mu.len();
            let mut counts: Vec<u32> = mu.parts().to_vec();
            let mut labels: Vec<u32> = Vec::with_capacity(n);
            let mut acc = QtPoly::zero();
            label_rec(area, nvals, &mut counts, &mut labels, &mut acc);
            out.add_term(mu, acc);
        }
        out
    }

    fn label_rec(
        area: &[u32],
        nvals: usize,
        counts: &mut [u32],
        labels: &mut Vec<u32>,
        acc: &mut Q,
    ) {
        let i = labels.len();
        if i == area.len() {
            let mut dinv = 0u32;
            for x in 0..area.len() {
                for y in (x + 1)..area.len() {
                    if (area[x] == area[y] && labels[x] < labels[y])
                        || (area[x] == area[y] + 1 && labels[x] > labels[y])
                    {
                        dinv += 1;
                    }
                }
            }
            acc.add_term(dinv, 0, 1);
            return;
        }
        let rise = i > 0 && area[i] == area[i - 1] + 1;
        for j in 0..nvals {
            if counts[j] == 0 {
                continue;
            }
            let v = j as u32 + 1;
            if rise && v <= labels[i - 1] {
                continue;
            }
            counts[j] -= 1;
            labels.push(v);
            label_rec(area, nvals, counts, labels, acc);
            labels.pop();
            counts[j] += 1;
        }
    }

    /// **The shuffle refinement**: `Σ_D t^{area} G_D = ∇e_n`, against
    /// [`crate::deltaop`]'s operator side.
    #[test]
    fn the_shuffle_refinement_is_nabla_e() {
        for n in 0..=5u32 {
            let mut total: Monomial<QtPoly<Rational>> = Monomial::zero();
            for (_, g) in nabla_e_by_path::<Rational>(n) {
                total = total.add(&g);
            }
            let want = crate::deltaop::nabla_e::<Rational>(n);
            assert_eq!(total.to_schur(), want, "∇e_{n} by path");
        }
    }

    /// Per-path Schur positivity is **recorded, never repaired**: it is a
    /// theorem for tuples of partitions (\[LT\]/Varagnolo–Vasserot) and rests
    /// on an unpublished preprint (\[GH\]) in general, so a negative
    /// coefficient here is a finding of the first order, not a bug to fix
    /// quietly.
    #[test]
    fn every_path_piece_is_schur_positive() {
        for n in 0..=5u32 {
            for (area, g) in nabla_e_by_path::<i64>(n) {
                for (lambda, p) in g.to_schur().terms() {
                    for (_, c) in p.terms() {
                        assert!(
                            *c >= 0,
                            "negative Schur coefficient {c} on s_{lambda} for area \
                             {area:?}: report this, do not repair it"
                        );
                    }
                }
            }
        }
    }

    /// **The chromatic bridge.** Shareshian–Wachs define `X_Γ(x;q)` by summing
    /// `q^{asc}` over *proper* colorings; the LLT side sums over *all* of them
    /// and undoes the difference with a `(q−1)`-plethysm. Both are computed
    /// here and they must meet.
    #[test]
    fn the_chromatic_bridge_is_shareshian_wachs() {
        for n in 0..=5usize {
            for_each_area(n, &mut |area| {
                let g = DecoratedGraph::unit_interval(area);
                let got: Monomial<QtPoly<Rational>> = chromatic_from_llt(&g);
                assert_eq!(got, proper_colorings(&g), "area {area:?}");
            });
        }
    }

    /// The graph must keep its isolated vertices. A two-vertex edgeless graph
    /// is not the empty graph, and collapsing it is a silent way to a plausible
    /// wrong answer.
    #[test]
    fn isolated_vertices_survive() {
        let g = DecoratedGraph::new(2, &[], &[]);
        let x: Monomial<QtPoly<Rational>> = chromatic_from_llt(&g);
        assert_eq!(x.coeff(&part(&[2])), <QtPoly<Rational> as Ring>::one());
        assert_eq!(
            x.coeff(&part(&[1, 1]))
                .eval(&Rational::from_int(1), &Rational::from_int(1)),
            Rational::from_int(2)
        );
    }

    /// `Σ_{proper κ} q^{asc(κ)} x^κ`, straight from Shareshian–Wachs.
    fn proper_colorings(g: &DecoratedGraph) -> Monomial<QtPoly<Rational>> {
        let n = g.n as usize;
        let edges: Vec<(u32, u32)> = g.weak.iter().map(|&(u, v)| (u.min(v), u.max(v))).collect();
        let mut out = Monomial::zero();
        for mu in crate::partitions_of(g.n) {
            let nvals = mu.len();
            let mut counts: Vec<u32> = mu.parts().to_vec();
            let mut kappa: Vec<u32> = Vec::with_capacity(n);
            let mut acc: QtPoly<Rational> = QtPoly::zero();
            proper_rec(n, nvals, &edges, &mut counts, &mut kappa, &mut acc);
            out.add_term(mu, acc);
        }
        out
    }

    fn proper_rec(
        n: usize,
        nvals: usize,
        edges: &[(u32, u32)],
        counts: &mut [u32],
        kappa: &mut Vec<u32>,
        acc: &mut QtPoly<Rational>,
    ) {
        let v = kappa.len();
        if v == n {
            let asc = edges
                .iter()
                .filter(|&&(a, b)| kappa[a as usize] < kappa[b as usize])
                .count() as u32;
            acc.add_term(asc, 0, Rational::from_int(1));
            return;
        }
        for j in 0..nvals {
            if counts[j] == 0 {
                continue;
            }
            let c = j as u32 + 1;
            if edges
                .iter()
                .any(|&(a, b)| b as usize == v && kappa[a as usize] == c)
            {
                continue;
            }
            counts[j] -= 1;
            kappa.push(c);
            proper_rec(n, nvals, edges, counts, kappa, acc);
            kappa.pop();
            counts[j] += 1;
        }
    }

    /// `p(q + d, t)`, by the binomial theorem. The \[AS\] formula lands on
    /// `G(x; q+1)`, so comparing it with `G` needs one of these in each
    /// direction.
    fn shift_q<C: Ring>(p: &QtPoly<C>, d: i64) -> QtPoly<C> {
        let mut out = QtPoly::zero();
        for (&(a, b), c) in p.terms() {
            let mut binom: i128 = 1;
            for i in (0..=a).rev() {
                // binom = C(a, i)
                let scale = binom * (d as i128).pow(a - i);
                out.add_term(i, b, C::from_i128(scale).mul(c));
                if i > 0 {
                    binom = binom * i as i128 / (a - i + 1) as i128;
                }
            }
        }
        out
    }

    /// **The \[AS\] orientation formula**, on the unicellular corpus: the
    /// e-expansion of `G(x; q+1)` must reproduce `G` after `q ↦ q−1`. And by
    /// \[DA\]'s theorem the coefficients are non-negative — a theorem, so a
    /// violation here is a bug in this crate, the *reverse* of the rule in
    /// `every_path_piece_is_schur_positive`.
    #[test]
    fn the_as_orientation_formula_reproduces_g() {
        for n in 0..=5usize {
            for_each_area(n, &mut |area| {
                let g = DecoratedGraph::unit_interval(area);
                let e = llt_e_expansion::<i64>(&g);
                for (lambda, p) in &e {
                    for (_, c) in p.terms() {
                        assert!(*c >= 0, "[DA] positivity fails on e_{lambda}: our bug");
                    }
                }
                let mut got: Elementary<Q> = Elementary::zero();
                for (lambda, p) in e {
                    got.add_term(lambda, shift_q(&p, -1));
                }
                let want: Elementary<Q> = Elementary::from_schur(&llt_graph::<i64>(&g).to_schur());
                assert_eq!(got, want, "area {area:?}");
            });
        }
    }

    /// **\[AS\] Ex 6.1** and **\[DA\] Ex 5.6**, the two published Schröder-path
    /// fixtures. Words are a test constructor, not API: graphs are the API.
    #[test]
    fn published_schroder_fixtures() {
        let g = graph_from_word("nndee");
        let s = llt_graph::<i64>(&g).to_schur();
        assert_eq!(s.coeff(&part(&[1, 1, 1])), poly(&[(2, 1)]), "[AS] Ex 6.1");
        assert_eq!(s.coeff(&part(&[2, 1])), poly(&[(1, 1)]), "[AS] Ex 6.1");
        assert_eq!(s.terms().len(), 2);

        let g = graph_from_word("ndndee");
        let e: Elementary<Q> = Elementary::from_schur(&llt_graph::<i64>(&g).to_schur());
        // q e_1 e_3 + q(q−1) e_4
        assert_eq!(e.coeff(&part(&[3, 1])), poly(&[(1, 1)]), "[DA] Ex 5.6");
        assert_eq!(
            e.coeff(&part(&[4])),
            poly(&[(1, -1), (2, 1)]),
            "[DA] Ex 5.6"
        );
        assert_eq!(e.terms().len(), 2);
    }

    /// A Schröder path word in `{n, e, d}` to its decorated graph, \[AS\] §2.6:
    /// vertices along the diagonal, an edge when the cell is below the path,
    /// and a diagonal step makes its endpoint pair strict.
    fn graph_from_word(word: &str) -> DecoratedGraph {
        let (mut x, mut y) = (0i64, 0i64);
        let mut colheight: Vec<i64> = Vec::new();
        let mut diag: Vec<(usize, usize)> = Vec::new();
        for st in word.chars() {
            match st {
                'n' => y += 1,
                'e' => {
                    colheight.push(y);
                    x += 1;
                }
                'd' => {
                    colheight.push(y + 1);
                    x += 1;
                    y += 1;
                    diag.push((x as usize, y as usize));
                }
                c => panic!("unexpected step {c}"),
            }
        }
        let n = x as usize;
        let mut weak = Vec::new();
        for u in 1..=n {
            for v in (u + 1)..=n {
                if (v as i64) <= colheight[u - 1] {
                    weak.push(((u - 1) as u32, (v - 1) as u32));
                }
            }
        }
        let strict: Vec<(u32, u32)> = diag
            .iter()
            .map(|&(u, v)| ((u - 1) as u32, (v - 1) as u32))
            .collect();
        // A diagonal step's endpoint pair is also below the path, so the cell
        // rule already emitted it; the strict decoration replaces it rather than
        // joining it.
        weak.retain(|e| !strict.contains(e));
        DecoratedGraph::new(n as u32, &weak, &strict)
    }

    /// **The \[HHL\] assembly**: the fourth route to `H̃_μ`, against the three
    /// in [`crate::qtkostka`].
    #[test]
    fn the_hhl_assembly_is_htilde() {
        for n in 0..=4u32 {
            for mu in crate::partitions_of(n) {
                let got = htilde_by_llt::<i64>(&mu).to_schur();
                let want = crate::qtkostka::macdonald_ht::<i64>(&mu);
                assert_eq!(got, want, "H̃_{mu} by LLT decomposition");
            }
        }
    }

    /// **R3**: the Fock column against the ribbon side, at `q = −v`.
    ///
    /// The range is chosen to *pin the variable dictionary*, not for coverage.
    /// A single monomial cannot tell `q = −v` from its mirrors, so the sweep
    /// has to reach a multi-term Kazhdan–Lusztig entry, and the final assertion
    /// fails if it does not.
    ///
    /// ⚠️ The prototype swept k = 2 through degree 4 and believed that pinned
    /// the dictionary. It does not: **every** Schur coefficient of `G_LT` at
    /// k = 2 is a single monomial through |μ| = 10. The first multi-term
    /// entries are at **k = 3** — `s_{21}` in `G_LT,(3,3,3)` is `q² + q⁴`, and
    /// \[LT\] Ex 4.1's `q³ + q⁵` on `s_{211}` is the k = 3 shape (3,3,3,2,1).
    /// So the k = 2-only sweep did not in fact pin `q = −v`; this test does,
    /// and the `multi > 0` assertion below is what keeps it honest.
    #[test]
    fn fock_straightening_is_the_ribbon_column_at_q_eq_minus_v() {
        let mut multi = 0;
        for (k, top) in [(2u32, 4u32), (3, 3)] {
            for lambda in (1..=top).flat_map(crate::partitions_of) {
                let got: HashMap<Partition, Q> =
                    llt_kl_column::<i64>(&lambda, k).into_iter().collect();
                for mu in crate::partitions_of(k * lambda.size()) {
                    let s: Schur<Q> = llt_g_lt::<i64>(&mu, k).to_schur();
                    let c = s.coeff(&lambda);
                    if c.terms().count() > 1 {
                        multi += 1;
                    }
                    // q ↦ −v: negate the odd-degree coefficients.
                    let mut want = QtPoly::zero();
                    for (&(a, b), cc) in c.terms() {
                        let v = if a % 2 == 1 { cc.neg() } else { *cc };
                        want.add_term(a, b, v);
                    }
                    let have = got.get(&mu).cloned().unwrap_or_else(QtPoly::zero);
                    assert_eq!(have, want, "c^{lambda}_{mu} at k={k}, q = −v");
                }
            }
        }
        assert!(
            multi > 0,
            "no multi-term KL entry in range: the q = −v dictionary is untested"
        );
    }

    /// The block-prefix strip enumeration against the naive one: all
    /// `C(rows, m)` subsets, filtered. Same lemma, shared nothing.
    #[test]
    fn strip_blocks_agree_with_naive_subsets() {
        for k in 2..=4u32 {
            for n in 0..=8u32 {
                for lambda in crate::partitions_of(n) {
                    // `abacus_of` works on the *conjugate*, so the bead count is
                    // bounded below by λ₁, not by ℓ(λ).
                    let rows = lambda.part(0).max(1) as usize + 4;
                    if lambda.len() + rows + 4 >= 128 {
                        continue;
                    }
                    let beta = abacus_of(&lambda, rows);
                    for m in 0..=4u32 {
                        let mut got: Vec<(Abacus, u32)> = Vec::new();
                        let mut sc = StripScratch::default();
                        for_each_strip_up(beta, k, m, &mut sc, &mut |nb, spin| {
                            got.push((nb, spin))
                        });
                        got.sort_unstable();
                        let mut want = naive_strips(beta, rows, k, m);
                        want.sort_unstable();
                        assert_eq!(got, want, "λ={lambda} k={k} m={m} rows={rows}");
                    }
                }
            }
        }
    }

    /// The abacus containment test against the definition it replaced:
    /// build both shapes and ask [`Partition::contains`].
    #[test]
    fn abacus_containment_is_partition_containment() {
        for n in 0..=8u32 {
            for lambda in crate::partitions_of(n) {
                let rows = lambda.part(0).max(1) as usize + 3;
                let target = abacus_of(&lambda, rows);
                for m in 0..=n {
                    for nu in crate::partitions_of(m) {
                        if nu.len() > rows || nu.part(0) as usize > rows {
                            continue;
                        }
                        let beta = abacus_of(&nu, rows);
                        assert_eq!(
                            abacus_contained(beta, target),
                            lambda.contains(&nu),
                            "{nu} ⊆ {lambda}?"
                        );
                    }
                }
            }
        }
    }

    /// The all-weights-at-once walk the ribbon engine actually runs, against
    /// the fixed-weight one the test above pins to the naive subsets.
    ///
    /// Without this the chain is broken:
    /// `strip_blocks_agree_with_naive_subsets` checks `for_each_strip_up`,
    /// which after the R2 profiling work is used only by that test — production
    /// goes through `for_each_strip_any`.
    #[test]
    fn the_all_weights_walk_agrees_with_the_fixed_weight_one() {
        for k in 1..=4u32 {
            for n in 0..=8u32 {
                for lambda in crate::partitions_of(n) {
                    let rows = lambda.part(0).max(1) as usize + 4;
                    if lambda.len() + rows + 4 >= 128 {
                        continue;
                    }
                    let beta = abacus_of(&lambda, rows);
                    let max_w = 5u32;
                    let mut sc = StripScratch::default();
                    let mut got: Vec<(u32, Abacus, u32)> = Vec::new();
                    for_each_strip_any(beta, k, max_w, &mut sc, &mut |w, nb, spin| {
                        got.push((w, nb, spin))
                    });
                    got.sort_unstable();
                    let mut want: Vec<(u32, Abacus, u32)> = Vec::new();
                    for m in 1..=max_w {
                        for_each_strip_up(beta, k, m, &mut sc, &mut |nb, spin| {
                            want.push((m, nb, spin))
                        });
                    }
                    want.sort_unstable();
                    assert_eq!(got, want, "λ={lambda} k={k} rows={rows}");
                }
            }
        }
    }

    /// Every m-subset of the beads, moved `+k`, keeping the results distinct.
    fn naive_strips(beta: Abacus, rows: usize, k: u32, m: u32) -> Vec<(Abacus, u32)> {
        let beads: Vec<u32> = (0..128u32).filter(|&b| beta >> b & 1 == 1).collect();
        assert_eq!(beads.len(), rows);
        let mut out = Vec::new();
        for mask in 0u64..(1u64 << rows) {
            if (mask.count_ones()) != m {
                continue;
            }
            let mut moved: Abacus = 0;
            for (i, &b) in beads.iter().enumerate() {
                if mask >> i & 1 == 1 {
                    moved |= 1u128 << b;
                }
            }
            let unmoved = beta & !moved;
            let shifted = moved << k;
            if shifted & unmoved != 0 {
                continue;
            }
            let mut cross = 0u32;
            for i in 1..k {
                cross += ((moved << i) & unmoved).count_ones();
            }
            out.push((unmoved | shifted, (k - 1) * m - cross));
        }
        out
    }

    /// The pruned single-shape walk and the unpruned whole-degree walk are
    /// different traversals of the same tree and must land on the same numbers.
    #[test]
    fn the_two_walks_agree() {
        for k in 1..=3u32 {
            for n in 0..=4u32 {
                let table: Vec<(Partition, Monomial<Q>)> = llt_gtilde_table(n, k);
                for (lambda, got) in &table {
                    assert_eq!(*got, llt_gtilde::<i64>(lambda, k), "λ={lambda} k={k}");
                }
                // and nothing with an empty k-core is missing
                for lambda in crate::partitions_of(k * n) {
                    if lambda.has_empty_k_core(k) {
                        assert!(
                            table.iter().any(|(l, _)| *l == lambda),
                            "{lambda} missing from the k={k} degree-{n} table"
                        );
                    }
                }
            }
        }
    }

    /// The `H` table must agree term for term with the one-at-a-time calls.
    #[test]
    fn h_table_agrees_with_individual_calls() {
        for k in 1..=3u32 {
            for n in 0..=4u32 {
                for (mu, got) in llt_h_table::<i64>(n, k) {
                    assert_eq!(got, llt_h::<i64>(&mu, k), "H^({k})_{mu}");
                }
            }
        }
    }

    /// **Fixed-width honesty**: the same computation at two coefficient widths.
    /// A silent `i64` wrap would show up as a disagreement with `i128`.
    #[test]
    fn fixed_width_ladders_agree() {
        for k in 1..=3u32 {
            for n in 0..=4u32 {
                for mu in crate::partitions_of(n) {
                    let narrow: Monomial<QtPoly<i64>> = llt_h(&mu, k);
                    let wide: Monomial<QtPoly<i128>> = llt_h(&mu, k);
                    assert_eq!(narrow.terms().len(), wide.terms().len(), "{mu} at k={k}");
                    for (nu, p) in narrow.terms() {
                        let w = wide.coeff(nu);
                        for (&(a, b), c) in p.terms() {
                            assert_eq!(i128::from(*c), w.coeff(a, b), "{mu}/{nu} at k={k}");
                        }
                    }
                }
            }
        }
    }

    /// The fundamental expansion is a refinement of the monomial one: summing
    /// the compositions that refine μ must give `[m_μ] G_ν`.
    #[test]
    fn the_fundamental_expansion_refines_the_monomial_one() {
        for shapes in [
            &[&[2u32][..], &[1]][..],
            &[&[1], &[1], &[1]],
            &[&[2, 1], &[2]],
        ] {
            let nu = tuple(shapes);
            let f = llt_fundamental::<i64>(&nu);
            let m: Monomial<Q> = llt_g(&nu);
            let total: u32 = f.iter().map(|(c, _)| c.iter().sum::<u32>()).max().unwrap();
            assert_eq!(total, nu.size() as u32, "compositions of n");
            for mu in crate::partitions_of(nu.size() as u32) {
                let allowed = partial_sum_mask(&mu);
                let mut acc = QtPoly::zero();
                for (comp, p) in &f {
                    let mut mask = 0u64;
                    let mut acc_s = 0u32;
                    for &c in &comp[..comp.len() - 1] {
                        acc_s += c;
                        mask |= 1u64 << (acc_s - 1);
                    }
                    if mask & !allowed == 0 {
                        acc.add_assign(p);
                    }
                }
                assert_eq!(acc, m.coeff(&mu), "[m_{mu}]");
            }
        }
    }
}