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
//! The basis-change engine: conversions between all six classical bases,
//! routed through the Schur hub except where a pair has a direct rule.
//!
//! Each basis implements [`ToSchur`] (expand into the Schur basis) and
//! [`FromSchur`] (contract a Schur element into this basis); [`convert`] then
//! composes them to reach any ordered pair. The per-basis algorithms are the
//! classical ones:
//!
//! | conversion            | method                                  | ring    |
//! |-----------------------|-----------------------------------------|---------|
//! | h → s, e → s          | products of one-row / one-column Schurs | ℤ       |
//! | s → h                 | Jacobi–Trudi, by signed permutations    | ℤ       |
//! | s → e                 | dual Jacobi–Trudi, likewise             | ℤ       |
//! | p → s                 | iterated Murnaghan–Nakayama             | ℤ       |
//! | s → p                 | s_λ = Σ z_μ⁻¹ χ^λ(μ) p_μ                 | **ℚ**   |
//! | s → m                 | Kostka numbers, per pair or one Pieri trie | ℤ    |
//! | m → s                 | Muir's rule                             | ℤ       |
//! | f ↔ s                 | the m conversion, composed with ω        | ℤ       |
//!
//! The hub is skipped wherever a pair has a direct rule
//! ([`FromSchur::from_basis`]): the six ordered pairs among h, e and p, which
//! are each free multiplicative bases and so need only their generators
//! expanded in each other, and the four pairs out of h and e into m and f,
//! whose coefficients count matrices:
//!
//! | conversion            | method                                  | ring    |
//! |-----------------------|-----------------------------------------|---------|
//! | p → h, p → e          | Newton's identity, one generator at a time | ℤ    |
//! | h → p, e → p          | the two halves of Cauchy, p_μ/z_μ       | **ℚ**   |
//! | h → e, e → h          | Newton's identity for the h/e pair       | ℤ       |
//! | h → m, e → m          | matrix counts with the given margins     | ℤ       |
//! | h → f, e → f          | the same counts, crossed by ω            | ℤ       |
//!
//! Going through Schur instead is not merely a longer road: it *inflates*. A
//! power-sum element with a handful of terms becomes a Schur element with p(n)
//! of them, and the contraction that follows is then p(n) determinants. That
//! cost is what the direct rules remove (`docs/record/transitions.md`).
//!
//! Only the conversions *into* p divide, and what they need is a [`QAlgebra`] —
//! a ring containing ℚ — not a [`Field`](crate::coeff::Field). The division is
//! by z_μ, an *integer*, so `ℚ[t]` and `ℚ[q,t]` qualify even though neither is
//! a field. Every other path stays exact over ℤ.
//!
//! In Sage these conversions are basis coercions —
//! `Sym = SymmetricFunctions(QQ)`, then `h(s[lam])`. The ordered pairs among
//! s, e, h, m and p dispatch into Symmetrica's C. Symmetrica has no forgotten
//! basis, so the f pairs fall back to Sage's own Python
//! (`scripts/compare_sage.py`, `docs/record/transitions.md`).
//!
//! ## References
//!
//! - **\[M\]** I. G. Macdonald, *Symmetric Functions and Hall Polynomials*,
//!   2nd ed., Oxford, 1995 — for the tables above: Jacobi–Trudi is
//!   I (3.4), in the signed-permutation form (3.4'), and its dual is (3.5);
//!   p → s is I (7.8), with characters from the Murnaghan–Nakayama rule, I.7
//!   Example 5; s → m is the Kostka numbers of I (6.4); Newton's identities
//!   are I (2.11) and (2.11'); the p-expansions of `h_n` and `e_n` are
//!   I (2.14); the matrix counts are I (6.7), and their ω-crossed forms
//!   `M(e, m) = M(h, f)` and `M(h, m) = M(e, f)` are I (6.6)(iii) and (iv);
//!   ω on Schur functions is I (3.8).
//! - **\[ER\]** Ö. Eğecioğlu, J. B. Remmel, *A combinatorial interpretation
//!   of the inverse Kostka matrix*, Linear and Multilinear Algebra **26**
//!   (1990) — Theorem 1, `(K⁻¹)_{μλ}`, the m → s coefficient, as a signed
//!   count of special rim hook tabloids of shape λ and type μ: rim hooks of
//!   sizes `μᵢ`, each with a cell in the first column.
//! - **\[Mu\]** T. Muir, *A treatise on the theory of determinants*,
//!   Macmillan, London, 1882 — the rule `s_ν m_α = Σ_β s_{ν+β}`, over the
//!   distinct rearrangements β of α with each term straightened; at ν = ∅ it
//!   is the m → s row above. \[Mu\] is cited through \[DLT\] §9, which states
//!   the rule, credits it to Muir, and gives Littlewood, *Modular
//!   representations of symmetric groups*, Proc. Roy. Soc. A **209** (1951),
//!   as a second source.
//! - **\[DLT\]** J. Désarménien, B. Leclerc, J.-Y. Thibon, *Hall-Littlewood
//!   functions and Kostka-Foulkes polynomials in representation theory*,
//!   Sém. Lothar. Combin. **32** (1994), B32c — §9, the statement of \[Mu\]'s
//!   rule.

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

use crate::character::character_in;
use crate::coeff::{QAlgebra, Ring};
use crate::fasthash::Map;
use crate::interrupt;
use crate::kostka::kostka;
use crate::memo::{inverse_kostka_row_cached, jt_row_cached, lex_parts_cached, partitions_cached};
use crate::partition::Partition;
use crate::sym::{
    Elementary, Forgotten, Homogeneous, Monomial, PowerSum, Schur, SymAlgebra, SymFn,
};

/// Expand `self` into the Schur basis.
pub trait ToSchur<C: Ring> {
    /// The same element, written in the Schur basis.
    fn to_schur(&self) -> Schur<C>;
}

/// Contract a Schur element into `Self`'s basis.
pub trait FromSchur<C: Ring>: Sized {
    /// The same element, written in `Self`'s basis.
    fn from_schur(s: &Schur<C>) -> Self;

    /// A route from the basis whose [`SymFn::SYMBOL`] is `src` that reaches
    /// `Self` **without** passing through Schur, or `None` when there is none.
    ///
    /// The hub is a cost, not just a convention: `p → s → h` inflates a
    /// power-sum element with a handful of terms into a Schur element with
    /// p(n) of them, and only then contracts. Overriding this is how a pair
    /// with a direct rule skips that, and [`convert`] prefers it whenever it
    /// answers.
    ///
    /// It is keyed on the *source symbol* rather than on the source type
    /// because that is what makes the bound land where it belongs: h → p
    /// divides by z_μ and so is only available over a [`QAlgebra`], while
    /// p → h is integral. A generic `convert` cannot state either condition,
    /// and each impl states its own.
    ///
    /// # Examples
    ///
    /// p_2 = 2h_2 − h_{(1,1)}, whose signs and the factor 2 are what separate
    /// Newton's identity from the two rival expansions that agree on p_1:
    ///
    /// ```
    /// use symfn::convert::{convert, FromSchur, ToSchur};
    /// use symfn::partition::Partition;
    /// use symfn::sym::{Homogeneous, PowerSum, SymFn};
    ///
    /// let p2: PowerSum<i64> = PowerSum::monomial(Partition::new([2]), 1);
    /// let h: Homogeneous<i64> = convert(&p2);
    /// assert_eq!(h.coeff(&Partition::new([2])), 2);
    /// assert_eq!(h.coeff(&Partition::new([1, 1])), -1);
    ///
    /// // The same answer the Schur hub gives, which is what `convert` skipped.
    /// assert_eq!(h, Homogeneous::from_schur(&p2.to_schur()));
    /// ```
    fn from_basis(src: &'static str, terms: &BTreeMap<Partition, C>) -> Option<Self> {
        let _ = (src, terms);
        None
    }
}

/// Convert between any two bases: by the direct rule when the pair has one,
/// otherwise by composing through Schur.
///
/// Every pair stays exact over ℤ except the conversions into p. Those divide
/// by z_μ, so their [`FromSchur`] impls are bound on [`QAlgebra`] rather than
/// on [`Ring`].
pub fn convert<C, A, B>(a: &A) -> B
where
    C: Ring,
    A: SymFn<C> + ToSchur<C>,
    B: FromSchur<C>,
{
    match B::from_basis(A::SYMBOL, a.terms()) {
        Some(b) => b,
        None => B::from_schur(&a.to_schur()),
    }
}

// --- Schur: the hub, identity both ways -------------------------------------

impl<C: Ring> ToSchur<C> for Schur<C> {
    fn to_schur(&self) -> Schur<C> {
        self.clone()
    }
}
impl<C: Ring> FromSchur<C> for Schur<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        s.clone()
    }
}

// --- the Jacobi–Trudi determinants ------------------------------------------

/// The determinant det(y_{c_i − i + j})_{i,j} expanded over a **free
/// multiplicative** basis, as a signed list of partitions.
///
/// Both Jacobi–Trudi determinants have this shape, and both are taken over a
/// basis (h or e) whose elements are indexed by partitions and multiply by
/// *concatenating* indices: y_a · y_b = y_{a ∪ b}. So a single permutation term
///
/// ```text
///   sgn(w) · ∏_i y_{c_i − i + w(i)}
/// ```
///
/// is one signed **monomial** y_μ, with μ the sorted multiset {c_i − i + w(i)}.
/// The whole determinant is therefore a signed count of permutations grouped by
/// that multiset — no polynomial arithmetic anywhere.
///
/// That is what keeps it cheap. A generic Laplace expansion over the
/// symmetric-function algebra instead clones an (n−1)×(n−1) matrix of
/// *polynomials* at every node and does a full polynomial add and multiply per
/// term, at a cost factorial in the matrix size. The matrix size is ℓ(λ) for
/// s → h but **λ₁** for s → e, since that one is built from the conjugate.
/// Same helper, opposite behavior: s → h stayed fast on the wide-but-shallow
/// shapes a degree ladder produces. s → e crossed over and fell behind Sage
/// past degree 16 (`scripts/compare_sage.py`).
///
/// Enumerating permutations directly also prunes where the determinant is
/// sparse: a negative index means the entry is zero, so that whole subtree is
/// skipped rather than multiplied out.
///
/// **Rows are assigned from the last to the first, and that is the whole
/// performance story.** Entry (i, j) vanishes when j < i - c_i, and c is weakly
/// decreasing, so i - c_i *increases* with i: the constraint tightens as the
/// row index grows. Walking rows forward therefore starts at the least
/// constrained row - row 0 accepts any column - and only meets the dead ends
/// near the leaves, long after the branching has happened. Walking them
/// backwards puts the tightest row first, so whole subtrees die at depth 1.
///
/// The difference is not a constant factor. Symmetrica's `tsh_jt` builds the
/// transposed matrix (lambda_i + i - j, invalid when j > lambda_i + i), which
/// puts its tight row first for free: the same determinant and the same
/// algorithm, with the orientation accounting for the entire gap
/// (`docs/record/transitions.md`).
fn jt_terms(c: &[u32]) -> Vec<(Partition, i64)> {
    if c.is_empty() {
        return vec![(Partition::default(), 1)];
    }
    let mut acc: HashMap<Partition, i64> = HashMap::new();
    let mut used = vec![false; c.len()];
    let mut idx: Vec<u32> = Vec::with_capacity(c.len());
    jt_rec(c, c.len(), &mut used, &mut idx, 1, &mut acc);
    acc.into_iter().filter(|(_, s)| *s != 0).collect()
}

/// The same determinant, expanded into ordered **compositions** instead of
/// sorted multisets.
///
/// [`jt_terms`] can sort each permutation term because its basis multiplies by
/// concatenation — `h_a · h_b` does not care which came first. The Macdonald
/// operator does: its eigenvalue `[|α|] = Σ_i q^{α_i} t^{n−i}` reads α
/// *positionally*, so the same multiset in two orders is two different
/// polynomials. This visits each permutation term with α laid out **by column**
/// — the index the consumer needs; see the note at the assignment.
///
/// Deliberately a sibling rather than a refactor of [`jt_terms`] into a shared
/// callback. That one is on the `s → h` and `s → e` hot paths, which are fast
/// precisely because no polynomial arithmetic happens and terms aggregate into
/// a `HashMap` as they are found. Threading a caller's closure through it would
/// put an indirect call in that inner loop. That path took `s → e` on λ=(14)
/// from 1.5 seconds to microseconds (`docs/record/transitions.md`). The pruning
/// argument in [`jt_terms`] — rows assigned last to first, so the tightest
/// constraint is met at depth 1 — is the part that matters and it is reproduced
/// here.
pub(crate) fn jt_compositions(c: &[u32], visit: &mut impl FnMut(&[u32], i64)) {
    if c.is_empty() {
        visit(&[], 1);
        return;
    }
    let mut used = vec![false; c.len()];
    let mut alpha = vec![0u32; c.len()];
    jtc_rec(c, c.len(), &mut used, &mut alpha, 1, visit);
}

// Jacobi–Trudi index arithmetic. `c[row]`, `row` and `j` are all bounded by
// ℓ(λ) and λ₁, both `u32` in `Partition`, and the guarded subtraction is what
// keeps the result non-negative — the value is a part, not a coefficient.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
fn jtc_rec(
    c: &[u32],
    i: usize,
    used: &mut [bool],
    alpha: &mut [u32],
    sign: i64,
    visit: &mut impl FnMut(&[u32], i64),
) {
    if i == 0 {
        visit(alpha, sign);
        return;
    }
    let row = i - 1;
    let mut below = 0i64;
    let lo = (row as i64 - c[row] as i64).max(0) as usize;
    for &u in used.iter().take(lo) {
        if u {
            below += 1;
        }
    }
    for j in lo..c.len() {
        if used[j] {
            below += 1;
            continue;
        }
        used[j] = true;
        // Indexed by **column**, not by row, and not pushed in visit order.
        // The consumer pairs position with a power of t, and in Lapointe-
        // Lascoux-Morse (IMRN 1998 no. 18, 957-978; arXiv:math/9808050) that
        // power comes from which column of the determinant the permutation
        // selected -- their 3.5, via the formal operators of their 2.4. See
        // `macop::eigenvalue`. Both other choices produce a plausible
        // triangular matrix with distinct eigenvalues and the wrong Macdonald
        // polynomials.
        alpha[j] = (c[row] as i64 - row as i64 + j as i64) as u32;
        let s = if below % 2 == 0 { sign } else { -sign };
        jtc_rec(c, row, used, alpha, s, visit);
        used[j] = false;
    }
}

/// Assign row `i - 1`, rows `i..` being already placed.
// As `jtc_rec`: subscripts of h, bounded by the shape, never coefficients.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
fn jt_rec(
    c: &[u32],
    i: usize,
    used: &mut [bool],
    idx: &mut Vec<u32>,
    sign: i64,
    acc: &mut HashMap<Partition, i64>,
) {
    if i == 0 {
        // `Partition::new` drops the zero indices (y_0 is the unit) and sorts.
        *acc.entry(Partition::new(idx.iter().copied())).or_insert(0) += sign;
        return;
    }
    let row = i - 1;
    // Rows after this one are already placed, so choosing w(row) = j inverts
    // against every *used* column beneath j - the mirror of the forward walk,
    // which counted the unused ones.
    let mut below = 0i64;
    // Every column below this is a zero entry, so the scan can start there.
    let lo = (row as i64 - c[row] as i64).max(0) as usize;
    for &u in used.iter().take(lo) {
        if u {
            below += 1;
        }
    }
    for j in lo..c.len() {
        if used[j] {
            below += 1;
            continue;
        }
        let k = c[row] as i64 - row as i64 + j as i64;
        used[j] = true;
        idx.push(k as u32);
        let s = if below % 2 == 0 { sign } else { -sign };
        jt_rec(c, row, used, idx, s, acc);
        idx.pop();
        used[j] = false;
    }
}

/// [`jt_terms`] behind the row cache, which is what makes a *repeated* small
/// conversion cheap. The determinant does not depend on the coefficient ring or
/// on the coefficient, so the row is shared by every caller that mentions the
/// index.
fn jt_row(index: &Partition) -> std::sync::Arc<Vec<(Partition, i64)>> {
    jt_row_cached(index, || jt_terms(index.parts()))
}

// --- Homogeneous <-> Schur --------------------------------------------------

impl<C: Ring> ToSchur<C> for Homogeneous<C> {
    fn to_schur(&self) -> Schur<C> {
        // h_λ = ∏_i h_{λ_i} = ∏_i s_{(λ_i)}, each factor a Pieri step.
        expand_multiplicative(self, false)
    }
}

impl<C: Ring> FromSchur<C> for Homogeneous<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        // s_λ = det(h_{λ_i − i + j}); the matrix is ℓ(λ)×ℓ(λ).
        contract_multiplicative(s, false)
    }

    fn from_basis(src: &'static str, terms: &BTreeMap<Partition, C>) -> Option<Self> {
        match src {
            "p" => Some(multiplicative_route(terms, |n| {
                power_generator::<C, Self>(n, false)
            })),
            "e" => Some(multiplicative_route(terms, flip_generator::<C, Self>)),
            _ => None,
        }
    }
}

// --- Elementary <-> Schur ---------------------------------------------------

impl<C: Ring> ToSchur<C> for Elementary<C> {
    fn to_schur(&self) -> Schur<C> {
        // e_λ = ∏_i e_{λ_i} = ∏_i s_{(1^{λ_i})} (single columns), each factor
        // a Pieri step on the conjugate side.
        expand_multiplicative(self, true)
    }
}

/// h_λ and e_λ in the Schur basis, by **Pieri steps shared across terms**.
///
/// Both are products of one-row or one-column Schur functions. Building them
/// term by term — `Schur::unit()`, then one `Schur::mul` per part, then
/// `out.add(&prod.scale(c))` — puts almost the whole cost on those two lines
/// and almost all of the self time in the allocator
/// (`examples/profile_convert.rs`, `loop e2s 20`). Two things are wrong with
/// it.
///
/// * **The multiply was the general Littlewood–Richardson engine.**
///   `Schur::mul` routes to `AutoLr`, which built and expanded a skew shape
///   for what is a Pieri step: multiplying by s_{(k)} adds a horizontal
///   k-strip and by s_{(1^k)} a vertical one, both a direct enumeration with
///   no LR machinery under them. That is where the time was.
/// * **The layer was rebuilt per term.** `terms()` is a `BTreeMap` keyed by
///   `Partition`, which orders lexicographically by parts, so partitions
///   sharing their first `depth` parts are *already contiguous* — no sort
///   needed, unlike [`p_expand_shared`], which is handed a `Vec`. Each such
///   run continues from one layer instead of rebuilding it from the unit.
///
/// The sharing is the smaller half and was measured before it was written.
/// What it removes are the short cheap prefixes, while the leaves — the
/// expensive steps — are exactly what no two terms share. So the saving
/// weighted by the degree each step multiplies into is much smaller than the
/// step count suggests (`docs/record/transitions.md`). It is kept because it
/// is nearly free once the traversal is written this way, not because it
/// carries the win.
/// The layer is a **β-mask**, not a `Schur`. With the Pieri step in place the
/// profile is mostly allocator and `memmove`, with actual strip enumeration a
/// small minority of it: a `Schur<C>` is a `BTreeMap<Partition, C>`, so every
/// shape a step emitted allocated a heap `Vec<u32>`, sorted it, and memmoved
/// its way into a B-tree. On the β-mask the same step is bit arithmetic on a
/// `u64` in a `Map`, and partitions are built once per *output* term rather
/// than once per emitted shape — the same trade `p_expand` and `muir_expand`
/// already make.
///
/// Layer coefficients are `i128`, not `C`. Pieri's structure constants are all
/// 1, so a layer coefficient is a plain multiplicity. For h_μ that multiplicity
/// is the Kostka number K_{λμ}, bounded by f^λ ≤ √(n!). This path only runs for
/// n ≤ [`MASK_LIMIT`] = 32, where √(32!) ≈ 1.6·10¹⁸ sits far inside `i128`. So
/// no ring arithmetic happens in the sweep at all; `C` is touched once per
/// output term. Same narrowing argument, and the same bound, as [`p_expand`].
///
/// Terms are batched by degree because the mask width is |λ|, exactly as
/// `PowerSum::to_schur` batches for the same reason. Degrees past the mask
/// width take the partition-keyed [`expand_shared`] below, which has no wall.
fn expand_multiplicative<C: Ring, S: SymFn<C>>(x: &S, vertical: bool) -> Schur<C> {
    let mut out = Schur::zero();
    // `terms()` is ordered by `Partition`, i.e. lexicographically by parts, and
    // pushing in that order keeps each degree's group in it — which is what
    // makes shared prefixes contiguous without a sort.
    let mut by_degree: BTreeMap<u32, Vec<(&Partition, &C)>> = BTreeMap::new();
    for (lambda, c) in x.terms() {
        by_degree
            .entry(lambda.size())
            .or_default()
            .push((lambda, c));
    }
    for (n, items) in by_degree {
        let l = n as usize;
        if l == 0 {
            for (_, c) in &items {
                out.add_term(Partition::default(), (*c).clone());
            }
        } else if l > MASK_LIMIT {
            expand_shared(&items, 0, &Schur::unit(), vertical, &mut out);
        } else {
            // [`expand_shared`] on the β-mask layer: the leaf for h_μ is the
            // Schur expansion of h_μ itself, scattered into the output.
            pieri_trie(
                &items,
                0,
                &unit_mask_layer(l),
                vertical,
                &mut |_, c, layer| {
                    for (&mask, &v) in layer {
                        out.add_term(mask_to_partition(mask, l), C::from_i128(v).mul(*c));
                    }
                },
            );
        }
    }
    out
}

/// The layer holding s_∅ alone, on `l` slots: β-numbers {0, 1, …, l−1}.
pub(crate) fn unit_mask_layer(l: usize) -> Map<u64, i128> {
    let mut root: Map<u64, i128> = Map::default();
    root.insert((1u64 << l) - 1, 1);
    root
}

/// The β-mask of `lambda` in `l` slots: β_i = λ_i + (l − 1 − i). Requires
/// ℓ(λ) ≤ l and λ₁ + l ≤ 64.
pub(crate) fn beta_mask(lambda: &Partition, l: usize) -> u64 {
    let mut mask = 0u64;
    for i in 0..l {
        mask |= 1 << (lambda.part(i) as usize + (l - 1 - i));
    }
    mask
}

/// The trie of Pieri steps over `items`, on the β-mask layer.
///
/// Each item is a shape μ with a payload; the walk consumes μ's parts in order,
/// one [`pieri_masks`] step per part, so at μ's leaf `layer` is h_μ (or e_μ,
/// if `vertical`) in the Schur basis — mask → multiplicity — and `emit` is
/// handed the item and that layer. Items sharing a prefix share the steps
/// that build it, which is why `items` must be ordered so that equal prefixes
/// are contiguous: lexicographic order on parts, in either direction, does it.
/// The layer starts as `layer` at `depth` parts consumed, so a caller passes
/// [`unit_mask_layer`] and 0.
pub(crate) fn pieri_trie<X>(
    items: &[(&Partition, X)],
    depth: usize,
    layer: &Map<u64, i128>,
    vertical: bool,
    emit: &mut impl FnMut(&Partition, &X, &Map<u64, i128>),
) {
    let mut i = 0;
    while i < items.len() && items[i].0.len() == depth {
        emit(items[i].0, &items[i].1, layer);
        i += 1;
    }
    while i < items.len() {
        let k = items[i].0.part(depth);
        let start = i;
        while i < items.len() && items[i].0.part(depth) == k {
            i += 1;
        }
        let next = pieri_masks(layer, k, vertical);
        pieri_trie(&items[start..i], depth + 1, &next, vertical, emit);
    }
}

/// One Pieri step on a layer of β-masks.
fn pieri_masks(cur: &Map<u64, i128>, k: u32, vertical: bool) -> Map<u64, i128> {
    // As `p_step`: the layer grows through a sweep, so sizing to the input is
    // a floor on the output rather than a guess.
    let mut next: Map<u64, i128> = Map::with_capacity_and_hasher(cur.len() * 2, Default::default());
    let mut shapes = Vec::new();
    for (&mask, &c) in cur {
        shapes.clear();
        strip_masks(mask, k, vertical, &mut shapes);
        for &m in &shapes {
            *next.entry(m).or_insert(0) += c;
        }
    }
    next
}

/// Every β-mask reachable from `mask` by adding a horizontal — or, if
/// `vertical`, a vertical — strip of `k` cells.
///
/// **The two strip conditions are different constraints on the β-set, and this
/// is the trap.** Writing one and reusing it for the other produces plausible
/// wrong answers, not errors, so both are derived here rather than shared.
///
/// With β_i = λ_i + (l−1−i), strictly decreasing:
///
/// * **Horizontal.** μ/λ is a horizontal strip iff μ_i ≥ λ_i and μ_i ≤ λ_{i−1},
///   which in β reads β^λ_{i−1} > β^μ_i ≥ β^λ_i. Each β therefore moves up
///   *within its own interval*, bounded by the **original** β above it, and the
///   intervals are disjoint — so the choices are independent and no collision
///   test is needed.
/// * **Vertical.** μ_i ∈ {λ_i, λ_i + 1}, so each β either stays or moves up by
///   one, with no interval bound at all. What constrains it is that β^μ must
///   stay strictly decreasing, which binds only on adjacent β: the lower may
///   not step onto a higher one that stayed. Rows are walked from the **highest
///   β down**, so everything above is already final and that test is
///   sound — the same argument [`muir_rec`] makes for its collision check.
fn strip_masks(mask: u64, k: u32, vertical: bool, out: &mut Vec<u64>) {
    let mut bits: Vec<u32> = Vec::with_capacity(mask.count_ones() as usize);
    let mut rest = mask;
    while rest != 0 {
        let b = 63 - rest.leading_zeros();
        bits.push(b);
        rest &= !(1u64 << b);
    }
    // Suffix capacity: the most the β from position i down can absorb between
    // them. The topmost is unbounded, so only the deeper levels can dead-end.
    let mut cap = vec![0u32; bits.len() + 1];
    for i in (1..bits.len()).rev() {
        let room = if vertical {
            1
        } else {
            bits[i - 1] - 1 - bits[i]
        };
        cap[i] = cap[i + 1].saturating_add(room);
    }
    cap[0] = u32::MAX;

    fn rec(
        bits: &[u32],
        cap: &[u32],
        i: usize,
        left: u32,
        vertical: bool,
        acc: u64,
        out: &mut Vec<u64>,
    ) {
        if i == bits.len() {
            if left == 0 {
                out.push(acc);
            }
            return;
        }
        if left > cap[i] {
            return;
        }
        let b = bits[i];
        // The ceiling is the *original* β above, which is what makes the
        // horizontal intervals disjoint; see the note above.
        let hi = if vertical {
            b + 1
        } else if i == 0 {
            b + left
        } else {
            (bits[i - 1] - 1).min(b + left)
        };
        for nb in b..=hi {
            let used = nb - b;
            if used > left {
                break;
            }
            // Only the vertical case can collide, and only with a β that stayed.
            if vertical && used > 0 && acc >> nb & 1 == 1 {
                continue;
            }
            rec(
                bits,
                cap,
                i + 1,
                left - used,
                vertical,
                acc | (1u64 << nb),
                out,
            );
        }
    }
    rec(&bits, &cap, 0, k, vertical, 0, out);
}

/// Walk one prefix group, mirroring [`p_expand_shared`]'s shape.
fn expand_shared<C: Ring>(
    items: &[(&Partition, &C)],
    depth: usize,
    layer: &Schur<C>,
    vertical: bool,
    out: &mut Schur<C>,
) {
    let mut i = 0;
    // Partitions that end here: the layer is their whole product. Emitted
    // term by term into `out` rather than through `out.add(&layer.scale(c))`,
    // which allocated a scaled copy and then a merged map per input term.
    while i < items.len() && items[i].0.len() == depth {
        for (lambda, v) in layer.terms() {
            out.add_term(lambda.clone(), v.mul(items[i].1));
        }
        i += 1;
    }
    // The rest are grouped by their next part, each group sharing one step.
    while i < items.len() {
        let k = items[i].0.part(depth);
        let start = i;
        while i < items.len() && items[i].0.part(depth) == k {
            i += 1;
        }
        let next = pieri_step(layer, k, vertical);
        expand_shared(&items[start..i], depth + 1, &next, vertical, out);
    }
}

/// Multiply a Schur element by s_{(1^k)} (`vertical`) or s_{(k)}.
///
/// Pieri: s_λ · h_k = Σ s_μ over μ/λ a horizontal k-strip, and s_λ · e_k the
/// same over vertical strips. Coefficients are all 1, so this only ever moves
/// the caller's coefficient onto a new index — no ring multiplication happens.
fn pieri_step<C: Ring>(cur: &Schur<C>, k: u32, vertical: bool) -> Schur<C> {
    let mut next = Schur::zero();
    let mut shapes = Vec::new();
    for (lambda, c) in cur.terms() {
        shapes.clear();
        if vertical {
            vertical_strips(lambda.parts(), k, &mut shapes);
        } else {
            horizontal_strips(lambda.parts(), k, &mut shapes);
        }
        for mu in shapes.drain(..) {
            next.add_term(mu, c.clone());
        }
    }
    next
}

/// Every μ ⊇ λ with μ/λ a horizontal strip of `k` cells.
///
/// The strip condition is the interlacing μ₁ ≥ λ₁ ≥ μ₂ ≥ λ₂ ≥ … — at most one
/// new cell per column. Row `i` is therefore capped by λ_{i−1}, the *old*
/// value, and μ comes out weakly decreasing for free: μ_i ≤ λ_{i−1} ≤ μ_{i−1}.
fn horizontal_strips(lambda: &[u32], k: u32, out: &mut Vec<Partition>) {
    fn rec(i: usize, left: u32, lambda: &[u32], cur: &mut Vec<u32>, out: &mut Vec<Partition>) {
        // A strip can open at most one new row, so the walk ends one past λ.
        if i == lambda.len() + 1 {
            if left == 0 {
                out.push(Partition::new(cur.iter().copied()));
            }
            return;
        }
        let lam_i = lambda.get(i).copied().unwrap_or(0);
        let upper = if i == 0 {
            lam_i + left
        } else {
            lambda[i - 1].min(lam_i + left)
        };
        for v in lam_i..=upper {
            cur.push(v);
            rec(i + 1, left - (v - lam_i), lambda, cur, out);
            cur.pop();
        }
    }
    let mut cur = Vec::with_capacity(lambda.len() + 1);
    rec(0, k, lambda, &mut cur, out);
}

/// Every μ ⊇ λ with μ/λ a vertical strip of `k` cells.
///
/// No two cells in one row, so μ_i ∈ {λ_i, λ_i + 1} and the only other
/// constraint is that μ stay weakly decreasing. Unlike a horizontal strip this
/// may open up to `k` new rows, each holding one cell.
fn vertical_strips(lambda: &[u32], k: u32, out: &mut Vec<Partition>) {
    fn rec(
        i: usize,
        rows: usize,
        left: u32,
        prev: u32,
        lambda: &[u32],
        cur: &mut Vec<u32>,
        out: &mut Vec<Partition>,
    ) {
        if left == 0 {
            // Nothing left to place: the remaining rows keep their old values.
            let mut done = cur.clone();
            done.extend_from_slice(&lambda[i.min(lambda.len())..]);
            out.push(Partition::new(done));
            return;
        }
        // Each remaining row can absorb at most one cell.
        if i == rows || left as usize > rows - i {
            return;
        }
        let lam_i = lambda.get(i).copied().unwrap_or(0);
        if lam_i <= prev {
            cur.push(lam_i);
            rec(i + 1, rows, left, lam_i, lambda, cur, out);
            cur.pop();
        }
        if lam_i < prev {
            cur.push(lam_i + 1);
            rec(i + 1, rows, left - 1, lam_i + 1, lambda, cur, out);
            cur.pop();
        }
    }
    let rows = lambda.len() + k as usize;
    let mut cur = Vec::with_capacity(rows);
    rec(0, rows, k, u32::MAX, lambda, &mut cur, out);
}

impl<C: Ring> FromSchur<C> for Elementary<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        // s_λ = det(e_{λ'_i − i + j}); the matrix is λ₁×λ₁, being built from the
        // conjugate.
        contract_multiplicative(s, true)
    }

    fn from_basis(src: &'static str, terms: &BTreeMap<Partition, C>) -> Option<Self> {
        match src {
            "p" => Some(multiplicative_route(terms, |n| {
                power_generator::<C, Self>(n, true)
            })),
            "h" => Some(multiplicative_route(terms, flip_generator::<C, Self>)),
            _ => None,
        }
    }
}

/// The h ↔ e transition, one generator at a time.
///
/// Newton's identity for the elementary/complete pair, Σ_{k=0}^{n} (−1)^k e_k
/// h_{n−k} = 0, rearranged:
///
/// ```text
///   h_n = Σ_{k=1}^{n} (−1)^{k−1} e_k · h_{n−k}
/// ```
///
/// and *symmetrically* with h and e exchanged — the identity is invariant under
/// the swap, so a single routine serves both directions. Each step multiplies
/// by one generator, which in a multiplicative basis is a multiset union, so
/// this is a linear recursion over cheap products rather than anything
/// determinantal.
///
/// `gen[n]` is then the one-part generator of the *source* basis expanded in
/// the target, and a multi-part index is the product of those.
fn flip_generator<C: Ring, S: SymAlgebra<C>>(n: u32) -> S {
    // The table is the *same* for h→e and e→h, and its coefficients are
    // integers independent of `C`, so it is computed once in i64 and injected.
    // Recomputing it per call was the dominant cost of a flipped conversion:
    // the recursion touches O(n²) products over elements with up to p(n) terms,
    // which is cheap once and wasteful on every call.
    let row = flip_row(n);
    let mut x = S::zero();
    for (mu, c) in row.iter() {
        x.add_term(mu.clone(), C::from_i64(*c));
    }
    x
}

/// h_n in the e-basis (equivalently e_n in the h-basis) as integer terms,
/// one row per degree in the process-wide memo.
///
/// Row n is built from every row below it — the recursion appends one part
/// `k` to each term of row n − k — so the rows below are asked for through
/// the same memo and land there on the way. `memo::lookup` releases its read
/// guard before computing, which is what makes that recursion safe.
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
fn flip_row(n: u32) -> std::sync::Arc<Vec<(Partition, i64)>> {
    crate::memo::flip_row_cached(n, || {
        if n == 0 {
            return vec![(Partition::default(), 1)];
        }
        let mut acc: HashMap<Partition, i64> = HashMap::new();
        for k in 1..=n {
            let sign = if k % 2 == 1 { 1i64 } else { -1 };
            for (mu, c) in flip_row(n - k).iter() {
                let mut parts = mu.parts().to_vec();
                parts.push(k);
                *acc.entry(Partition::new(parts)).or_insert(0) += sign * c;
            }
        }
        acc.into_iter().filter(|(_, c)| *c != 0).collect()
    })
}

/// Pairs each multiplicative basis with the other, h with e, so a contraction
/// can be computed in whichever Jacobi–Trudi matrix is smaller.
///
/// An associated type rather than a flag, so "compute in whichever Jacobi–Trudi
/// matrix is smaller and flip back" is expressible without either basis naming
/// the other at the call site — and so the recursion that does it is checked to
/// terminate by the compiler rather than by argument.
pub trait Dual<C: Ring>: SymAlgebra<C> {
    /// The other multiplicative basis: [`Elementary`] for [`Homogeneous`], and
    /// back again, so the pair is its own inverse.
    type Other: SymAlgebra<C> + Dual<C, Other = Self>;
}

impl<C: Ring> Dual<C> for Homogeneous<C> {
    type Other = Elementary<C>;
}

impl<C: Ring> Dual<C> for Elementary<C> {
    type Other = Homogeneous<C>;
}

/// Re-express an element of one multiplicative basis in the other, h ↔ e.
///
/// This is what makes a *wide* shape cheap for s → e and a *tall* one cheap for
/// s → h: whichever Jacobi–Trudi matrix is smaller can be used, and the result
/// flipped into the basis actually wanted. ℓ(λ) and λ₁ are the two matrix sizes
/// and they trade off against each other, so taking the minimum turns each
/// direction's worst family into the other's best.
fn flip_basis<C: Ring, A: SymFn<C>, B: SymAlgebra<C>>(x: &A) -> B {
    multiplicative_route(x.terms(), flip_generator::<C, B>)
}

/// Rewrite a **free multiplicative** basis in another, given the source's
/// generators already expanded in the target.
///
/// h, e and p are each free on one generator per positive integer, and each
/// multiplies by index concatenation: x_μ · x_ν = x_{μ ∪ ν}. So an index of
/// several parts is the product of its parts' expansions, and the whole
/// transition is fixed by `gens[n]`, the source's n-th generator written in the
/// target. No determinant, no Schur hub, and no term of the target is ever
/// touched that the answer does not mention.
///
/// `gens[0]` is the unit; a partition has no zero part, so it is only ever read
/// when the index is empty.
fn multiplicative_route<C: Ring, B: SymAlgebra<C>>(
    terms: &BTreeMap<Partition, C>,
    generator: impl Fn(u32) -> B,
) -> B {
    // Only the parts actually mentioned. A single h_(18) names one generator,
    // and building the whole ladder up to it is four times the work of the
    // conversion — the peel that motivates these routes asks for one index at
    // a time, so that ladder would be rebuilt on every call.
    let mut gens: BTreeMap<u32, B> = BTreeMap::new();
    for mu in terms.keys() {
        for &part in mu.parts() {
            gens.entry(part).or_insert_with(|| generator(part));
        }
    }
    let mut out = B::zero();
    for (mu, c) in terms {
        // The product starts from the first generator, not from the unit —
        // `unit.times(gens[..])` is a full copy — and lands in the output term
        // by term rather than through `out.add(&prod.scale(c))`, which
        // allocated a scaled copy and then a merged map per input term. A
        // single-part index, the shape the peel hands this route, now costs
        // one pass over its generator.
        match mu.parts() {
            [] => out.add_term(Partition::default(), c.clone()),
            [first, rest @ ..] => {
                let mut prod: Option<B> = None;
                for part in rest {
                    let p = prod.as_ref().unwrap_or(&gens[first]);
                    prod = Some(p.times(&gens[part]));
                }
                for (nu, v) in prod.as_ref().unwrap_or(&gens[first]).terms() {
                    out.add_term(nu.clone(), v.mul(c));
                }
            }
        }
    }
    out
}

/// p_n expanded in the h-basis, as an integer term list.
///
/// Newton's identity n·h_n = Σ_{i=1}^{n} p_i h_{n−i}, rearranged so that the
/// unknown is alone:
///
/// ```text
///   p_n = n·h_n − Σ_{i=1}^{n−1} h_{n−i} · p_i
/// ```
///
/// Each term on the right multiplies an already-known p_i by the single
/// generator h_{n−i}, which in a multiplicative basis appends one part. So the
/// whole table is built by appending parts to earlier rows — the same shape as
/// [`flip_row`], and for the same reason.
///
/// The **e-basis needs no second table**: log E(t) = Σ (−1)^{r−1} p_r t^r / r
/// against log H(t) = Σ p_r t^r / r differs only by that sign, so p_n in e is
/// p_n in h with every coefficient scaled by (−1)^{n−1} and the letter changed.
///
/// Coefficients are `i128` rather than `i64` because the largest of them is
/// n·(ℓ−1)!/∏ m_i!, which counts compositions and so grows like 2^n; i64 would
/// cap the table near degree 60 while every other path here keeps going.
fn power_in_h_row(n: u32) -> std::sync::Arc<Vec<(Partition, i128)>> {
    crate::memo::power_in_h_row_cached(n, || {
        if n == 0 {
            return vec![(Partition::default(), 1)];
        }
        let mut acc: HashMap<Partition, i128> = HashMap::new();
        acc.insert(Partition::new([n]), i128::from(n));
        for i in 1..n {
            for (mu, c) in power_in_h_row(i).iter() {
                let mut parts = mu.parts().to_vec();
                parts.push(n - i);
                *acc.entry(Partition::new(parts)).or_insert(0) -= c;
            }
        }
        acc.into_iter().filter(|(_, c)| *c != 0).collect()
    })
}

/// p_n in the h-basis (`dual` false) or the e-basis (`dual` true), injected
/// into the coefficient ring.
fn power_generator<C: Ring, S: SymAlgebra<C>>(n: u32, dual: bool) -> S {
    // (−1)^{n−1} for n ≥ 1; the n = 0 row is the unit and unsigned.
    let flip = dual && n.is_multiple_of(2) && n > 0;
    let row = power_in_h_row(n);
    let mut x = S::zero();
    for (mu, c) in row.iter() {
        x.add_term(mu.clone(), C::from_i128(if flip { -c } else { *c }));
    }
    x
}

/// h_n (`dual` false) or e_n (`dual` true) in the power-sum basis.
///
/// ```text
///   h_n = Σ_{μ ⊢ n} p_μ / z_μ        e_n = Σ_{μ ⊢ n} (−1)^{n−ℓ(μ)} p_μ / z_μ
/// ```
///
/// the two halves of the Cauchy identity, and the only direction of this family
/// that divides. The division is by z_μ, an integer, which is what a
/// [`QAlgebra`] promises.
///
/// A ring that answers [`Ring::from_ratio`] gets ±1/z_μ **built in one step**.
/// The numerator is ±1, so there is no gcd to find, where dividing z_μ's
/// factors off one at a time reduces after every one. z_μ ≤ n! passes `i128`
/// at n = 34, so the one-step form is offered through 33. Everything else —
/// higher degrees, and rings with no ratio form, `BigRational` included —
/// takes [`Partition::div_by_z`], which never forms z_μ and so has no degree
/// ceiling of its own.
fn multiplicative_in_power<C: QAlgebra>(n: u32, dual: bool) -> PowerSum<C> {
    let mut x = PowerSum::zero();
    for mu in partitions_cached(n).iter() {
        let sign: i64 = if dual && (n as usize - mu.len()) % 2 == 1 {
            -1
        } else {
            1
        };
        // z_μ ≤ n! ≤ 33! < 2¹²³, so the conversion cannot fail under the gate.
        let c = if n <= 33 {
            C::from_ratio(
                sign.into(),
                i128::try_from(mu.z()).expect("z_mu <= 33! fits i128"),
            )
        } else {
            None
        }
        .unwrap_or_else(|| mu.div_by_z(&C::from_i64(sign)));
        x.add_term(mu.clone(), c);
    }
    x
}

/// Jacobi–Trudi matrix size past which the determinant is abandoned for a Muir
/// sweep.
///
/// [`jt_terms`] enumerates permutations, so it is exponential in the matrix
/// size — and the matrix is ℓ(λ) for s → h but **λ₁** for s → e. Both
/// directions therefore have a family of shapes that ruins them, and they are
/// each other's mirror image: s → e dies on a single long row, s → h on a
/// single tall column.
///
/// The cost is therefore set by λ₁, not by the degree, and it goes
/// exponential once λ₁ is large (`docs/record/transitions.md`).
///
/// `scripts/compare_sage.py` builds its shapes with several rows, so λ₁ stays
/// under 8 and no wide shape is covered there. `scripts/check_backend.py` lets
/// Sage pick the inputs, and reaches them.
///
/// Taking the smaller of the two matrices (see [`flip_basis`]) removes most of
/// the problem on its own, since a shape that is bad for one direction is good
/// for the other. What survives is the family bad for *both* — hooks, where
/// ℓ(λ) and λ₁ are each about |λ|/2.
///
/// The limit is set high because **the sweep is nearly always the worse of the
/// two**, which was not the expectation: a Muir sweep is p(n) expansions, and
/// p(n) grows at every degree while the determinant is only bad once the
/// matrix is genuinely large. So the sweep is a backstop against a
/// pathological shape, not a fast path, and the threshold sits where the
/// determinant finally stops being cheap (`docs/record/transitions.md`).
const JT_LIMIT: usize = 14;

/// Matrix size at which flipping to the conjugate basis starts to pay.
///
/// Flipping is *not* free — see [`flip_basis`] — and taking the smaller matrix
/// whenever it is smaller at all was measured worse in aggregate over every
/// partition of degree 20 (`docs/record/transitions.md`). A shape like
/// (5,5,5,5) has matrices of 4 and 5, and a 5-wide determinant is far cheaper
/// than expanding an h-element of degree 20 into e.
///
/// So the flip is reserved for the cases where the determinant is genuinely
/// exponential and the conjugate collapses it: a single row of degree 24,
/// whose h-expansion is the one term h_24. Below this size the direct
/// determinant always wins.
const FLIP_MIN: usize = 14;

/// s → h and s → e, which are the same computation on λ and on λ'.
///
/// Two routes, chosen per term by the matrix size:
///
/// * **the determinant**, for small matrices, via [`jt_terms`];
/// * **a Muir sweep**, for large ones, using
///
///   ```text
///     coefficient of h_μ in s_λ  =  coefficient of s_λ in m_μ
///   ```
///
///   which is just K⁻¹ read by column instead of by row: h_μ = Σ_λ K_{λμ} s_λ
///   gives s = (Kᵀ)⁻¹h, so the h-coefficients of s_λ are the λ-column of K⁻¹ —
///   and [`muir_expand`] already produces its rows, fast. Sweeping every μ ⊢ n
///   and keeping the λ entry costs p(n) expansions regardless of shape, which
///   is the same "a table is p(n) sweeps" trade as
///   [`kostka_table`](crate::kostka::kostka_table).
///
/// e is the conjugate case throughout: ω is an isometry with ω(h_μ) = e_μ, so
/// the e-coefficients of s_λ are the h-coefficients of s_{λ'}.
fn contract_multiplicative<C: Ring, S: Dual<C>>(s: &Schur<C>, dual: bool) -> S {
    let mut out = S::zero();
    // Terms needing the sweep, grouped by degree since a sweep serves a whole
    // degree at once.
    let mut swept: BTreeMap<u32, Vec<(Partition, C)>> = BTreeMap::new();
    // Terms cheaper in the *other* basis, to be flipped back at the end.
    let mut crossed: Schur<C> = Schur::zero();
    for (lambda, c) in s.terms() {
        let index = if dual {
            lambda.conjugate()
        } else {
            lambda.clone()
        };
        let other = index.conjugate();
        if index.len().min(other.len()) > JT_LIMIT {
            swept
                .entry(index.size())
                .or_default()
                .push((index, c.clone()));
        } else if index.len() >= FLIP_MIN && other.len() < index.len() {
            // The conjugate determinant is smaller: compute there and flip.
            crossed.add_term(lambda.clone(), c.clone());
        } else {
            // Accumulated into `out` directly rather than built and merged:
            // one element per input term is an allocation and a second pass
            // over the row, and this loop runs once per term of the input.
            for (mu, v) in jt_row(&index).iter() {
                out.add_term(mu.clone(), C::from_i64(*v).mul(c));
            }
        }
    }
    if !crossed.is_zero() {
        // `dual` is inverted, so this lands in the opposite basis; `flip_basis`
        // brings it back. Both are multiplicative, so the flip is the Newton
        // recursion above and never a determinant.
        let mirror: S::Other = contract_multiplicative(&crossed, !dual);
        out = out.add(&flip_basis::<C, _, S>(&mirror));
    }
    for (n, targets) in swept {
        match muir_column(&targets, n) {
            Some(terms) => {
                for (mu, v) in terms {
                    out.add_term(mu, v);
                }
            }
            // Past the β-mask width, where `muir_expand` declines. The
            // determinant has no wall, only a cost.
            None => {
                for (index, c) in &targets {
                    for (mu, v) in jt_row(index).iter() {
                        out.add_term(mu.clone(), C::from_i64(*v).mul(c));
                    }
                }
            }
        }
    }
    out
}

/// Σ_λ c_λ · (column λ of K⁻¹), by expanding every m_μ of degree `n` once.
fn muir_column<C: Ring>(targets: &[(Partition, C)], n: u32) -> Option<Vec<(Partition, C)>> {
    let want: HashMap<&Partition, &C> = targets.iter().map(|(p, c)| (p, c)).collect();
    let mut out = Vec::new();
    for mu in partitions_cached(n).iter() {
        let mut acc = C::zero();
        for (lambda, v) in muir_expand(mu)? {
            if let Some(c) = want.get(&lambda) {
                acc.add_assign(&C::from_i128(v).mul(c));
            }
        }
        if !acc.is_zero() {
            out.push((mu.clone(), acc));
        }
    }
    Some(out)
}

// --- PowerSum <-> Schur -----------------------------------------------------

impl<C: Ring> ToSchur<C> for PowerSum<C> {
    fn to_schur(&self) -> Schur<C> {
        let mut out = Schur::zero();
        // Terms are batched by degree, because p_μ and p_ν share Murnaghan–
        // Nakayama work whenever they share parts — and expanding each one
        // separately from ∅ throws all of that away. The β-mask width is |μ|,
        // so only equal degrees can share a sweep.
        let mut by_degree: HashMap<u32, Vec<(&Partition, &C)>> = HashMap::new();
        for (mu, c) in self.terms() {
            let n = mu.size();
            if n as usize <= WIDE_MASK_LIMIT {
                by_degree.entry(n).or_default().push((mu, c));
            } else {
                // Degree past what any β-mask holds: fall back to characters,
                // which are exact in `C` and so stay correct for bignum rings.
                // This is p(n) character recursions in the coefficient ring per
                // term, against one shared sweep below, and it is the slowest
                // reachable path in the crate — the reason the sweep is worth
                // widening at all (`docs/record/plethysm.md`).
                for lambda in partitions_cached(n).iter() {
                    interrupt::poll();
                    let chi = character_in::<C>(lambda, mu);
                    if !chi.is_zero() {
                        out.add_term(lambda.clone(), chi.mul(c));
                    }
                }
            }
        }
        // Drained in ascending degree. Taking the keys first and removing as we
        // go visits each bucket once, in order, without holding a borrow.
        let mut degrees: Vec<u32> = by_degree.keys().copied().collect();
        degrees.sort_unstable();
        for n in degrees {
            let Some(mut items) = by_degree.remove(&n) else {
                continue;
            };
            // Descending part order, so the longest common prefixes are shared.
            items.sort_by(|a, b| a.0.parts().cmp(b.0.parts()));
            let l = n as usize;
            if l == 0 {
                for (_, c) in &items {
                    out.add_term(Partition::default(), (*c).clone());
                }
                continue;
            }
            // The narrow mask carries every degree it can. Widening is not free
            // — `docs/record/plethysm.md` has what it costs at equal degree —
            // and degrees past 32 are the only ones that need it.
            if l <= MASK_LIMIT {
                sweep_degree::<u64, C>(&items, l, &mut out);
            } else {
                sweep_degree::<u128, C>(&items, l, &mut out);
            }
        }
        out
    }
}

/// Expand one degree's batch of p_μ, in whichever mask width holds it.
///
/// Split out of [`ToSchur::to_schur`] so the two widths are one body rather
/// than two, with the choice made once at the call above.
fn sweep_degree<M: Beta, C: Ring>(items: &[(&Partition, &C)], l: usize, out: &mut Schur<C>) {
    let mut root: Map<M, i128> = Map::default();
    root.insert(M::low_ones(l), 1);
    if integral_sweep(items, l, &root, out) {
        return;
    }
    // Accumulate on the β-mask, not on a Partition. Every leaf of the
    // traversal touches the whole layer, so keying by partition allocated and
    // sorted a fresh Vec — and hashed a heap key — once per (μ, mask) pair to
    // produce a few dozen distinct terms. Masks are words, and the partitions
    // get built once at the end.
    let mut acc: Map<M, C> = Map::default();
    p_expand_shared(items, 0, &root, &mut |c: &&C, mask, chi: &i128| {
        let term = C::from_i128(*chi).mul(c);
        acc.entry(mask).or_insert_with(C::zero).add_assign(&term);
    });
    for (mask, c) in acc {
        if !c.is_zero() {
            out.add_term(mask_to_partition(mask, l), c);
        }
    }
}

/// Expand a batch of p_μ of one degree in a single traversal, sharing the
/// Murnaghan–Nakayama sweep across every common prefix.
///
/// `items` is sorted by part sequence, so partitions agreeing in their first
/// `depth` parts are contiguous; each such run continues from *one* layer
/// instead of rebuilding it. Plethysm is the case that motivates this: it
/// finishes by converting a p-element of degree d·e with dozens of terms, and
/// that conversion is nearly all of its runtime
/// (`docs/record/plethysm.md`).
pub(crate) fn p_expand_shared<M: Beta, C: Ring, T, F>(
    items: &[(&Partition, T)],
    depth: usize,
    layer: &Map<M, C>,
    emit: &mut F,
) where
    F: FnMut(&T, M, &C),
{
    let mut i = 0;
    // Partitions that end here: emit the layer against their coefficient.
    while i < items.len() && items[i].0.len() == depth {
        interrupt::poll();
        for (&mask, chi) in layer {
            if !chi.is_zero() {
                emit(&items[i].1, mask, chi);
            }
        }
        i += 1;
    }
    // The rest are grouped by their next part, each group sharing one step.
    while i < items.len() {
        let k = items[i].0.part(depth);
        let start = i;
        while i < items.len() && items[i].0.part(depth) == k {
            i += 1;
        }
        let next = p_step(layer, k);
        p_expand_shared(&items[start..i], depth + 1, &next, emit);
    }
}

/// Run one degree's sweep entirely in `i128`, over a common denominator.
///
/// Returns `false` if that is not possible — an unsupported ring, or an
/// overflow — in which case the caller takes the generic path and nothing has
/// been written to `out`.
///
/// The point is that `p → s` computes Σ_μ c_μ χ^λ(μ), a sum of
/// (coefficient × integer) terms. Done in ℚ that is a rational multiply and a
/// rational add per (μ, mask) leaf, each normalizing by a gcd — and those gcds
/// with the i128 division underneath them are most of plethysm's runtime
/// (`docs/record/plethysm.md`). Putting every c_μ over one denominator D makes
/// the entire accumulation integer, with a single conversion back per output
/// term.
///
/// D is the lcm of the denominators, which measurement said is the right shape
/// for this: across the plethysms driving this work the lcm *equalled the
/// largest denominator* every time, and never exceeded ~5·10⁵. Overflow is
/// still checked at every step rather than argued away, because the guarantee
/// is only about the cases measured.
fn integral_sweep<M: Beta, C: Ring>(
    items: &[(&Partition, &C)],
    l: usize,
    root: &Map<M, i128>,
    out: &mut Schur<C>,
) -> bool {
    let mut den: i128 = 1;
    let mut ratios = Vec::with_capacity(items.len());
    for (_, c) in items {
        let (n, d) = match c.as_ratio() {
            Some(r) => r,
            None => return false, // ring opts out
        };
        ratios.push((n, d));
        let g = gcd_i128(den, d);
        den = match den.checked_mul(d / g) {
            Some(v) => v,
            None => return false,
        };
    }
    // Numerators rescaled to the common denominator.
    let mut scaled = Vec::with_capacity(items.len());
    for &(n, d) in &ratios {
        match n.checked_mul(den / d) {
            Some(v) => scaled.push(v),
            None => return false,
        }
    }
    let paired: Vec<(&Partition, i128)> = items
        .iter()
        .zip(&scaled)
        .map(|((mu, _), &s)| (*mu, s))
        .collect();

    let mut acc: Map<M, i128> = Map::default();
    let mut overflow = false;
    p_expand_shared(&paired, 0, root, &mut |&s: &i128, mask, chi: &i128| {
        if overflow {
            return;
        }
        let slot = acc.entry(mask).or_insert(0);
        match s.checked_mul(*chi).and_then(|t| slot.checked_add(t)) {
            Some(v) => *slot = v,
            None => overflow = true,
        }
    });
    if overflow {
        return false;
    }
    // Convert back once per output term, not once per leaf.
    let mut built = Vec::with_capacity(acc.len());
    for (&mask, &v) in &acc {
        if v == 0 {
            continue;
        }
        match C::from_ratio(v, den) {
            Some(c) => built.push((mask, c)),
            None => return false,
        }
    }
    for (mask, c) in built {
        out.add_term(mask_to_partition(mask, l), c);
    }
    true
}

// Neither operand is `MIN` here (a denominator and a positive divisor), so
// the magnitudes and their gcd fit back in `i128`.
#[allow(clippy::cast_possible_wrap)]
fn gcd_i128(a: i128, b: i128) -> i128 {
    crate::coeff::gcd_u128(a.unsigned_abs(), b.unsigned_abs()) as i128
}

/// p_μ in the Schur basis, by **iterated Murnaghan–Nakayama** rather than by
/// evaluating characters.
///
/// `p_μ = Σ_λ χ^λ(μ) s_λ`, and the obvious implementation asks for χ^λ(μ) once
/// per λ — p(n) independent recursions for one p_μ. But MN is itself a
/// multiplication rule,
///
/// ```text
///   p_k · s_λ = Σ (−1)^{ht(ξ)} s_{λ ∪ ξ},   ξ a k-rim-hook added to λ,
/// ```
///
/// so multiplying successively by p_{μ₁}, p_{μ₂}, … builds the entire expansion
/// in ℓ(μ) passes and never computes a character at all. Same "produce the
/// whole answer in one sweep rather than query it entry by entry" shape as the
/// Kostka and coproduct fixes.
///
/// Rim hooks are handled in β-numbers (first-column hook lengths, strictly
/// decreasing): adding a k-rim-hook is replacing some β by β+k when that value
/// is free, and the height is how many β lie strictly between them. Using a
/// fixed β-length of n keeps every intermediate comparable — a partition of n
/// has at most n rows, so no representable shape is lost.
///
/// Accumulation is in **i128**, not the caller's ring, and that is a deliberate
/// and safe narrowing rather than the usual truncation hazard. Every value here
/// is a character χ^λ(μ), and |χ^λ(μ)| ≤ f^λ ≤ √(n!). This function already
/// declines when l > 32 (the β-mask does not fit), and √(32!) ≈ 1.6·10¹⁸ — so
/// on every input it *accepts*, i128 cannot overflow. Callers past that width
/// take the character fallback, which stays exact in `C` for bignum rings.
///
/// The narrowing matters because the ring is the hot loop. Plethysm runs this
/// over ℚ, where each rim hook cost a rational add — a gcd — plus a temporary
/// from negating the coefficient, to combine two integers. That makes p → s
/// nearly all of plethysm's runtime (`docs/record/plethysm.md`).
///
/// Retained as the **reference form**: production now takes the batched
/// [`p_expand_shared`] path, which shares this sweep across every p_μ of a
/// degree, and `batched_p_expansion_matches_per_term` holds the two to
/// agreement. The prefix grouping is the part of that batching that can quietly
/// go wrong, so it gets an oracle rather than trust.
#[cfg(test)]
fn p_expand(mu: &Partition) -> Option<Vec<(Partition, i128)>> {
    let l = mu.size() as usize;
    if l == 0 {
        return Some(vec![(Partition::default(), 1)]);
    }
    if l > MASK_LIMIT {
        return None;
    }
    // β-numbers of ∅ with l slots: {0, 1, …, l−1}.
    let mut cur: Map<u64, i128> = Map::default();
    cur.insert((1u64 << l) - 1, 1);
    for &k in mu.parts() {
        cur = p_step(&cur, k);
    }
    Some(
        cur.into_iter()
            .filter(|&(_, c)| c != 0)
            .map(|(mask, c)| (mask_to_partition(mask, l), c))
            .collect(),
    )
}

/// The largest degree a `u64` β-mask holds, 32.
///
/// β values run from 0 to at most (l−1) + max part < 2l, so a 64-bit mask holds
/// the whole set for l ≤ 32. Degrees past it are swept in [`u128`] instead, up
/// to [`WIDE_MASK_LIMIT`]; only past *that* does a caller fall back.
pub(crate) const MASK_LIMIT: usize = 32;

/// The largest degree the β-mask sweep accepts at all, 55 — and the ceiling is
/// the accumulator, not the mask.
///
/// A `u128` mask would hold l ≤ 64. What stops it sooner is that the layer
/// accumulates in `i128`: every value in it is a character, so |χ^λ(μ)| ≤ f^λ ≤
/// √(l!), and one slot takes at most l contributions before it settles, giving
/// a transient bound of l·√(l!). That is 6.2·10³⁷ at l = 55 and 1.5·10³⁹ at
/// l = 56, against an `i128` ceiling of 1.7·10³⁸ — so 55 is the last degree on
/// which the sweep provably cannot overflow. R3 is the backstop if this
/// reasoning is ever wrong: the accumulation is checked in every profile, so a
/// broken bound is a panic and not a wrapped character.
pub(crate) const WIDE_MASK_LIMIT: usize = 55;

/// The bit operations the Murnaghan–Nakayama sweep performs on a β-mask.
///
/// A type parameter rather than one wider mask everywhere, because the widening
/// is only ever needed above degree 32 and the sweep below it is the hot path
/// the whole batching design exists to serve (`docs/record/plethysm.md`). Both
/// instantiations monomorphize, so the `u64` sweep compiles to what it compiled
/// to before this trait existed; the measured cost of each is in
/// `docs/record/plethysm.md`.
pub(crate) trait Beta: Copy + Eq + std::hash::Hash + 'static {
    /// The width of the mask, so a caller can ask whether a β-set fits.
    const BITS: u32;
    /// `(1 << n) - 1`: the β-set of the empty partition with n slots.
    fn low_ones(n: usize) -> Self;
    /// `self >> (number of trailing ones)`: the β-mask of the same partition
    /// with exactly ℓ(λ) slots, which is its canonical mask — the mask with
    /// one more slot is `(m << 1) | 1`, so stripping the trailing ones of any
    /// β-mask of λ reaches it. The empty partition is `0`.
    fn canonical(self) -> Self;
    fn is_zero(self) -> bool;
    fn test(self, n: u32) -> bool;
    fn with_bit(self, n: u32) -> Self;
    fn without_bit(self, n: u32) -> Self;
    /// `self & (((1 << hi) - 1) ^ ((1 << lo) - 1))`: the β strictly between two
    /// positions, which is what a rim hook's height counts.
    fn between(self, lo: u32, hi: u32) -> Self;
    fn trailing_zeros(self) -> u32;
    fn count_ones(self) -> u32;
    /// `self & (self - 1)`: drop the lowest set bit.
    fn clear_lowest(self) -> Self;
    /// Index of the highest set bit; only called on a nonzero mask.
    fn highest(self) -> usize;
}

macro_rules! impl_beta {
    ($t:ty) => {
        impl Beta for $t {
            const BITS: u32 = <$t>::BITS;
            #[inline]
            fn low_ones(n: usize) -> Self {
                (1 as $t << n) - 1
            }
            #[inline]
            fn canonical(self) -> Self {
                // A β-mask never has every bit set (its top slot is below
                // `BITS`), so the shift is below the width.
                self >> (!self).trailing_zeros()
            }
            #[inline]
            fn is_zero(self) -> bool {
                self == 0
            }
            #[inline]
            fn test(self, n: u32) -> bool {
                self >> n & 1 == 1
            }
            #[inline]
            fn with_bit(self, n: u32) -> Self {
                self | (1 as $t) << n
            }
            #[inline]
            fn without_bit(self, n: u32) -> Self {
                self & !((1 as $t) << n)
            }
            #[inline]
            fn between(self, lo: u32, hi: u32) -> Self {
                self & ((((1 as $t) << hi) - 1) ^ (((1 as $t) << lo) - 1))
            }
            #[inline]
            fn trailing_zeros(self) -> u32 {
                <$t>::trailing_zeros(self)
            }
            #[inline]
            fn count_ones(self) -> u32 {
                <$t>::count_ones(self)
            }
            #[inline]
            fn clear_lowest(self) -> Self {
                self & (self - 1)
            }
            #[inline]
            fn highest(self) -> usize {
                (<$t>::BITS - 1 - <$t>::leading_zeros(self)) as usize
            }
        }
    };
}

impl_beta!(u64);
impl_beta!(u128);

/// One Murnaghan–Nakayama step: multiply a layer of β-masks by p_k.
// β-mask bit positions, bounded by `MASK_LIMIT = 32`.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
pub(crate) fn p_step<M: Beta, C: Ring>(cur: &Map<M, C>, k: u32) -> Map<M, C> {
    // The layer grows monotonically through a sweep, so a default-capacity
    // map rehashes several times per step. Sizing to the input is a floor on
    // the output, not a guess.
    let mut next: Map<M, C> = Map::with_capacity_and_hasher(cur.len() * 2, Default::default());
    for (&mask, c) in cur {
        interrupt::poll();
        let mut rest = mask;
        while !rest.is_zero() {
            let b = rest.trailing_zeros();
            rest = rest.clear_lowest();
            let nb = b + k;
            if mask.test(nb) {
                continue; // that β is taken: no such rim hook
            }
            // Height = how many β lie strictly between b and b+k.
            let between = mask.between(b + 1, nb);
            let m = mask.without_bit(b).with_bit(nb);
            let slot = next.entry(m).or_insert_with(C::zero);
            if between.count_ones().is_multiple_of(2) {
                slot.add_assign(c);
            } else {
                slot.sub_assign(c);
            }
        }
    }
    next
}

/// Bits high-to-low are β₀ > β₁ > …, and λ_i = β_i − (l−1−i).
// As `character::mask_to_partition`: a β-mask bit minus an offset below 32.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
fn mask_to_partition<M: Beta>(mask: M, l: usize) -> Partition {
    let mut parts = Vec::with_capacity(l);
    let mut rest = mask;
    let mut i = 0usize;
    while !rest.is_zero() {
        let b = rest.highest();
        rest = rest.without_bit(b as u32);
        let part = b - (l - 1 - i);
        if part > 0 {
            parts.push(part as u32);
        }
        i += 1;
    }
    // Bits walk high to low and β is strictly decreasing, so `parts` comes out
    // weakly decreasing with the zeros already dropped -- `Partition::new`
    // would sort a sorted vector, which the profile charged for.
    Partition::from_sorted(parts)
}

impl<C: QAlgebra> FromSchur<C> for PowerSum<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        // s_λ = Σ_μ z_μ⁻¹ χ^λ(μ) p_μ  (needs division by z_μ).
        let mut out = PowerSum::zero();
        for (lambda, c) in s.terms() {
            // One batched recursion per λ rather than one `try_character` per
            // (λ, μ): the per-call memo round trip was 21% of this conversion
            // (`docs/record/coefficient-arithmetic.md`).
            let row = crate::character::character_row(lambda);
            // A `None` entry passed `i128` (|λ| ≈ 58 up); it re-runs in `C`,
            // exact for a bignum ring, sharing one memo across the row as the
            // batched pass does in `i128`.
            let mut wide: Option<HashMap<(Partition, Partition), C>> = None;
            for (mu, chi) in partitions_cached(lambda.size()).iter().zip(row) {
                let chi = match chi {
                    Some(v) => C::from_i128(v),
                    None => crate::character::character_generic(
                        lambda,
                        mu,
                        wide.get_or_insert_with(HashMap::new),
                    ),
                };
                if !chi.is_zero() {
                    // Divisions by an integer — never by a ring element. That
                    // is exactly the `QAlgebra` contract, and why this is not
                    // bounded on `Field`. `div_by_z` divides by z_μ's factors
                    // one at a time rather than forming z_μ, which would cap
                    // this conversion at degree 34 (z_{1^35} leaves `u128`).
                    out.add_term(mu.clone(), mu.div_by_z(&c.mul(&chi)));
                }
            }
        }
        out
    }

    fn from_basis(src: &'static str, terms: &BTreeMap<Partition, C>) -> Option<Self> {
        match src {
            "h" => Some(multiplicative_route(terms, |n| {
                multiplicative_in_power::<C>(n, false)
            })),
            "e" => Some(multiplicative_route(terms, |n| {
                multiplicative_in_power::<C>(n, true)
            })),
            _ => None,
        }
    }
}

// --- Monomial <-> Schur -----------------------------------------------------

impl<C: Ring> FromSchur<C> for Monomial<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        // s_λ = Σ_μ K_{λμ} m_μ. Two routes, chosen per degree by how many
        // Schur terms the input has there:
        //
        // * Few terms: one `kostka(λ, μ)` per pair. Each λ runs its own chain
        //   DP over the shapes inside λ, once per μ, and the pair lands in
        //   `kostka_cached`, which is what makes a repeated small conversion
        //   cheap (`docs/record/transitions.md`, "The repeated small
        //   conversion").
        // * Many terms: one Pieri trie over every μ ⊢ n, whose leaf for μ is
        //   the whole Kostka column K_{·μ}, dotted against the input. The
        //   trie's cost does not depend on the term count, so it wins once
        //   the input has more than a few dozen terms — a small fraction of
        //   the p(n) shapes, and every X → s → m conversion through the hub
        //   hands this function most of them. Measured 17-66x over per-pair
        //   on full support at n = 16-28 (`examples/bench_s2m.rs`,
        //   `docs/record/transitions.md`).
        let mut out = Monomial::zero();
        let mut by_degree: BTreeMap<u32, Vec<(&Partition, &C)>> = BTreeMap::new();
        for (lambda, c) in s.terms() {
            by_degree
                .entry(lambda.size())
                .or_default()
                .push((lambda, c));
        }
        for (n, items) in by_degree {
            if kostka_batched_wins(n, items.len()) {
                kostka_batched(&items, n, &mut out);
            } else {
                for (lambda, c) in items {
                    for mu in partitions_cached(n).iter() {
                        let k = kostka(lambda, mu);
                        if k != 0 {
                            out.add_term(mu.clone(), C::from_u128(k).mul(c));
                        }
                    }
                }
            }
        }
        out
    }

    fn from_basis(src: &'static str, terms: &BTreeMap<Partition, C>) -> Option<Self> {
        match src {
            "h" => multiplicative_to_monomial(terms, false),
            "e" => multiplicative_to_monomial(terms, true),
            _ => None,
        }
    }
}

/// Whether `terms` Schur terms of degree `n` are enough for the batched
/// Kostka sweep to beat one `kostka` call per pair.
///
/// The crossover is not a fixed fraction of p(n): `examples/bench_s2m.rs`
/// puts it at p(n)/11 at n = 12 and p(n)/66 at n = 28. As a term count it is
/// close to linear in n — 7, 17, 27, 42, 56 terms at n = 12, 16, 20, 24, 28 —
/// and `3n − 30` fits within three terms everywhere measured
/// (`docs/record/transitions.md`). A single term never batches: that is the
/// shape of a peeled conversion, and its repeats are what `kostka_cached`
/// serves. Past [`MASK_LIMIT`] there is no sweep to dispatch to.
fn kostka_batched_wins(n: u32, terms: usize) -> bool {
    n > 0 && n as usize <= MASK_LIMIT && terms >= 2 && terms >= (3 * n as usize).saturating_sub(30)
}

/// Σ_λ c_λ s_λ → m for every term of one degree at once, through the Pieri
/// trie over all μ ⊢ n.
///
/// ⟨Σ_λ c_λ s_λ, h_μ⟩ = Σ_λ c_λ K_{λμ}, and the trie's leaf for h_μ is exactly
/// the layer {λ ↦ K_{λμ}}, so the coefficient of m_μ is that layer dotted
/// against the input. This is the h → s walk of [`expand_multiplicative`]
/// with a different leaf, and it shares its bounds: `n ≤ MASK_LIMIT`, layer
/// multiplicities in `i128`, `C` touched once per output term.
fn kostka_batched<C: Ring>(items: &[(&Partition, &C)], n: u32, out: &mut Monomial<C>) {
    let l = n as usize;
    let coeff: Map<u64, &C> = items
        .iter()
        .map(|&(lam, c)| (beta_mask(lam, l), c))
        .collect();
    let mus = partitions_cached(n);
    let leaves: Vec<(&Partition, ())> = mus.iter().map(|mu| (mu, ())).collect();
    pieri_trie(
        &leaves,
        0,
        &unit_mask_layer(l),
        false,
        &mut |mu, (), layer| {
            interrupt::poll();
            let mut acc = C::zero();
            // Walk the smaller side: the leaf for μ holds every λ ⊵ μ, which for
            // μ near 1ⁿ is all of p(n), while the input may be a handful of terms.
            if layer.len() <= coeff.len() {
                for (mask, &v) in layer {
                    if let Some(c) = coeff.get(mask) {
                        acc.add_assign(&C::from_i128(v).mul(c));
                    }
                }
            } else {
                for (mask, c) in &coeff {
                    if let Some(&v) = layer.get(mask) {
                        acc.add_assign(&C::from_i128(v).mul(c));
                    }
                }
            }
            out.add_term(mu.clone(), acc);
        },
    );
}

// --- h/e -> m: matrix counts, one generator at a time -------------------------

/// Degree past which [`multiplicative_to_monomial`] declines and [`convert`]
/// composes through the Schur hub instead.
///
/// The route's weights are binomials `C(a, b)` with `a ≤ ℓ(ρ) ≤ |ρ| ≤ n`,
/// computed stepwise in `u128`; the largest intermediate is `C(a, ⌈a/2⌉)·a`,
/// which at n = 120 is under 1.2·10³⁷ and inside `u128`, and at n = 128 is
/// not. Declining rather than checking per multiply is the `integral_sweep`
/// shape (`docs/policies/failure.md`, R6): the fast path bails to the generic
/// one, which has no wall of its own.
const MATRIX_ROUTE_LIMIT: u32 = 120;

/// `C(a, b)` exactly. Callers keep `b ≤ a ≤` [`MATRIX_ROUTE_LIMIT`], under
/// which every intermediate fits `u128` — see the limit's doc.
fn binomial(a: usize, b: usize) -> u128 {
    let b = b.min(a - b);
    let mut out: u128 = 1;
    for i in 0..b {
        // C(a, i)·(a − i) = C(a, i + 1)·(i + 1), so the division is exact.
        out = out * (a - i) as u128 / (i + 1) as u128;
    }
    out
}

/// h_λ and e_λ in the monomial basis, **skipping the Schur hub**: the
/// coefficient of m_ν in h_μ counts the matrices of non-negative integers
/// with row sums μ and column sums ν, and in e_μ the 0-1 matrices
/// (Macdonald I.6, the two Cauchy expansions). The count is built one row at
/// a time —
/// multiply by one generator per part of μ, in the monomial basis throughout —
/// so no term is touched that the answer does not mention. The hub reaches
/// the same number as Σ_λ K_{λμ} K_{λν}, through up to p(n) Schur terms that
/// this route never forms; Symmetrica's `t_HOMSYM_MONOMIAL` never forms them
/// either, and closing that routing gap is what this is for
/// (`docs/record/transitions.md`).
///
/// Terms sharing a prefix of parts share the layers that build it, exactly as
/// [`expand_shared`]; `terms` iterates in `Partition` order, which keeps equal
/// prefixes contiguous. Layer coefficients live in `C` from the start: the
/// counts reach n!, so there is no width an integer layer could promise, and
/// the ring already holds the exact-or-loud line.
///
/// `None` past [`MATRIX_ROUTE_LIMIT`], where the weights' `u128` arithmetic
/// loses its bound proof; [`convert`] then composes through the hub.
fn multiplicative_to_monomial<C: Ring>(
    terms: &BTreeMap<Partition, C>,
    vertical: bool,
) -> Option<Monomial<C>> {
    if terms.keys().any(|mu| mu.size() > MATRIX_ROUTE_LIMIT) {
        return None;
    }
    let items: Vec<(&Partition, &C)> = terms.iter().collect();
    let mut root = BTreeMap::new();
    root.insert(Partition::default(), C::one());
    let mut out = Monomial::zero();
    monomial_route_shared(&items, 0, &root, vertical, &mut out);
    Some(out)
}

/// Walk one prefix group, mirroring [`expand_shared`]: the layer is the
/// prefix product h_{μ₁}⋯h_{μ_d} (or e's), written in the monomial basis.
fn monomial_route_shared<C: Ring>(
    items: &[(&Partition, &C)],
    depth: usize,
    layer: &BTreeMap<Partition, C>,
    vertical: bool,
    out: &mut Monomial<C>,
) {
    let mut i = 0;
    while i < items.len() && items[i].0.len() == depth {
        for (nu, v) in layer {
            out.add_term(nu.clone(), v.mul(items[i].1));
        }
        i += 1;
    }
    while i < items.len() {
        let k = items[i].0.part(depth);
        let start = i;
        while i < items.len() && items[i].0.part(depth) == k {
            i += 1;
        }
        let next = generator_step(layer, k, vertical);
        monomial_route_shared(&items[start..i], depth + 1, &next, vertical, out);
    }
}

/// Multiply a monomial-basis element by h_k — or by e_k, if `vertical`.
fn generator_step<C: Ring>(
    cur: &BTreeMap<Partition, C>,
    k: u32,
    vertical: bool,
) -> BTreeMap<Partition, C> {
    let mut next: BTreeMap<Partition, C> = BTreeMap::new();
    for (nu, c) in cur {
        interrupt::poll();
        let mut push = |rho: Partition, w: C| {
            next.entry(rho)
                .or_insert_with(C::zero)
                .add_assign(&w.mul(c));
        };
        if vertical {
            e_times_monomial(nu.parts(), k, &mut push);
        } else {
            h_times_monomial(nu.parts(), k, &mut push);
        }
    }
    next
}

/// h_k · m_ν in the monomial basis: `emit(ρ, w)` once per ρ with w ≠ 0.
///
/// Extracting the x^ρ coefficient, h_k contributes every degree-k monomial
/// exactly once, so w counts the distinct rearrangements α of ν — padded with
/// zeros to ℓ(ρ) slots — with α_j ≤ ρ_j; the matrix picture adds the row
/// ρ − α. The support is every ρ ⊇ ν with |ρ/ν| = k — any skew shape, **not**
/// a strip, which is what separates this from every Pieri enumerator above.
/// Walking the rows of ρ therefore visits exactly the output and dead-ends
/// nowhere: cells left over always fit in fresh rows of size ≥ 1.
fn h_times_monomial<C: Ring>(nu: &[u32], k: u32, emit: &mut impl FnMut(Partition, C)) {
    fn rec<C: Ring>(
        nu: &[u32],
        i: usize,
        left: u32,
        prev: u32,
        cur: &mut Vec<u32>,
        emit: &mut impl FnMut(Partition, C),
    ) {
        if left == 0 {
            // Nothing left to place: the remaining rows keep their old values,
            // and ν_i ≤ ν_{i−1} ≤ ρ_{i−1} keeps the result decreasing.
            let len = cur.len();
            cur.extend_from_slice(&nu[i.min(nu.len())..]);
            let w = arrangements_under(nu, cur);
            emit(Partition::from_sorted(cur.clone()), w);
            cur.truncate(len);
            return;
        }
        let base = nu.get(i).copied().unwrap_or(0);
        let (lo, hi) = if i < nu.len() {
            (base, prev.min(base + left))
        } else {
            (1, prev.min(left))
        };
        for v in lo..=hi {
            cur.push(v);
            rec(nu, i + 1, left - (v - base), v, cur, emit);
            cur.pop();
        }
    }
    let mut cur = Vec::with_capacity(nu.len() + k as usize);
    rec(nu, 0, k, u32::MAX, &mut cur, emit);
}

/// The number of distinct rearrangements α of ν, padded with zeros to ℓ(ρ)
/// slots, with α_j ≤ ρ_j — given ρ ⊇ ν, so never zero.
///
/// Placing the values of ν largest first, value v may take any slot with
/// ρ_j ≥ v not already taken; every slot taken earlier also has ρ_j ≥ v, so
/// the choices number `C(#{j : ρ_j ≥ v} − placed, m_v)` and the factors
/// multiply. Zeros fill what remains, one way. Each factor fits `u128` under
/// [`MATRIX_ROUTE_LIMIT`] and is injected into the ring separately: the
/// *product* is the matrix count, which no fixed width can promise to hold.
fn arrangements_under<C: Ring>(nu: &[u32], rho: &[u32]) -> C {
    let mut w = C::one();
    let mut placed = 0usize;
    let mut j = 0usize;
    let mut i = 0usize;
    while i < nu.len() {
        let v = nu[i];
        let mut m = 0usize;
        while i < nu.len() && nu[i] == v {
            m += 1;
            i += 1;
        }
        while j < rho.len() && rho[j] >= v {
            j += 1;
        }
        let b = binomial(j - placed, m);
        if b != 1 {
            w = w.mul(&C::from_u128(b));
        }
        placed += m;
    }
    w
}

/// e_k · m_ν in the monomial basis: `emit(ρ, w)` once per ρ with w ≠ 0.
///
/// e_k's monomials are 0-1, so each part of ν either stays or grows by one,
/// and exactly k grow — zeros included, which is where new parts equal to 1
/// come from. The choice of how many parts of each value grow determines ρ
/// and is determined by it, so the walk over those choices visits each ρ
/// once. The weight counts the distinct rearrangements: the slots of value
/// v + 1 in ρ hold the t promoted parts and the kept parts that were already
/// v + 1, interchangeably — `C(kept + t, t)` per value, zeros included.
fn e_times_monomial<C: Ring>(nu: &[u32], k: u32, emit: &mut impl FnMut(Partition, C)) {
    // Parts grouped by value, descending — as `muir_expand` groups, and for
    // the same reason: choosing "t parts equal to v" once is what keeps the
    // rearrangements distinct.
    let mut vals: Vec<(u32, u32)> = Vec::new();
    for &v in nu {
        match vals.last_mut() {
            Some((u, m)) if *u == v => *m += 1,
            _ => vals.push((v, 1)),
        }
    }
    // `prev_val`/`prev_kept`: the value handled one level up and how many of
    // its parts stayed — the kept count for this level when the values are
    // adjacent, and irrelevant otherwise.
    // The eight parameters are the recursion state; a struct would carry the
    // same eight fields.
    #[allow(clippy::too_many_arguments)]
    fn rec<C: Ring>(
        vals: &[(u32, u32)],
        i: usize,
        left: u32,
        prev_val: u32,
        prev_kept: u32,
        cur: &mut Vec<u32>,
        w: &C,
        emit: &mut impl FnMut(Partition, C),
    ) {
        if i == vals.len() {
            // The zeros: `left` of them become ones. Pushed after every
            // positive value, so `cur` stays sorted.
            let kept = if prev_val == 1 { prev_kept } else { 0 };
            let b = binomial((kept + left) as usize, left as usize);
            let w = if b == 1 {
                w.clone()
            } else {
                w.mul(&C::from_u128(b))
            };
            let len = cur.len();
            cur.extend(std::iter::repeat_n(1u32, left as usize));
            emit(Partition::from_sorted(cur.clone()), w);
            cur.truncate(len);
            return;
        }
        let (v, m) = vals[i];
        let kept_above = if prev_val == v + 1 { prev_kept } else { 0 };
        for t in 0..=m.min(left) {
            let b = binomial((kept_above + t) as usize, t as usize);
            let w2 = if b == 1 {
                w.clone()
            } else {
                w.mul(&C::from_u128(b))
            };
            let len = cur.len();
            // v + 1 ≤ the previous value, so pushing the promoted parts first
            // keeps `cur` weakly decreasing.
            cur.extend(std::iter::repeat_n(v + 1, t as usize));
            cur.extend(std::iter::repeat_n(v, (m - t) as usize));
            rec(vals, i + 1, left - t, v, m - t, cur, &w2, emit);
            cur.truncate(len);
        }
    }
    let mut cur = Vec::with_capacity(nu.len() + k as usize);
    rec(&vals, 0, k, u32::MAX, 0, &mut cur, &C::one(), emit);
}

impl<C: Ring> ToSchur<C> for Monomial<C> {
    fn to_schur(&self) -> Schur<C> {
        let mut out = Schur::zero();
        for (mu, c) in self.terms() {
            match muir_expand(mu) {
                Some(terms) => {
                    for (lambda, v) in terms {
                        out.add_term(lambda, C::from_i128(v).mul(c));
                    }
                }
                // Past the β-mask width: fall back to the row solve, which is
                // slow but has no degree wall.
                None => {
                    let parts = lex_parts_cached(mu.size());
                    let row = inverse_kostka_row_cached(mu, || inverse_kostka_row(&parts, mu));
                    for (i, lambda) in parts.iter().enumerate() {
                        if row[i] != 0 {
                            // `row` is i128 because that is what the solve is
                            // built in; inject at that width, not through i64.
                            out.add_term(lambda.clone(), C::from_i128(row[i]).mul(c));
                        }
                    }
                }
            }
        }
        out
    }
}

// --- Forgotten <-> Schur ----------------------------------------------------
//
// f_λ = ω(m_λ), and ω is an involution, so both directions are the monomial
// conversion with an ω applied on the Schur side. Nothing new is computed:
//
//   to_schur:    Σ c_λ f_λ = ω(Σ c_λ m_λ)        →  ω(monomial_to_schur(c))
//   from_schur:  x = Σ c_λ f_λ  ⟺  ω(x) = Σ c_λ m_λ  →  monomial coeffs of ω(x)
//
// ω on the Schur basis is just conjugation of every index, so the extra cost is
// one transpose per term. Both directions therefore inherit Muir's rule and the
// Kostka machinery — including their asymptotics — for free.

impl<C: Ring> ToSchur<C> for Forgotten<C> {
    fn to_schur(&self) -> Schur<C> {
        Monomial::from_terms(self.terms().clone())
            .to_schur()
            .omega()
    }
}

impl<C: Ring> FromSchur<C> for Forgotten<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        let m: Monomial<C> = Monomial::from_schur(&s.omega());
        Forgotten::from_terms(m.terms().clone())
    }

    fn from_basis(src: &'static str, terms: &BTreeMap<Partition, C>) -> Option<Self> {
        // ω fixes h_μ = ω(e_μ) = Σ_ν M(μ, ν) ω(m_ν) = Σ_ν M(μ, ν) f_ν with M
        // the **0-1** count, so h → f is e → m with the letters changed, and
        // e → f is h → m: the same two engines, crossed.
        let m = match src {
            "h" => multiplicative_to_monomial(terms, true),
            "e" => multiplicative_to_monomial(terms, false),
            _ => None,
        }?;
        Some(Forgotten::from_terms(m.terms().clone()))
    }
}

/// m_μ in the Schur basis, by **Muir's rule** — no Kostka numbers and no linear
/// solve.
///
/// In n variables the bialternant gives s_λ = a_{λ+δ}/a_δ, and multiplying by
/// m_μ = Σ_α x^α (over the distinct rearrangements α of μ) just shifts
/// exponents:
///
/// ```text
///   m_μ · a_δ = Σ_α a_{α+δ},   so   m_μ = Σ_α ± s_{sort(α+δ) − δ}
/// ```
///
/// with `a_β = 0` when β repeats and `± a_{sorted β}` otherwise. Taking n = |μ|
/// slots loses nothing: (K⁻¹)_{μλ} ≠ 0 forces μ ⊵ λ, so ℓ(λ) ≤ |μ|.
///
/// Working in β-numbers β = α + δ, each part of μ is *added to a distinct slot*
/// of the initial set {0, 1, …, l−1}. That makes this the same machinery as
/// [`p_expand`] — a u64 mask, values moved one at a time, sign flipped by the
/// number of occupied values jumped over. The one difference from
/// Murnaghan–Nakayama is that MN may move the same value repeatedly while here
/// every slot receives at most one part.
///
/// **Slots are processed in decreasing initial value, and that is what makes it
/// fast.** At the moment slot v is handled, every slot above it is final and
/// every slot below still sits at its own value, which is < v < v+k. So a
/// collision at v+k can only be with an already-final value: it can never be
/// resolved later, and the branch dies immediately. Processing upward instead
/// would make the same test unsound, since the occupant might yet move. That
/// prune is the difference between exploring the C(l, ℓ(μ)) · (rearrangements)
/// placements and exploring only the surviving ones — the placements chain
/// together exactly as rim hooks do, so the survivors are few.
///
/// This replaces a forward solve of the unitriangular system K⁻¹K = I, which
/// needed O(p(n)²) Kostka numbers to read p(n) of them — the largest deficit
/// the library carried, and one no constant-factor work could close
/// (`docs/record/transitions.md`).
// `l = |μ|`, a `u32` degree, and the recursion's `v` walks down from it.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
fn muir_expand(mu: &Partition) -> Option<Vec<(Partition, i128)>> {
    let l = mu.size() as usize;
    if l == 0 {
        return Some(vec![(Partition::default(), 1)]);
    }
    // β values reach (l−1) + μ₁ ≤ 2l−1, so a 64-bit mask holds them for l ≤ 32.
    if l > 32 {
        return None;
    }
    // Parts grouped by value: choosing "a part equal to k" once is what makes
    // the rearrangements *distinct*, so equal parts are never double-counted.
    let mut avail: Vec<(u32, u32)> = Vec::new();
    for &k in mu.parts() {
        match avail.last_mut() {
            Some((v, n)) if *v == k => *n += 1,
            _ => avail.push((k, 1)),
        }
    }
    // Accumulate on the β-mask, not on a `Partition` — the same change
    // `p_expand_shared`'s caller makes, for the same reason and in the same
    // file. Every surviving placement reaches the leaf, and keying by partition
    // built, heap-allocated and SipHashed a fresh `Vec<u32>` there once per
    // leaf to produce a few hundred distinct terms. The mask is already the
    // recursion's state and is one word; the partitions get built once at the
    // end, p(n) of them rather than one per leaf.
    let mut acc: Map<u64, i128> = Map::default();
    muir_rec(
        l as i32 - 1,
        (1u64 << l) - 1,
        &mut avail,
        mu.len(),
        1,
        &mut acc,
    );
    Some(
        acc.into_iter()
            .filter(|&(_, v)| v != 0)
            .map(|(mask, v)| (mask_to_partition(mask, l), v))
            .collect(),
    )
}

// β-set slot indices, all bounded by 64 (the mask width). The signs and
// coefficients in `acc` are `i128` and never cast.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
fn muir_rec(
    v: i32,
    mask: u64,
    avail: &mut [(u32, u32)],
    left: usize,
    sign: i128,
    acc: &mut Map<u64, i128>,
) {
    if v < 0 {
        if left == 0 {
            // The mask *is* the β-set; `mask_to_partition` reads λ_i = β_i −
            // (l − i) off it once per distinct term, not once per leaf.
            *acc.entry(mask).or_insert(0) += sign;
        }
        return;
    }
    // Every remaining part needs its own slot, and v+1 slots remain.
    if left > v as usize + 1 {
        return;
    }
    // Leave slot v where it is. Safe without a collision test: every already
    // final value is > v.
    muir_rec(v - 1, mask, avail, left, sign, acc);

    if left == 0 {
        return;
    }
    for i in 0..avail.len() {
        if avail[i].1 == 0 {
            continue;
        }
        let nb = v as u32 + avail[i].0;
        if mask >> nb & 1 == 1 {
            continue; // permanent collision — see the note above
        }
        // Jumping an occupied value transposes the two, flipping the sign.
        let between = mask & (((1u64 << nb) - 1) ^ ((1u64 << (v + 1)) - 1));
        let s = if between.count_ones().is_multiple_of(2) {
            sign
        } else {
            -sign
        };
        avail[i].1 -= 1;
        muir_rec(
            v - 1,
            (mask & !(1 << v)) | (1 << nb),
            avail,
            left - 1,
            s,
            acc,
        );
        avail[i].1 += 1;
    }
}

/// Row μ of the inverse Kostka matrix, indexed against `parts`
/// (decreasing-lex).
///
/// In that order the Kostka matrix K is upper-unitriangular — `K[i][j] ≠ 0`
/// needs λᵢ ⊵ λⱼ, and dominance implies lex — so `K⁻¹K = I` restricted to row μ
/// solves forward:
///
/// ```text
///   w[j] = 1,   w[jj] = −Σ_{m=j}^{jj−1} w[m]·K[m][jj]   for jj > j
/// ```
///
/// Only this one row is ever needed: m_μ = Σ_λ (K⁻¹)_{μλ} s_λ. Building the
/// whole matrix and inverting it computes p(n)² Kostka numbers to read p(n) of
/// them, and the matrix is then nearly all of the conversion's cost
/// (`docs/record/transitions.md`).
///
/// The `w[m] == 0` skip is the part that matters: a zero coefficient makes its
/// Kostka number irrelevant, so the call is never made rather than made and
/// multiplied by zero.
fn inverse_kostka_row(parts: &[Partition], mu: &Partition) -> Vec<i128> {
    let size = parts.len();
    let j = parts
        .iter()
        .position(|p| p == mu)
        .expect("μ ∈ partitions(|μ|)");
    let mut w = vec![0i128; size];
    w[j] = 1;
    for jj in (j + 1)..size {
        let mut acc = 0i128;
        for m in j..jj {
            if w[m] == 0 {
                continue;
            }
            // The one narrowing here that carries a *value* rather than an
            // index: `kostka` answers in `u128`, and past `i128::MAX` an `as`
            // would hand back a negative Kostka number, which the alternating
            // sum below would absorb without a trace (R5, and R8's rule for the
            // same constants at the `Ring` seam).
            let k = i128::try_from(kostka(&parts[m], &parts[jj])).unwrap_or_else(|_| {
                panic!(
                    "K_{{{},{}}} does not fit i128; this row solve is \
                     fixed-width whatever the coefficient ring",
                    parts[m], parts[jj]
                )
            });
            acc += w[m] * k;
        }
        w[jj] = -acc;
    }
    w
}

// --- Monomial multiplication (routed through Schur) -------------------------

impl<C: Ring> Monomial<C> {
    /// [`Monomial::mul`](crate::Monomial::mul) by the long way round: expand
    /// into Schur, multiply there, contract back.
    ///
    /// Kept as the **reference oracle**, the same role `NaiveLr` plays for the
    /// Littlewood–Richardson backends, and not as the default: `m → s` inverts
    /// the Kostka matrix, so this costs the whole degree — every partition of
    /// `|μ| + |ν|` participates — where the direct rule costs the answer. It
    /// also passes through `i128` in the inverse Kostka row solve, which the
    /// direct rule never needs, since the monomial structure constants are
    /// counts and no intermediate is larger than the result.
    ///
    /// `monomial_product_agrees_with_the_schur_route` in
    /// [`crate::sym`] is the agreement test.
    ///
    /// # Panics
    ///
    /// Panics when a structure constant does not fit the coefficient ring
    /// `C`. The constants are LR coefficients, Muir's-rule counts, and Kostka
    /// numbers.
    ///
    /// Panics when a Kostka number needed by the inverse Kostka row solve does
    /// not fit `i128`. That solve runs only on input terms of size above 32.
    /// It runs at `i128` whatever `C` is.
    pub fn mul_via_schur(&self, other: &Self) -> Self {
        let prod = self.to_schur().mul(&other.to_schur());
        Monomial::from_schur(&prod)
    }
}

// --- the same routing, with the pair named at runtime ------------------------

/// [`convert`] with the destination given as a basis symbol rather than a type.
///
/// Split out so the six arms exist once; the source symbol is resolved by
/// [`convert_named`], which is generic over `A` at each of its own six arms.
fn convert_named_dst<C, A>(a: &A, dst: &str) -> Option<BTreeMap<Partition, C>>
where
    C: Ring,
    A: SymFn<C> + ToSchur<C>,
{
    Some(match dst {
        "s" => convert::<C, A, Schur<C>>(a).terms().clone(),
        "h" => convert::<C, A, Homogeneous<C>>(a).terms().clone(),
        "e" => convert::<C, A, Elementary<C>>(a).terms().clone(),
        "m" => convert::<C, A, Monomial<C>>(a).terms().clone(),
        "f" => convert::<C, A, Forgotten<C>>(a).terms().clone(),
        _ => return None,
    })
}

/// Convert between two of the six classical bases named by their
/// [`SymFn::SYMBOL`] at runtime, over any coefficient ring containing ℚ.
///
/// [`convert`] chooses its route from the *types* of its two ends, which a
/// caller holding a basis code rather than a type cannot supply. This is the
/// same routing — direct rule where the pair has one, through the Schur hub
/// otherwise — with the pair resolved at runtime instead. `None` if either
/// code names no basis; the six are `s`, `h`, `e`, `p`, `m`, `f`.
///
/// **`dst` may not be `"p"`**, and `None` says so. The conversions into the
/// power-sum basis divide by z_μ and so need a [`QAlgebra`], while the ring a
/// parameter family's coefficients live in need not be one — `QtPoly<i128>`,
/// which carries every `t`- and `(q,t)`-polynomial coefficient at this
/// library's boundary, is a [`Ring`] and nothing more. The five other
/// destinations stay exact over ℤ for any `C`. This is the same restriction
/// the integer path states, where `p` is reached through a separate entry
/// point returning numerator–denominator pairs.
///
/// ```
/// use std::collections::BTreeMap;
/// use symfn::convert::convert_named;
/// use symfn::{Partition, QtPoly};
///
/// // t·m_(2), in the monomial basis over ℚ[q,t].
/// let mut f: BTreeMap<Partition, QtPoly<i64>> = BTreeMap::new();
/// f.insert(Partition::new([2]), QtPoly::term(0, 1, 1));
///
/// let s = convert_named(&f, "m", "s").unwrap();
/// assert_eq!(s[&Partition::new([2])], QtPoly::term(0, 1, 1));
/// assert_eq!(s[&Partition::new([1, 1])], QtPoly::term(0, 1, -1));
/// ```
///
/// That is `m_2 = s_2 − s_11`, scaled by `t` — the coefficient ring rides
/// along untouched, because a basis change is a ℤ-linear map on the
/// partitions and never divides outside the `p` column.
pub fn convert_named<C: Ring>(
    terms: &BTreeMap<Partition, C>,
    src: &str,
    dst: &str,
) -> Option<BTreeMap<Partition, C>> {
    match src {
        "s" => convert_named_dst(&Schur::from_terms(terms.clone()), dst),
        "h" => convert_named_dst(&Homogeneous::from_terms(terms.clone()), dst),
        "e" => convert_named_dst(&Elementary::from_terms(terms.clone()), dst),
        "m" => convert_named_dst(&Monomial::from_terms(terms.clone()), dst),
        "f" => convert_named_dst(&Forgotten::from_terms(terms.clone()), dst),
        "p" => convert_named_dst(&PowerSum::from_terms(terms.clone()), dst),
        _ => None,
    }
}

/// [`convert_named`] into the power-sum basis — the one destination that
/// divides (by z_μ), which is why it asks [`QAlgebra`] of the coefficients
/// where the six-basis router above asks only [`Ring`], and why
/// [`convert_named`] excludes it. `None` if `src` names no basis.
///
/// ```
/// use std::collections::BTreeMap;
/// use symfn::{convert_named_to_power, Partition, Rational};
///
/// let mut f = BTreeMap::new();
/// f.insert(Partition::new([1, 1]), Rational::from_int(1));
/// let p = convert_named_to_power(&f, "s").unwrap();
///
/// assert_eq!(p[&Partition::new([1, 1])], Rational::new(1, 2));
/// assert_eq!(p[&Partition::new([2])], Rational::new(-1, 2));
/// ```
///
/// So `s_11 = (p_11 − p_2)/2`, with the sign on the one-part shape — under ω
/// it would sit on `p_11`.
pub fn convert_named_to_power<C: QAlgebra>(
    terms: &BTreeMap<Partition, C>,
    src: &str,
) -> Option<BTreeMap<Partition, C>> {
    fn go<C: QAlgebra, A: SymFn<C> + ToSchur<C>>(a: &A) -> BTreeMap<Partition, C> {
        convert::<C, A, PowerSum<C>>(a).terms().clone()
    }
    Some(match src {
        "s" => go(&Schur::from_terms(terms.clone())),
        "h" => go(&Homogeneous::from_terms(terms.clone())),
        "e" => go(&Elementary::from_terms(terms.clone())),
        "m" => go(&Monomial::from_terms(terms.clone())),
        "f" => go(&Forgotten::from_terms(terms.clone())),
        "p" => terms.clone(),
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::coeff::Rational;
    use crate::QtPoly;

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

    /// The five destinations `convert_named` reaches, as the codes it takes.
    const NAMED: [&str; 5] = ["s", "h", "e", "m", "f"];

    /// A basis change is ℤ-linear in the coefficient ring, so scaling every
    /// coefficient by `q²t` and converting must give `q²t` times the integer
    /// answer. The integer route is the one the oracles cover, and the two
    /// share no coefficient arithmetic — `i64` addition against `QtPoly`
    /// addition — so agreement is evidence about the dispatch rather than
    /// about a shared implementation. A transposed arm in either table shows
    /// up as a mismatch at the pair that names it.
    #[test]
    fn convert_named_scales_with_the_coefficient_ring() {
        let mut plain: BTreeMap<Partition, i64> = BTreeMap::new();
        plain.insert(part(&[2, 1]), 1);
        plain.insert(part(&[1, 1, 1]), 2);
        plain.insert(part(&[2]), -3);
        let scaled: BTreeMap<Partition, QtPoly<i64>> = plain
            .iter()
            .map(|(la, c)| (la.clone(), QtPoly::term(2, 1, *c)))
            .collect();

        for src in NAMED {
            for dst in NAMED {
                let a = convert_named(&plain, src, dst).unwrap();
                let b = convert_named(&scaled, src, dst).unwrap();
                assert_eq!(a.len(), b.len(), "{src} -> {dst}: term counts differ");
                for (la, c) in &a {
                    assert_eq!(
                        b.get(la),
                        Some(&QtPoly::term(2, 1, *c)),
                        "{src} -> {dst}: coefficient of {la}"
                    );
                }
            }
        }
    }

    /// Every ordered pair composes back to the identity, which is what makes
    /// the nine parametric bases reachable from each other: both ends expand
    /// into a classical basis, so a route between them is two of these.
    #[test]
    fn convert_named_round_trips_every_ordered_pair() {
        let mut f: BTreeMap<Partition, QtPoly<i64>> = BTreeMap::new();
        f.insert(part(&[2, 1]), QtPoly::term(0, 1, 1));
        f.insert(part(&[1, 1, 1]), QtPoly::term(1, 0, -2));
        for src in NAMED {
            for dst in NAMED {
                let there = convert_named(&f, src, dst).unwrap();
                let back = convert_named(&there, dst, src).unwrap();
                assert_eq!(back, f, "{src} -> {dst} -> {src}");
            }
        }
    }

    /// The power-sum destination divides by z_μ and so needs a `QAlgebra`,
    /// which `QtPoly<i64>` is not; an unknown code is the other `None`. Both
    /// decline rather than reaching for a route that does not exist.
    #[test]
    fn convert_named_declines_power_sum_and_unknown_codes() {
        let mut f: BTreeMap<Partition, QtPoly<i64>> = BTreeMap::new();
        f.insert(part(&[2]), QtPoly::term(0, 1, 1));
        assert!(convert_named(&f, "m", "p").is_none(), "m -> p declines");
        assert!(
            convert_named(&f, "Schur", "s").is_none(),
            "long name declines"
        );
        assert!(
            convert_named(&f, "m", "z").is_none(),
            "unknown dst declines"
        );
        // The source side accepts `p`: only the division is unavailable.
        assert!(convert_named(&f, "p", "s").is_some(), "p -> s converts");
    }

    /// `convert_named` and `convert` are the same routing, so a pair with a
    /// direct rule and a pair without must each match the typed call. `p → h`
    /// is Newton's identity and `m → f` composes through the hub.
    #[test]
    fn convert_named_matches_the_typed_call() {
        let mut f: BTreeMap<Partition, Rational> = BTreeMap::new();
        f.insert(part(&[2, 1]), Rational::new(3, 2));
        let p = PowerSum::from_terms(f.clone());
        let h: Homogeneous<Rational> = convert(&p);
        assert_eq!(
            convert_named(&f, "p", "h").unwrap(),
            *h.terms(),
            "p -> h, the direct rule"
        );
        let m = Monomial::from_terms(f.clone());
        let fg: Forgotten<Rational> = convert(&m);
        assert_eq!(
            convert_named(&f, "m", "f").unwrap(),
            *fg.terms(),
            "m -> f, through the hub"
        );
    }

    /// The matrix route against the Schur hub, which reaches the same numbers
    /// as Σ_λ K_{λμ} K_{λν} — Kostka columns and Jacobi–Trudi, sharing no code
    /// with the row-by-row matrix count.
    #[test]
    fn matrix_route_matches_the_schur_hub() {
        for n in 0..=9u32 {
            for mu in partitions_cached(n).iter() {
                let h: Homogeneous<i64> = Homogeneous::monomial(mu.clone(), 1);
                let e: Elementary<i64> = Elementary::monomial(mu.clone(), 1);
                let hm: Monomial<i64> = convert(&h);
                assert_eq!(hm, Monomial::from_schur(&h.to_schur()), "h_{mu} -> m");
                let em: Monomial<i64> = convert(&e);
                assert_eq!(em, Monomial::from_schur(&e.to_schur()), "e_{mu} -> m");
                let hf: Forgotten<i64> = convert(&h);
                assert_eq!(hf, Forgotten::from_schur(&h.to_schur()), "h_{mu} -> f");
                let ef: Forgotten<i64> = convert(&e);
                assert_eq!(ef, Forgotten::from_schur(&e.to_schur()), "e_{mu} -> f");
            }
        }
        // A mixed-degree element with signed coefficients, so the trie's
        // shared prefixes and the per-term scatter both run.
        let mut h: Homogeneous<i64> = Homogeneous::zero();
        for n in 0..=8u32 {
            for (i, mu) in partitions_cached(n).iter().enumerate() {
                h.add_term(mu.clone(), if i % 2 == 0 { 2 } else { -1 });
            }
        }
        let got: Monomial<i64> = convert(&h);
        assert_eq!(
            got,
            Monomial::from_schur(&h.to_schur()),
            "mixed degrees 0..=8, signed"
        );
    }

    /// h_{(2,1)} = m_3 + 2m_21 + 3m_111 but e_{(2,1)} = m_21 + 3m_111: the m_3
    /// term and the m_21 coefficient separate the non-negative count from the
    /// 0-1 count, so a swapped rule cannot pass. Hand computation:
    /// h_2 h_1 = (m_2 + m_11) m_1 and e_2 e_1 = m_11 m_1, by monomials.
    #[test]
    fn nonneg_and_zero_one_counts_are_not_the_same_rule() {
        let terms = BTreeMap::from([(part(&[2, 1]), 1i64)]);
        let hm = <Monomial<i64> as FromSchur<i64>>::from_basis("h", &terms).unwrap();
        assert_eq!(hm.coeff(&part(&[3])), 1);
        assert_eq!(hm.coeff(&part(&[2, 1])), 2);
        assert_eq!(hm.coeff(&part(&[1, 1, 1])), 3);
        assert_eq!(hm.terms().len(), 3);
        let em = <Monomial<i64> as FromSchur<i64>>::from_basis("e", &terms).unwrap();
        assert_eq!(em.coeff(&part(&[3])), 0);
        assert_eq!(em.coeff(&part(&[2, 1])), 1);
        assert_eq!(em.coeff(&part(&[1, 1, 1])), 3);
        assert_eq!(em.terms().len(), 2);
    }

    /// Past the limit the route must decline — handing [`convert`] back to the
    /// hub — rather than run binomials past their `u128` bound proof.
    #[test]
    fn matrix_route_declines_past_its_limit() {
        let terms = BTreeMap::from([(part(&[MATRIX_ROUTE_LIMIT + 1]), 1i64)]);
        assert!(<Monomial<i64> as FromSchur<i64>>::from_basis("h", &terms).is_none());
        assert!(<Forgotten<i64> as FromSchur<i64>>::from_basis("e", &terms).is_none());
    }

    /// f_{(n)} = (−1)^{n−1} p_n and f_{(1^n)} = h_n.
    ///
    /// Both are hand-derivable and neither mentions ω: the implementation *is*
    /// "apply ω", so a test that mentioned ω would only restate it. These come
    /// from the two edge cases of the monomial basis, m_{(n)} = p_n and
    /// m_{(1^n)} = e_n, pushed through ω(p_n) = (−1)^{n−1} p_n and ω(e_n) =
    /// h_n — facts about the *other* bases.
    #[test]
    fn forgotten_endpoints_match_hand_computation() {
        // The endpoints are one row and one column of n >= 1 cells, and the sign
        // (-1)^{n-1} has no n = 0 case; the empty shape is covered by the
        // round-trip and duality tests, which sweep from 0.
        for n in 1..=6u32 {
            let row: Forgotten<i64> = Forgotten::monomial(part(&[n]), 1);
            let want = if (n - 1) % 2 == 0 { 1 } else { -1 };
            let got: PowerSum<Rational> = PowerSum::from_schur(&to_rat(&row.to_schur()));
            assert_eq!(got.terms().len(), 1, "f_({n}) should be a single p term");
            assert_eq!(got.coeff(&part(&[n])), Rational::from_int(want));

            let col: Forgotten<i64> = Forgotten::monomial(part(&vec![1; n as usize]), 1);
            let h: Homogeneous<i64> = Homogeneous::from_schur(&col.to_schur());
            assert_eq!(h.coeff(&part(&[n])), 1);
            assert_eq!(h.terms().len(), 1, "f_(1^{n}) should be exactly h_{n}");
        }
    }

    /// {f_λ} is dual to {e_λ} under the Hall inner product: ⟨f_λ, e_μ⟩ =
    /// δ_{λμ}.
    ///
    /// This is the structural characterization of the forgotten basis, and it
    /// reaches it through code the conversion never touches — `hall` and the e
    /// → s expansion. If `Forgotten` were wired to the wrong involution, or to
    /// conjugation on the *index* rather than on the Schur expansion, the
    /// duality would fail while a round trip still closed.
    #[test]
    fn forgotten_is_dual_to_elementary() {
        for n in 0..=7u32 {
            let parts = partitions_cached(n);
            for lambda in parts.iter() {
                let f: Forgotten<i64> = Forgotten::monomial(lambda.clone(), 1);
                for mu in parts.iter() {
                    let e: Elementary<i64> = Elementary::monomial(mu.clone(), 1);
                    let want = i64::from(lambda == mu);
                    assert_eq!(
                        crate::ops::hall::<i64, _, _>(&f, &e),
                        want,
                        "<f_{lambda}, e_{mu}>"
                    );
                }
            }
        }
    }

    /// Every basis pair round-trips through the Schur hub, forgotten included.
    #[test]
    fn forgotten_round_trips_through_every_basis() {
        for n in 0..=7u32 {
            for lambda in partitions_cached(n).iter() {
                let f: Forgotten<i64> = Forgotten::monomial(lambda.clone(), 1);
                let s = f.to_schur();
                assert_eq!(Forgotten::from_schur(&s), f, "f -> s -> f");

                // out through each other basis and back
                let m: Monomial<i64> = Monomial::from_schur(&s);
                assert_eq!(Forgotten::from_schur(&m.to_schur()), f, "via m");
                let e: Elementary<i64> = Elementary::from_schur(&s);
                assert_eq!(Forgotten::from_schur(&e.to_schur()), f, "via e");
                let h: Homogeneous<i64> = Homogeneous::from_schur(&s);
                assert_eq!(Forgotten::from_schur(&h.to_schur()), f, "via h");
            }
        }
    }

    fn to_rat(s: &Schur<i64>) -> Schur<Rational> {
        let mut out = Schur::zero();
        for (p, c) in s.terms() {
            out.add_term(p.clone(), Rational::from_int(*c as i128));
        }
        out
    }

    #[test]
    fn h_and_e_expand_into_schur() {
        // h_{11} = s_2 + s_{11}; e_2 = s_{11}.
        let h11: Homogeneous<i64> = Homogeneous::monomial(part(&[1, 1]), 1);
        let s = h11.to_schur();
        assert_eq!(s.coeff(&part(&[2])), 1);
        assert_eq!(s.coeff(&part(&[1, 1])), 1);

        let e2: Elementary<i64> = Elementary::monomial(part(&[2]), 1);
        let se = e2.to_schur();
        assert_eq!(se.coeff(&part(&[1, 1])), 1);
        assert_eq!(se.terms().len(), 1);
    }

    /// Every direct transition among h, e and p gives what the Schur hub gives,
    /// on every index of every degree through 9.
    ///
    /// The two routes share no step. The hub side is Pieri products, a
    /// Jacobi–Trudi determinant and — for p — a table of `S_n` characters
    /// divided by z_μ; the direct side is a linear recursion over index
    /// concatenation. A sign convention that were self-consistently wrong on
    /// one side would still fail here, which a round trip through the same rule
    /// would not.
    #[test]
    fn the_direct_multiplicative_routes_agree_with_the_hub() {
        for n in 0..=9u32 {
            for lambda in partitions_cached(n).iter() {
                let h: Homogeneous<i64> = Homogeneous::monomial(lambda.clone(), 1);
                let e: Elementary<i64> = Elementary::monomial(lambda.clone(), 1);
                let p: PowerSum<i64> = PowerSum::monomial(lambda.clone(), 1);

                assert_eq!(
                    convert::<i64, _, Elementary<i64>>(&h),
                    Elementary::from_schur(&h.to_schur()),
                    "h_{lambda} -> e"
                );
                assert_eq!(
                    convert::<i64, _, Homogeneous<i64>>(&e),
                    Homogeneous::from_schur(&e.to_schur()),
                    "e_{lambda} -> h"
                );
                assert_eq!(
                    convert::<i64, _, Homogeneous<i64>>(&p),
                    Homogeneous::from_schur(&p.to_schur()),
                    "p_{lambda} -> h"
                );
                assert_eq!(
                    convert::<i64, _, Elementary<i64>>(&p),
                    Elementary::from_schur(&p.to_schur()),
                    "p_{lambda} -> e"
                );

                // The two directions into p divide, so they need a ring
                // containing ℚ on both sides of the comparison.
                let hq: Homogeneous<Rational> =
                    Homogeneous::monomial(lambda.clone(), Rational::one());
                let eq: Elementary<Rational> =
                    Elementary::monomial(lambda.clone(), Rational::one());
                assert_eq!(
                    convert::<Rational, _, PowerSum<Rational>>(&hq),
                    PowerSum::from_schur(&hq.to_schur()),
                    "h_{lambda} -> p"
                );
                assert_eq!(
                    convert::<Rational, _, PowerSum<Rational>>(&eq),
                    PowerSum::from_schur(&eq.to_schur()),
                    "e_{lambda} -> p"
                );
            }
        }
    }

    #[test]
    fn jacobi_trudi_inverts_expansion() {
        // s_{11} = h_{11} − h_2 (Jacobi–Trudi).
        let s11: Schur<i64> = Schur::monomial(part(&[1, 1]), 1);
        let h = Homogeneous::from_schur(&s11);
        assert_eq!(h.coeff(&part(&[1, 1])), 1);
        assert_eq!(h.coeff(&part(&[2])), -1);
    }

    /// The batched p → s must equal expanding each p_μ on its own and summing.
    /// Batching groups terms by shared prefix and continues one layer per
    /// group; an off-by-one in that grouping would silently attribute a term to
    /// the wrong μ, which no round-trip test would catch.
    #[test]
    fn batched_p_expansion_matches_per_term() {
        for n in 0..=10u32 {
            let mus = partitions_cached(n);
            // A single element carrying *every* p_μ of the degree at once, which
            // is the shape plethysm produces and the case batching exists for.
            let mut elt: PowerSum<i128> = PowerSum::zero();
            for (i, mu) in mus.iter().enumerate() {
                elt.add_term(mu.clone(), (i as i128) + 1);
            }
            let got: Schur<i128> = elt.to_schur();

            let mut want: Schur<i128> = Schur::zero();
            for (i, mu) in mus.iter().enumerate() {
                for (lambda, chi) in p_expand(mu).expect("small degree") {
                    want.add_term(lambda, chi * ((i as i128) + 1));
                }
            }
            assert_eq!(got, want, "batched p → s at degree {n}");
        }
    }

    /// The two mask widths are one algorithm, so they must not be two answers.
    ///
    /// Only degrees at most [`MASK_LIMIT`] can be run both ways, and those are
    /// exactly the degrees the wide path never sees in production — which is
    /// the point. Without this, `u128` would be exercised only where nothing
    /// else can check it, and a transcription slip in the wider `Beta` impl
    /// would surface as a wrong plethysm at a degree no oracle reaches.
    #[test]
    fn the_two_mask_widths_agree_where_both_apply() {
        // Small degrees only. Every partition of n is swept both ways here, so
        // the cost climbs with p(n), and what is being checked is a bit
        // transcription rather than anything that appears late: the widths
        // either agree on the whole layer algebra or they disagree at once.
        for n in 1..=14u32 {
            let mus = partitions_cached(n);
            let items: Vec<(&Partition, &i128)> = mus.iter().map(|mu| (mu, &1i128)).collect();

            let mut narrow: Schur<i128> = Schur::zero();
            sweep_degree::<u64, i128>(&items, n as usize, &mut narrow);
            let mut wide: Schur<i128> = Schur::zero();
            sweep_degree::<u128, i128>(&items, n as usize, &mut wide);

            assert_eq!(narrow, wide, "u64 and u128 sweeps disagree at degree {n}");
        }
    }

    /// p → s past the old 32 wall, against a closed form rather than a route.
    ///
    /// `p_n = Σ_{r<n} (−1)^r s_{(n−r, 1^r)}` — the alternating sum of hooks —
    /// is exact, independent of everything here, and cheap on both sides: a
    /// one-part μ is a single Murnaghan–Nakayama step from the root, so the
    /// layer never grows. A round trip through s → p would test the same wide
    /// sweep but costs p(n) terms to set up, which is minutes at these degrees
    /// in a debug build and does not belong in a suite that runs in seconds.
    ///
    /// Degrees 33 and 55 are the two that matter: the first is the one past
    /// the narrow mask, the second is [`WIDE_MASK_LIMIT`] itself, where the
    /// `i128` bound in its doc is tightest.
    #[test]
    fn the_wide_mask_expands_a_power_sum_to_its_hooks() {
        for n in [33u32, 40, WIDE_MASK_LIMIT as u32] {
            let p: PowerSum<i128> = PowerSum::monomial(Partition::new([n]), 1);

            let mut want: Schur<i128> = Schur::zero();
            for r in 0..n {
                let mut parts = vec![n - r];
                parts.extend(std::iter::repeat_n(1, r as usize));
                want.add_term(
                    Partition::from_sorted(parts),
                    if r % 2 == 0 { 1 } else { -1 },
                );
            }
            assert_eq!(p.to_schur(), want, "p_{n} → s is not the hook sum");
        }
    }

    /// The common-denominator integer sweep must agree exactly with rational
    /// arithmetic done per term.
    ///
    /// `batched_p_expansion_matches_per_term` above cannot cover this: it uses
    /// `PowerSum<i128>`, and `i128` declines `as_ratio`, so it exercises the
    /// generic path only. Over ℚ the integral path is what actually runs, and
    /// it is the one with a common denominator, a rescale, and three overflow
    /// checks in it.
    ///
    /// Coefficients are z_μ⁻¹, which is not an arbitrary choice — that is
    /// exactly what `s → p` produces and what plethysm then feeds back through
    /// `p → s`.
    #[test]
    fn integral_sweep_matches_rational_arithmetic() {
        for n in 0..=10u32 {
            let mus = partitions_cached(n);
            let mut elt: PowerSum<Rational> = PowerSum::zero();
            for mu in mus.iter() {
                elt.add_term(mu.clone(), Rational::new(1, mu.z() as i128));
            }
            let got: Schur<Rational> = elt.to_schur();

            let mut want: Schur<Rational> = Schur::zero();
            for mu in mus.iter() {
                let c = Rational::new(1, mu.z() as i128);
                for (lambda, chi) in p_expand(mu).expect("small degree") {
                    want.add_term(lambda, Rational::from_i128(chi).mul(&c));
                }
            }
            assert_eq!(got, want, "integral p → s at degree {n}");
        }
    }

    /// A ring that declines `as_ratio` must still convert correctly — the
    /// integral sweep has to bail without having written anything.
    #[test]
    fn rings_that_decline_as_ratio_fall_back_cleanly() {
        for n in 0..=8u32 {
            let mus = partitions_cached(n);
            let mut elt: PowerSum<i128> = PowerSum::zero();
            for (i, mu) in mus.iter().enumerate() {
                elt.add_term(mu.clone(), (i as i128) - 3);
            }
            assert!(i128::from_ratio(1, 2).is_none(), "i128 should decline");
            let got: Schur<i128> = elt.to_schur();
            let mut want: Schur<i128> = Schur::zero();
            for (i, mu) in mus.iter().enumerate() {
                for (lambda, chi) in p_expand(mu).expect("small degree") {
                    want.add_term(lambda, chi * ((i as i128) - 3));
                }
            }
            assert_eq!(got, want, "fallback p → s at degree {n}");
        }
    }

    /// Muir's rule against the linear solve it replaced, on **every** μ up to
    /// degree 12 — the two are independent routes to the same row of K⁻¹, and
    /// the solve was the shipped implementation, so this is a real oracle
    /// rather than a self-consistency check.
    #[test]
    fn muir_agrees_with_the_inverse_kostka_solve() {
        for n in 0..=12u32 {
            let parts = lex_parts_cached(n);
            for mu in parts.iter() {
                let row = inverse_kostka_row(&parts, mu);
                let mut want: Vec<(Partition, i128)> = parts
                    .iter()
                    .zip(&row)
                    .filter(|(_, &v)| v != 0)
                    .map(|(l, &v)| (l.clone(), v))
                    .collect();
                let mut got = muir_expand(mu).expect("degree 12 is inside the mask");
                want.sort();
                got.sort();
                assert_eq!(got, want, "m_{mu} in the Schur basis");
            }
        }
    }

    /// The batched Kostka sweep against one `kostka` call per pair, which is
    /// the chain DP over the shapes inside λ — a different walk from the
    /// unpruned Pieri trie, and the one the Sage fixtures validate. Every
    /// degree through 12, on full support with signed coefficients that make
    /// some m_μ coefficients cancel, on a thinned subset that exercises the
    /// coefficient-side walk of the leaf, and on the mixed-degree element the
    /// public entry point dispatches degree by degree.
    #[test]
    fn batched_kostka_sweep_matches_per_pair() {
        fn per_pair(items: &[(&Partition, &i128)], n: u32) -> Monomial<i128> {
            let mut want = Monomial::zero();
            for &(lambda, c) in items {
                for mu in partitions_cached(n).iter() {
                    want.add_term(mu.clone(), i128::from_u128(kostka(lambda, mu)) * c);
                }
            }
            want
        }
        let mut mixed: Schur<i128> = Schur::zero();
        for n in 1..=12u32 {
            let parts = partitions_cached(n);
            let coeffs: Vec<i128> = (0..parts.len())
                .map(|i| [3, -1, 2, -5, 1][i % 5] * (i as i128 % 7 - 3))
                .collect();
            let full: Vec<(&Partition, &i128)> = parts.iter().zip(&coeffs).collect();
            let thin: Vec<(&Partition, &i128)> = full.iter().copied().step_by(9).collect();
            for (name, items) in [("full", &full), ("thin", &thin)] {
                let mut got = Monomial::zero();
                kostka_batched(items, n, &mut got);
                assert_eq!(got, per_pair(items, n), "degree {n}, {name} support");
            }
            for &(lambda, c) in &full {
                mixed.add_term(lambda.clone(), *c);
            }
        }
        let got: Monomial<i128> = Monomial::from_schur(&mixed);
        let mut want = Monomial::zero();
        for (lambda, c) in mixed.terms() {
            for mu in partitions_cached(lambda.size()).iter() {
                want.add_term(mu.clone(), i128::from_u128(kostka(lambda, mu)) * c);
            }
        }
        assert_eq!(got, want, "mixed degrees 1..=12 through from_schur");
    }

    /// The two shapes worked by hand when the rule was derived. `m_{21}` is the
    /// one that catches a wrong triangularity assumption: (K⁻¹)_{μλ} is nonzero
    /// for μ ⊵ λ, so λ may be *longer* than μ, and taking only ℓ(μ) slots would
    /// silently drop the s_{111} term and return the 2-variable answer.
    #[test]
    fn muir_matches_hand_computation() {
        let got = muir_expand(&part(&[2, 1])).unwrap();
        let mut got: Vec<_> = got.iter().map(|(l, c)| (l.parts().to_vec(), *c)).collect();
        got.sort();
        assert_eq!(got, vec![(vec![1, 1, 1], -2), (vec![2, 1], 1)]);

        // m_{(n)} = Σ_i (−1)^i s_{(n−i, 1^i)}: the hooks, alternating.
        let got = muir_expand(&part(&[5])).unwrap();
        let mut got: Vec<_> = got.iter().map(|(l, c)| (l.parts().to_vec(), *c)).collect();
        got.sort_by_key(|(l, _)| l.len());
        let want = vec![
            (vec![5], 1),
            (vec![4, 1], -1),
            (vec![3, 1, 1], 1),
            (vec![2, 1, 1, 1], -1),
            (vec![1, 1, 1, 1, 1], 1),
        ];
        assert_eq!(got, want);
    }

    fn strips_via_masks(lambda: &Partition, k: u32, vertical: bool) -> Vec<Partition> {
        let l = lambda.size() as usize + k as usize;
        let mut masks = Vec::new();
        strip_masks(beta_mask(lambda, l), k, vertical, &mut masks);
        let mut out: Vec<Partition> = masks.into_iter().map(|m| mask_to_partition(m, l)).collect();
        out.sort();
        out
    }

    /// The β-mask strip enumeration must agree with the partition-keyed one on
    /// every shape and every strip size through degree 10.
    ///
    /// The two are independent readings of the Pieri rule — one an interlacing
    /// on parts, the other on β-numbers — and the partition form is the one the
    /// Sage oracle fixtures already validate, so this is a real oracle rather
    /// than a self-consistency check. It also has to be, because the horizontal
    /// and vertical conditions are *different* constraints on the β-set and
    /// getting one of them wrong yields plausible partitions rather than
    /// errors.
    #[test]
    fn beta_mask_strips_agree_with_the_partition_enumeration() {
        for n in 0..=10u32 {
            for lambda in partitions_cached(n).iter() {
                for k in 0..=6u32 {
                    let mut want = Vec::new();
                    horizontal_strips(lambda.parts(), k, &mut want);
                    want.sort();
                    assert_eq!(
                        strips_via_masks(lambda, k, false),
                        want,
                        "horizontal {k}-strips on {lambda}"
                    );

                    let mut want = Vec::new();
                    vertical_strips(lambda.parts(), k, &mut want);
                    want.sort();
                    assert_eq!(
                        strips_via_masks(lambda, k, true),
                        want,
                        "vertical {k}-strips on {lambda}"
                    );
                }
            }
        }
    }

    /// A shape where the two strip types give *different* answers, worked by
    /// hand — the value that pins which is which.
    ///
    /// From λ = (2,1), the 2-strips that separate the two rules are (4,1) and
    /// (2,1,1,1). Horizontal means no two new cells in one **column**, vertical
    /// no two in one **row**:
    ///
    /// * (4,1)/λ puts both cells in row 0, columns 2 and 3 — horizontal only.
    /// * (2,1,1,1)/λ puts both in column 0, rows 2 and 3 — vertical only.
    /// * (3,2)/λ puts one at (0,2) and one at (1,1) — both rules accept it, and
    ///   testing it alone would not distinguish them.
    #[test]
    fn horizontal_and_vertical_strips_are_not_the_same_rule() {
        let lambda = part(&[2, 1]);
        let h = strips_via_masks(&lambda, 2, false);
        let v = strips_via_masks(&lambda, 2, true);
        assert!(h.contains(&part(&[4, 1])), "horizontal: two cells in row 0");
        assert!(!v.contains(&part(&[4, 1])), "vertical: never two in a row");
        assert!(
            v.contains(&part(&[2, 1, 1, 1])),
            "vertical: two cells in column 0"
        );
        assert!(
            !h.contains(&part(&[2, 1, 1, 1])),
            "horizontal: never two in a column"
        );
        assert!(
            h.contains(&part(&[3, 2])) && v.contains(&part(&[3, 2])),
            "both rules accept (3,2)"
        );
    }

    /// s_λ · h_k and s_λ · e_k through the mask layer must equal the general
    /// Littlewood–Richardson product, which is what this path replaced.
    #[test]
    fn pieri_steps_agree_with_the_lr_product() {
        for n in 0..=7u32 {
            for lambda in partitions_cached(n).iter() {
                for k in 1..=4u32 {
                    let s: Schur<i128> = Schur::monomial(lambda.clone(), 1);
                    for vertical in [false, true] {
                        let gen = if vertical {
                            Partition::new(std::iter::repeat_n(1, k as usize))
                        } else {
                            Partition::new([k])
                        };
                        let want = s.mul(&Schur::monomial(gen, 1));
                        let mut got: Schur<i128> = Schur::zero();
                        for mu in strips_via_masks(lambda, k, vertical) {
                            got.add_term(mu, 1);
                        }
                        assert_eq!(
                            got,
                            want,
                            "s_{lambda} * {}_{k}",
                            if vertical { "e" } else { "h" }
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn round_trips_are_identity() {
        // s → h → s and s → e → s and s → m → s recover the original.
        for parts in [&[2, 1][..], &[3, 1], &[2, 2], &[3, 2, 1]] {
            let s: Schur<i64> = Schur::monomial(part(parts), 1);
            let back_h: Schur<i64> = convert(&Homogeneous::from_schur(&s));
            let back_e: Schur<i64> = convert(&Elementary::from_schur(&s));
            let back_m: Schur<i64> = convert(&Monomial::from_schur(&s));
            assert_eq!(back_h, s, "s→h→s at {:?}", parts);
            assert_eq!(back_e, s, "s→e→s at {:?}", parts);
            assert_eq!(back_m, s, "s→m→s at {:?}", parts);
        }
    }

    #[test]
    fn power_sum_round_trip_over_rationals() {
        // s → p → s over ℚ is the identity.
        for parts in [&[2, 1][..], &[3], &[2, 2], &[3, 1]] {
            let s: Schur<Rational> = Schur::monomial(part(parts), Rational::one());
            let p: PowerSum<Rational> = PowerSum::from_schur(&s);
            let back: Schur<Rational> = p.to_schur();
            assert_eq!(back, s, "s→p→s at {:?}", parts);
        }
    }

    #[test]
    fn power_sum_two_is_s2_minus_s11() {
        // p_2 = s_2 − s_{11}.
        let p2: PowerSum<i64> = PowerSum::monomial(part(&[2]), 1);
        let s = p2.to_schur();
        assert_eq!(s.coeff(&part(&[2])), 1);
        assert_eq!(s.coeff(&part(&[1, 1])), -1);
    }

    #[test]
    fn monomial_multiplication_via_schur() {
        // m_1 · m_1 = 2 m_{11} + m_2.
        let m1: Monomial<i64> = Monomial::monomial(part(&[1]), 1);
        let prod = m1.mul(&m1);
        assert_eq!(prod.coeff(&part(&[1, 1])), 2);
        assert_eq!(prod.coeff(&part(&[2])), 1);
        assert_eq!(prod.terms().len(), 2);
    }
}