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
//! The Orellana–Zabrocki character bases, and a reduced-Kronecker engine.
//!
//! Two inhomogeneous bases live here: [`St`] (`s̃_λ`, the irreducible character
//! basis) and [`Ht`] (`h̃_λ`, the induced trivial character basis). The source
//! is Orellana–Zabrocki [OZ]; equation and theorem numbers below, and every
//! `OZ Thm` in the item docs, are that paper's. `docs/record/kronecker.md` has
//! the measured record, including the measurements that chose between routes.
//!
//! The reason to want them is Theorem 7:
//!
//! ```text
//!     s̃_λ · s̃_μ = Σ_{|ν| ≤ |λ|+|μ|} ḡ^ν_{λμ} · s̃_ν
//! ```
//!
//! — an *ordinary* product of symmetric functions whose structure constants are
//! the **reduced (stable) Kronecker coefficients**. Nothing here is ever
//! indexed by a partition of the large n, so this sidesteps the p(n)×p(n)
//! character table that makes [`ops::internal`](crate::ops::internal) run out
//! of memory (1.1 GB at n = 32, per `docs/record/kronecker.md`) long before the
//! interesting cases.
//!
//! ## How it computes
//!
//! Theorem 14 gives the whole engine, once read the right way. The linear map Γ
//! defined by `Γ(s_λ) = s̃_λ` satisfies
//!
//! ```text
//!     Γ(p_γ) = 𝐩_γ = Π_i 𝐩_{i^{m_i(γ)}}                                  (24)
//!     𝐩_{i^r} = Σ_{k=0}^{r} (−1)^{r−k} i^k C(r,k) · (P_i)_k
//!     P_i     = (1/i) Σ_{d|i} μ(i/d) p_d      ⟺      p_i = Σ_{d|i} d·P_d
//! ```
//!
//! where `(x)_k` is the falling factorial *taken in the ring*. The consequence
//! the paper does not spell out, and that this module is built on: `𝐩_{i^r}` is
//! a univariate polynomial in `P_i` of degree r with leading coefficient `i^r`,
//! so the change of basis between monomials in the `P_i` and the `𝐩_γ` is a
//! **tensor product of univariate triangular matrices** — one per part size,
//! and each invertible on its own. Γ⁻¹ therefore costs a per-variable back
//! substitution rather than a p(n)×p(n) matrix inversion.
//!
//! That makes the product cheap in a way the Schur route is not:
//!
//! ```text
//!     s̃_λ · s̃_μ = Γ⁻¹( Γ(s_λ) · Γ(s_μ) ),  read in the Schur basis
//! ```
//!
//! and the multiplication in the middle happens in the **power-sum basis**,
//! where a product is a multiset union of indices. No Littlewood–Richardson
//! coefficient is computed anywhere in a reduced Kronecker calculation.
//!
//! ## What is checked, and against what
//!
//! Sage is an oracle here and was never read — the same clean-room rule the
//! LR engine was written under (`NOTICE.md`). Before any of this was written,
//! the Γ/Γ⁻¹
//! route was prototyped and compared against Sage's `st` basis: exact agreement
//! on the transitions and on products through `st[4,2]·st[4,2]`, which is 186
//! terms.
//!
//! ## References
//!
//! - **[OZ]** R. Orellana, M. Zabrocki, *Symmetric group characters as
//!   symmetric functions*, arXiv:1605.06672 — Theorem 1, the integral
//!   transitions and `s̃_{1^r}`; Theorem 7, the product rule above; and
//!   Theorem 14, the map Γ.
//!
//! [OZ]: https://arxiv.org/abs/1605.06672

// Shape indices. The two structure-constant narrowings check at their sites.
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]

use std::collections::BTreeMap;
use std::sync::Arc;

use crate::coeff::{QAlgebra, Rational, Ring};
use crate::convert::{FromSchur, ToSchur};
use crate::guard::{guarded, overflow_count, GuardedRat};
use crate::kostka::kostka;
use crate::memo::{
    bold_p_peek, bold_p_store, ht_to_st_cached, reduced_kronecker_cached, schur_to_st_cached,
    st_to_ht_cached, st_to_schur_cached,
};
use crate::partition::Partition;
use crate::sym::{impl_product_ops, Ht, PowerSum, Schur, St, SymAlgebra, SymFn};

// --- small number theory ----------------------------------------------------

fn divisors(n: u32) -> Vec<u32> {
    (1..=n).filter(|d| n.is_multiple_of(*d)).collect()
}

/// The number-theoretic Möbius function μ(n).
fn mobius(n: u32) -> i128 {
    let mut n = n;
    let mut primes = 0;
    let mut d = 2;
    while d * d <= n {
        if n.is_multiple_of(d) {
            n /= d;
            if n.is_multiple_of(d) {
                return 0; // a squared factor
            }
            primes += 1;
        }
        d += 1;
    }
    if n > 1 {
        primes += 1;
    }
    if primes % 2 == 0 {
        1
    } else {
        -1
    }
}

/// The parts of γ as (part, multiplicity) pairs, ascending by part.
fn multiplicities(gamma: &Partition) -> Vec<(u32, usize)> {
    let mut out: Vec<(u32, usize)> = Vec::new();
    for &part in gamma.parts().iter().rev() {
        match out.last_mut() {
            Some((p, m)) if *p == part => *m += 1,
            _ => out.push((part, 1)),
        }
    }
    out
}

// --- the univariate transition (24), and its inverse ------------------------

/// Coefficients of `𝐩_{i^r}` as a polynomial in `x = P_i`, indexed by power.
///
/// `B[m]` is the coefficient of `x^m`; `B[r] = i^r` is the leading one, which
/// is what makes the family a basis of `ℚ[x]` and the inverse below exist.
///
/// The entries stay small for a reason worth stating, since `i^k` looks
/// alarming: r is only ever a multiplicity `m_i(γ)` of a part i in a partition
/// of n, so `i·r ≤ n`. That makes `i^r` maximized around i = 2, r = n/2, where
/// it is ~10³ at n = 20 rather than 20²⁰. Callers that do not respect
/// `i·r ≤ n` are outside the
/// contract.
fn bold_uni(i: u32, r: usize) -> Vec<i128> {
    // Falling factorials (x)_k as coefficient vectors, built up by multiplying
    // by (x − (k−1)).
    let mut falls: Vec<Vec<i128>> = vec![vec![1]];
    for k in 1..=r {
        let prev = &falls[k - 1];
        let mut next = vec![0i128; k + 1];
        for (m, &c) in prev.iter().enumerate() {
            next[m + 1] += c; // times x
            next[m] -= c * (k as i128 - 1); // times −(k−1)
        }
        falls.push(next);
    }

    let mut out = vec![0i128; r + 1];
    let mut binom = 1i128; // C(r, k)
    for k in 0..=r {
        let sign = if (r - k).is_multiple_of(2) { 1 } else { -1 };
        let scale = sign * (i as i128).pow(k as u32) * binom;
        for (m, &c) in falls[k].iter().enumerate() {
            out[m] += scale * c;
        }
        binom = binom * (r as i128 - k as i128) / (k as i128 + 1);
    }
    out
}

/// A rational coefficient ring the engine can run over, and can recognize
/// integers in on the way out.
///
/// Two instantiations that matter, and the pair is the whole overflow story:
/// [`GuardedRat`], which is fixed-width and *reports* leaving it, and (under
/// the `bignum` feature) `BigRational`, which cannot leave it. The engine runs
/// over the first and re-runs over the second when the first says it lost.
trait RatLike: QAlgebra {
    /// The integer type this fraction is built from, for the passes that clear
    /// denominators and work in ℤ ([`schur_to_st_degree`]).
    type Int: IntLike;

    /// This value as an integer, or `None` if it is not one.
    fn as_integer(&self) -> Option<i128>;
    /// The numerator, in the reduced form the type maintains.
    fn numerator(&self) -> Self::Int;
    /// The denominator; positive, because the sign lives on the numerator.
    fn denominator(&self) -> Self::Int;
}

impl RatLike for Rational {
    type Int = i128;

    fn as_integer(&self) -> Option<i128> {
        (self.denom() == 1).then(|| self.numer())
    }
    fn numerator(&self) -> i128 {
        self.numer()
    }
    fn denominator(&self) -> i128 {
        self.denom()
    }
}

impl RatLike for GuardedRat {
    type Int = i128;

    fn as_integer(&self) -> Option<i128> {
        (self.denom() == 1).then(|| self.numer())
    }
    fn numerator(&self) -> i128 {
        self.numer()
    }
    fn denominator(&self) -> i128 {
        self.denom()
    }
}

#[cfg(feature = "bignum")]
impl RatLike for num_rational::BigRational {
    type Int = num_bigint::BigInt;

    fn as_integer(&self) -> Option<i128> {
        use num_traits::ToPrimitive;
        self.is_integer()
            .then(|| self.to_integer().to_i128())
            .flatten()
    }
    fn numerator(&self) -> num_bigint::BigInt {
        self.numer().clone()
    }
    fn denominator(&self) -> num_bigint::BigInt {
        self.denom().clone()
    }
}

/// Integer arithmetic for the cleared-denominator pass: checked at fixed
/// width, infallible over `BigInt` — which is what lets one generic pass be
/// both rungs of the escalation ladder, per `docs/policies/failure.md` ("the
/// wide pass is the same code").
trait IntLike: Clone + PartialEq {
    fn zero() -> Self;
    fn one() -> Self;
    fn is_zero(&self) -> bool;
    fn checked_mul(&self, o: &Self) -> Option<Self>;
    fn checked_add(&self, o: &Self) -> Option<Self>;
    /// `lcm(self, o)` for positive operands, or `None` past the width.
    fn checked_lcm(&self, o: &Self) -> Option<Self>;
    /// `self / o` where `o` divides `self` — the callers prove it (an lcm is
    /// divided by the denominators it absorbed).
    fn div_exact(&self, o: &Self) -> Self;
    /// `self / o` if `o` divides `self` exactly, else `None`.
    fn checked_div_exact(&self, o: &Self) -> Option<Self>;
    /// `χ^λ(μ)` in this width, or `None` past it.
    fn character(lambda: &Partition, mu: &Partition) -> Option<Self>;
    /// The value as an `i128`, or `None` if it does not fit.
    fn as_i128(&self) -> Option<i128>;
}

impl IntLike for i128 {
    fn zero() -> Self {
        0
    }
    fn one() -> Self {
        1
    }
    fn is_zero(&self) -> bool {
        *self == 0
    }
    fn checked_mul(&self, o: &Self) -> Option<Self> {
        i128::checked_mul(*self, *o)
    }
    fn checked_add(&self, o: &Self) -> Option<Self> {
        i128::checked_add(*self, *o)
    }
    fn checked_lcm(&self, o: &Self) -> Option<Self> {
        let g = crate::modular::gcd128(self.unsigned_abs(), o.unsigned_abs());
        (self / i128::try_from(g).ok()?).checked_mul(*o)
    }
    fn div_exact(&self, o: &Self) -> Self {
        debug_assert_eq!(self % o, 0);
        self / o
    }
    fn checked_div_exact(&self, o: &Self) -> Option<Self> {
        (self % o == 0).then(|| self / o)
    }
    fn character(lambda: &Partition, mu: &Partition) -> Option<Self> {
        crate::character::try_character(lambda, mu)
    }
    fn as_i128(&self) -> Option<i128> {
        Some(*self)
    }
}

#[cfg(feature = "bignum")]
impl IntLike for num_bigint::BigInt {
    fn zero() -> Self {
        <num_bigint::BigInt as num_traits::Zero>::zero()
    }
    fn one() -> Self {
        <num_bigint::BigInt as num_traits::One>::one()
    }
    fn is_zero(&self) -> bool {
        num_traits::Zero::is_zero(self)
    }
    fn checked_mul(&self, o: &Self) -> Option<Self> {
        Some(self * o)
    }
    fn checked_add(&self, o: &Self) -> Option<Self> {
        Some(self + o)
    }
    fn checked_lcm(&self, o: &Self) -> Option<Self> {
        let (mut a, mut b) = (self.clone(), o.clone());
        while !num_traits::Zero::is_zero(&b) {
            let t = &a % &b;
            a = b;
            b = t;
        }
        Some(self / &a * o)
    }
    fn div_exact(&self, o: &Self) -> Self {
        self / o
    }
    fn checked_div_exact(&self, o: &Self) -> Option<Self> {
        num_traits::Zero::is_zero(&(self % o)).then(|| self / o)
    }
    fn character(lambda: &Partition, mu: &Partition) -> Option<Self> {
        Some(crate::character::character_in(lambda, mu))
    }
    fn as_i128(&self) -> Option<i128> {
        num_traits::ToPrimitive::to_i128(self)
    }
}

/// The row `x^m = Σ_r N[r] · 𝐩_{i^r}`, by back substitution against
/// [`bold_uni`].
///
/// This is the piece that makes Γ⁻¹ cheap: the full change of basis is a tensor
/// product over part sizes, so inverting it never means inverting anything
/// bigger than an (m+1)×(m+1) triangular matrix.
fn bold_uni_inverse<R: RatLike>(i: u32, m: usize) -> Vec<R> {
    let rows: Vec<Vec<i128>> = (0..=m).map(|r| bold_uni(i, r)).collect();
    let mut coeffs = vec![R::zero(); m + 1];
    // Remainder in the monomial basis, starting at x^m.
    let mut rem = vec![R::zero(); m + 1];
    rem[m] = R::one();
    for r in (0..=m).rev() {
        if rem[r].is_zero() {
            continue;
        }
        // The diagonal entry is rows[r][r] = i^r, so the division is by a
        // positive integer — `QAlgebra`, never `Field`.
        let c = rem[r].div_u128((i as u128).pow(r as u32));
        coeffs[r] = c.clone();
        for (j, &b) in rows[r].iter().enumerate().take(r + 1) {
            let term = c.mul(&R::from_i128(b));
            rem[j].sub_assign(&term);
        }
    }
    coeffs
}

/// `P_i = (1/i) Σ_{d|i} μ(i/d) p_d`, in the power-sum basis.
fn p_variable<R: RatLike>(i: u32) -> PowerSum<R> {
    let mut out = PowerSum::zero();
    for d in divisors(i) {
        let m = mobius(i / d);
        if m != 0 {
            out.add_term(Partition::new([d]), R::from_i128(m).div_u128(i as u128));
        }
    }
    out
}

/// `𝐩_γ` in the power-sum basis (OZ Eq 24).
fn bold_p_in<R: RatLike>(gamma: &Partition) -> PowerSum<R> {
    let mut acc: PowerSum<R> = PowerSum::unit();
    for (i, r) in multiplicities(gamma) {
        let coeffs = bold_uni(i, r);
        let pi = p_variable::<R>(i);
        // Powers of P_i, accumulated rather than recomputed.
        let mut power: PowerSum<R> = PowerSum::unit();
        let mut factor = PowerSum::zero();
        for (m, &c) in coeffs.iter().enumerate() {
            if m > 0 {
                power = power.mul(&pi);
            }
            if c != 0 {
                factor = factor.add(&power.scale(&R::from_i128(c)));
            }
        }
        acc = acc.mul(&factor);
    }
    acc
}

/// `𝐩_γ` over [`GuardedRat`], memoized — but **only when the computation stayed
/// inside the fixed width**.
///
/// A value produced by a call that overflowed is garbage, and caching it would
/// convert a detected overflow into an undetected one: the counter is compared
/// around the call that computes a value, so a later reader of a poisoned entry
/// would see a clean counter and accept the answer. Recomputing is the cheap
/// side of that trade — past the wall every call is about to escalate anyway.
fn bold_guarded(gamma: &Partition) -> PowerSum<GuardedRat> {
    if let Some(v) = bold_p_peek(gamma) {
        return (*v).clone();
    }
    let before = overflow_count();
    let value = bold_p_in::<GuardedRat>(gamma);
    if overflow_count() == before {
        bold_p_store(gamma, value.clone());
    }
    value
}

// --- Γ and Γ⁻¹ ---------------------------------------------------------------

/// Apply Γ to a power-sum element: `p_γ ↦ 𝐩_γ` (OZ Thm 14).
///
/// Because `Γ(s_λ) = s̃_λ`, this is how an `st` element becomes an ordinary
/// one: write it over the Schur basis formally, convert to power sums, apply
/// this.
fn gamma<R: RatLike>(f: &PowerSum<R>, bold: fn(&Partition) -> PowerSum<R>) -> PowerSum<R> {
    let mut out = PowerSum::zero();
    for (g, c) in f.terms() {
        crate::interrupt::poll();
        for (idx, v) in bold(g).terms() {
            out.add_term(idx.clone(), v.mul(c));
        }
    }
    out
}

/// Apply Γ⁻¹ to a power-sum element.
///
/// Two steps, both of them tensor products over part sizes:
///
/// 1. `p → P`-monomials, by `p_i = Σ_{d|i} d·P_d` (the Möbius inverse of the
///    definition of `P_i`, so this direction has no denominators at all);
/// 2. `P`-monomials → the `𝐩` basis, by [`bold_uni_inverse`] one variable at a
///    time.
///
/// The result is read back with its indices interpreted as `p_γ` rather than
/// `𝐩_γ`, which is exactly Γ⁻¹.
fn gamma_inverse<R: RatLike>(f: &PowerSum<R>) -> PowerSum<R> {
    // Step 1: expand into monomials in the P variables.
    let mut monomials: BTreeMap<Partition, R> = BTreeMap::new();
    for (g, c) in f.terms() {
        crate::interrupt::poll();
        let mut acc: BTreeMap<Vec<u32>, R> = BTreeMap::new();
        acc.insert(Vec::new(), c.clone());
        for &part in g.parts() {
            let mut next: BTreeMap<Vec<u32>, R> = BTreeMap::new();
            for (mono, cc) in &acc {
                for d in divisors(part) {
                    let mut key = mono.clone();
                    key.push(d);
                    key.sort_unstable_by(|a, b| b.cmp(a));
                    let v = cc.mul(&R::from_i128(d as i128));
                    next.entry(key)
                        .and_modify(|e| e.add_assign(&v))
                        .or_insert(v);
                }
            }
            acc = next;
        }
        for (mono, v) in acc {
            if v.is_zero() {
                continue;
            }
            let key = Partition::new(mono);
            monomials
                .entry(key)
                .and_modify(|e| e.add_assign(&v))
                .or_insert(v);
        }
    }

    // Step 2: each P-monomial into the 𝐩 basis, one variable at a time.
    let mut out = PowerSum::zero();
    for (mono, c) in monomials {
        crate::interrupt::poll();
        if c.is_zero() {
            continue;
        }
        let mut acc: BTreeMap<Vec<u32>, R> = BTreeMap::new();
        acc.insert(Vec::new(), c);
        for (i, m) in multiplicities(&mono) {
            let inv = bold_uni_inverse::<R>(i, m);
            let mut next: BTreeMap<Vec<u32>, R> = BTreeMap::new();
            for (idx, cc) in &acc {
                for (r, n) in inv.iter().enumerate() {
                    if n.is_zero() {
                        continue;
                    }
                    let mut key = idx.clone();
                    key.extend(std::iter::repeat_n(i, r));
                    key.sort_unstable_by(|a, b| b.cmp(a));
                    let v = cc.mul(n);
                    next.entry(key)
                        .and_modify(|e| e.add_assign(&v))
                        .or_insert(v);
                }
            }
            acc = next;
        }
        for (idx, v) in acc {
            out.add_term(Partition::new(idx), v);
        }
    }
    out
}

/// A Schur element over ℚ whose coefficients are known to be integers, as
/// integers.
///
/// Both transitions are integral — Γ⁻¹ by OZ Thm 1(2), where the coefficients
/// are multiplicities in the restriction of a GLₙ-module, and Γ because it
/// inverts one. The rationals are an artefact of routing through power sums,
/// which divides by `z_γ`. Panicking on a surviving denominator is the same
/// discipline `Rat::into_poly` applies on the Macdonald side: the theorem is
/// enforced where it is used, not assumed.
fn integral_row<R: RatLike>(f: &Schur<R>) -> Option<Vec<(Partition, i128)>> {
    f.terms()
        .iter()
        .map(|(p, c)| c.as_integer().map(|n| (p.clone(), n)))
        .collect()
}

/// `s̃_λ` in the power-sum basis.
fn st_in_power_sum<R: RatLike>(
    lambda: &Partition,
    bold: fn(&Partition) -> PowerSum<R>,
) -> PowerSum<R> {
    let s: Schur<R> = Schur::monomial(lambda.clone(), R::one());
    gamma(&PowerSum::from_schur(&s), bold)
}

/// Run a row computation over fixed-width coefficients, and re-run it exactly
/// if anything left the width.
///
/// The measured wall is `|λ|+|μ| = 24`: `st[8,5]·st[7,4]` completes and
/// `st[8,5]·st[8,5]` does not. The overflow is entirely in the **intermediate**
/// rationals — the answers there are 16-bit — because routing through power
/// sums divides by `z_γ`, and `z_γ` alone reaches 10²⁶ by degree 26, before the
/// two sides are multiplied together.
///
/// Without the `bignum` feature this panics rather than returning something
/// wrong, which is the only acceptable behavior: an intermediate that left the
/// width has no exact continuation here. A wrapped intermediate can land on a
/// denominator of 1 and be accepted as an integer answer. That is the failure
/// mode [`guarded`] exists to remove.
fn escalating<T>(
    what: &str,
    fast: impl FnOnce() -> Option<T>,
    exact: impl FnOnce() -> Option<T>,
) -> T {
    // Two ways the fast path can lose, and both must be non-fatal: the guard
    // counter moves, or a wrapped intermediate lands on a value that is not an
    // integer. Panicking on the second — which an earlier version did, inside
    // the closure — makes the escalation unreachable, since the panic escapes
    // `guarded` before it can report `None`.
    if let Some(Some(v)) = guarded(fast) {
        return v;
    }
    #[cfg(feature = "bignum")]
    {
        let _ = what;
        exact().unwrap_or_else(|| {
            panic!(
                "{what}: a coefficient is not an integer over BigRational, which is a bug \
                    rather than an overflow"
            )
        })
    }
    #[cfg(not(feature = "bignum"))]
    {
        let _ = exact;
        panic!(
            "{what}: an intermediate coefficient left i128. The answers are almost \
             certainly small — the wall is the z_γ-sized denominators this route \
             divides by or clears, not the coefficients it returns. Rebuild with \
             --features bignum."
        )
    }
}

/// `s̃_λ` in the Schur basis, memoized.
///
/// A miss computes and stores the **whole degree** ([`st_to_schur_degree`]),
/// the same unit [`schur_to_st_row`] uses and for the same reason: the rows
/// share their expensive part, and the callers convert whole elements.
fn st_to_schur_row(lambda: &Partition) -> Arc<Vec<(Partition, i128)>> {
    st_to_schur_cached(lambda, || {
        let n = lambda.size();
        let rows = escalating(
            &format!("s̃ → s at degree {n}"),
            || st_to_schur_degree::<GuardedRat>(n, bold_guarded),
            || {
                #[cfg(feature = "bignum")]
                {
                    st_to_schur_degree::<num_rational::BigRational>(n, bold_p_in)
                }
                #[cfg(not(feature = "bignum"))]
                None
            },
        );
        let mut mine = None;
        for (v, row) in crate::memo::partitions_cached(n).iter().zip(rows) {
            if v == lambda {
                mine = Some(row);
            } else {
                st_to_schur_cached(v, || row);
            }
        }
        mine.expect("partitions_cached(|λ|) lists every partition of |λ|")
    })
}

/// Every row `s̃_λ → s` of one degree, in `partitions_cached(n)` order.
///
/// `s̃_λ = Σ_{γ⊢n} χ^λ(γ)/z_γ · 𝐩_γ` (OZ Eq 23), so the shared per-γ vector
/// is the Schur expansion of `𝐩_γ/z_γ` — where the route this replaced
/// converted the whole assembled element once per λ, the p(n)² shape the
/// `s → s̃` direction had already shed (`docs/record/kronecker.md`).
///
/// `bold` is the source of `𝐩_γ`: memoized [`bold_guarded`] on the fixed
/// rung, plain [`bold_p_in`] on the wide one — the same pair
/// [`st_in_power_sum`] takes.
fn st_to_schur_degree<R: RatLike>(
    n: u32,
    bold: fn(&Partition) -> PowerSum<R>,
) -> Option<Vec<Vec<(Partition, i128)>>> {
    degree_rows(n, |g| {
        let mut pg: PowerSum<R> = PowerSum::zero();
        pg.add_term(g.clone(), g.div_by_z(&R::one()));
        gamma(&pg, bold)
    })
}

/// Every row `s_ν → s̃` of one degree, in `partitions_cached(n)` order.
///
/// `s_ν = Σ_{γ⊢n} χ^ν(γ)/z_γ · p_γ` and Γ⁻¹ is linear, so the shared per-γ
/// vector is `Γ⁻¹(p_γ)/z_γ` — where the route this replaced rebuilt it inside
/// `gamma_inverse(PowerSum::from_schur(s_ν))` once per ν rather than once per
/// γ: the p(n)² shape (`docs/record/kronecker.md`).
fn schur_to_st_degree<R: RatLike>(n: u32) -> Option<Vec<Vec<(Partition, i128)>>> {
    degree_rows(n, |g| {
        let mut pg: PowerSum<R> = PowerSum::zero();
        pg.add_term(g.clone(), g.div_by_z(&R::one()));
        gamma_inverse(&pg)
    })
}

/// Every row of one degree, from the per-γ power-sum image both directions
/// share the shape of: row(λ) `= Σ_{γ⊢n} χ^λ(γ) · per_gamma(γ)`, read in the
/// Schur basis.
///
/// The arithmetic is in ℤ, not ℚ. Each `per_gamma(γ)` — which carries `1/z_γ`
/// and its own denominators — is cleared to one denominator `D_γ` and
/// expanded into an integer vector `X_γ` over the Schur basis, which the
/// character expansion of `p_δ` permits by being integral. A row is then
/// `Σ_γ χ^λ(γ)·(L/D_γ)·X_γ` — fused integer multiply-adds over a flat index —
/// divided by `L = lcm_γ D_γ` at the end, exactly or not at all. A first
/// version assembled the rows in ℚ instead and *lost* to the per-λ route it
/// replaced: 22.7M `GuardedRat` map-insertions at degree 16 against these
/// same counts in ℤ (`docs/record/kronecker.md`).
///
/// `None` when anything leaves `R::Int` — over `i128` an intermediate past
/// the width, over `BigInt` never — or when a final division is not exact,
/// which over [`GuardedRat`]/`i128` means a wrapped intermediate and over
/// `BigRational` a bug; [`escalating`] tells those apart.
fn degree_rows<R: RatLike>(
    n: u32,
    per_gamma: impl Fn(&Partition) -> PowerSum<R>,
) -> Option<Vec<Vec<(Partition, i128)>>> {
    let parts = crate::memo::partitions_cached(n);
    let by_degree: Vec<_> = (0..=n).map(crate::memo::partitions_cached).collect();
    let offsets: Vec<usize> = by_degree
        .iter()
        .scan(0usize, |acc, p| {
            let o = *acc;
            *acc += p.len();
            Some(o)
        })
        .collect();
    let total = offsets[n as usize] + parts.len();

    // The per-γ image, cleared to one denominator and expanded over the Schur
    // basis as integers on the flat index.
    struct Cleared<I> {
        denom: I,
        terms: Vec<(u32, I)>,
    }
    let mut shared: Vec<Cleared<R::Int>> = Vec::with_capacity(parts.len());
    for g in parts.iter() {
        crate::interrupt::poll();
        let v = per_gamma(g);
        let mut denom = R::Int::one();
        for c in v.terms().values() {
            denom = denom.checked_lcm(&c.denominator())?;
        }
        let mut dense: Vec<R::Int> = vec![R::Int::zero(); total];
        for (delta, c) in v.terms() {
            let u = c
                .numerator()
                .checked_mul(&denom.div_exact(&c.denominator()))?;
            let d = delta.size() as usize;
            for (i, lam) in by_degree[d].iter().enumerate() {
                let chi = R::Int::character(lam, delta)?;
                if chi.is_zero() {
                    continue;
                }
                let slot = &mut dense[offsets[d] + i];
                *slot = slot.checked_add(&u.checked_mul(&chi)?)?;
            }
        }
        let terms = dense
            .into_iter()
            .enumerate()
            .filter(|(_, v)| !v.is_zero())
            .map(|(i, v)| (i as u32, v))
            .collect();
        shared.push(Cleared { denom, terms });
    }
    let mut l = R::Int::one();
    for c in &shared {
        l = l.checked_lcm(&c.denom)?;
    }

    let flat_partition = |idx: usize| {
        let d = offsets.partition_point(|&o| o <= idx) - 1;
        &by_degree[d][idx - offsets[d]]
    };
    let mut out = Vec::with_capacity(parts.len());
    for lam in parts.iter() {
        crate::interrupt::poll();
        let mut acc: Vec<R::Int> = vec![R::Int::zero(); total];
        for (g, cl) in parts.iter().zip(shared.iter()) {
            let chi = R::Int::character(lam, g)?;
            if chi.is_zero() {
                continue;
            }
            let scale = chi.checked_mul(&l.div_exact(&cl.denom))?;
            for (idx, x) in &cl.terms {
                let slot = &mut acc[*idx as usize];
                *slot = slot.checked_add(&scale.checked_mul(x)?)?;
            }
        }
        let mut row = Vec::new();
        for (idx, v) in acc.iter().enumerate() {
            if v.is_zero() {
                continue;
            }
            let r = v.checked_div_exact(&l)?.as_i128()?;
            row.push((flat_partition(idx).clone(), r));
        }
        out.push(row);
    }
    Some(out)
}

/// `s_ν` in the `s̃` basis, memoized — the coefficients `r_{νμ}` of OZ Thm
/// 1(2).
///
/// A miss computes and stores the **whole degree**, because the rows share
/// their expensive part ([`schur_to_st_degree`]) and the one caller converts
/// whole elements, which want most of the degree anyway.
fn schur_to_st_row(nu: &Partition) -> Arc<Vec<(Partition, i128)>> {
    schur_to_st_cached(nu, || {
        let n = nu.size();
        let rows = escalating(
            &format!("s → s̃ at degree {n}"),
            || schur_to_st_degree::<GuardedRat>(n),
            || {
                #[cfg(feature = "bignum")]
                {
                    schur_to_st_degree::<num_rational::BigRational>(n)
                }
                #[cfg(not(feature = "bignum"))]
                None
            },
        );
        let mut mine = None;
        for (v, row) in crate::memo::partitions_cached(n).iter().zip(rows) {
            if v == nu {
                mine = Some(row);
            } else {
                schur_to_st_cached(v, || row);
            }
        }
        mine.expect("partitions_cached(|ν|) lists every partition of |ν|")
    })
}

/// One whole column of reduced Kronecker coefficients, `s̃_λ · s̃_μ`, memoized.
///
/// The multiplication is a multiset union of power-sum indices; the two Γ's
/// either side are what cost anything.
fn reduced_kronecker_row(lambda: &Partition, mu: &Partition) -> Arc<Vec<(Partition, i128)>> {
    reduced_kronecker_cached(lambda, mu, || {
        fn run<R: RatLike>(
            lambda: &Partition,
            mu: &Partition,
            bold: fn(&Partition) -> PowerSum<R>,
        ) -> Option<Vec<(Partition, i128)>> {
            let prod = st_in_power_sum(lambda, bold).mul(&st_in_power_sum(mu, bold));
            integral_row(&gamma_inverse(&prod).to_schur())
        }
        escalating(
            &format!("s̃_{lambda} · s̃_{mu}"),
            || run(lambda, mu, bold_guarded),
            || {
                #[cfg(feature = "bignum")]
                {
                    run::<num_rational::BigRational>(lambda, mu, bold_p_in)
                }
                #[cfg(not(feature = "bignum"))]
                None
            },
        )
    })
}

// --- the public surface ------------------------------------------------------

/// Reach: in fixed width the row engine behind this completes degree 24 —
/// under twenty seconds, runtime-bound to there (`examples/bench_s2st.rs`) —
/// and refuses degree 26, two degrees before the `s → s̃` direction, because
/// `𝐩_γ` clears to larger integers than `Γ⁻¹(p_γ)`; under `bignum` the same
/// call escalates and answers (`docs/record/kronecker.md`).
impl<C: Ring> ToSchur<C> for St<C> {
    fn to_schur(&self) -> Schur<C> {
        let mut out = Schur::zero();
        for (lambda, c) in self.terms() {
            for (nu, k) in st_to_schur_row(lambda).iter() {
                out.add_term(nu.clone(), C::from_i128(*k).mul(c));
            }
        }
        out
    }
}

/// Reach: in fixed width the row engine behind this completes degree 26 —
/// about a minute, runtime-bound the whole way (`examples/bench_s2st.rs`) —
/// and refuses degree 28, where the cleared-denominator intermediates leave
/// `i128`; under `bignum` the same call escalates and answers
/// (`docs/record/kronecker.md`).
impl<C: Ring> FromSchur<C> for St<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        let mut out = St::zero();
        for (nu, c) in s.terms() {
            for (lambda, k) in schur_to_st_row(nu).iter() {
                out.add_term(lambda.clone(), C::from_i128(*k).mul(c));
            }
        }
        out
    }
}

impl<C: Ring> St<C> {
    /// The product `s̃_λ · s̃_μ`, whose structure constants are the reduced
    /// Kronecker coefficients (OZ Thm 7).
    ///
    /// Bilinear over one memoized column per (λ, μ), the same shape as
    /// [`Schur::mul_with`] over an LR backend — so a memoized column is shared
    /// by every element that mentions the pair, and the coefficient ring never
    /// enters the engine.
    ///
    /// # Panics
    ///
    /// Panics where [`reduced_kronecker_product`] does, whose columns this
    /// reads.
    pub fn mul(&self, other: &Self) -> Self {
        let mut out = Self::zero();
        for (lambda, cl) in self.terms() {
            for (mu, cm) in other.terms() {
                let scale = cl.mul(cm);
                for (nu, k) in reduced_kronecker_row(lambda, mu).iter() {
                    out.add_term(nu.clone(), C::from_i128(*k).mul(&scale));
                }
            }
        }
        out
    }
}

impl_product_ops!(St);

impl<C: Ring> SymAlgebra<C> for St<C> {
    fn times(&self, o: &Self) -> Self {
        self.mul(o)
    }
}

/// The reduced (stable) Kronecker product `s̃_λ · s̃_μ = Σ_ν ḡ^ν_{λμ} s̃_ν`.
///
/// The whole column at once, because that is the engine's unit of work.
/// `s̃_∅` is the unit, so an empty λ returns `s̃_μ`.
///
/// # Panics
///
/// Panics without the `bignum` feature, past the measured wall at `|λ|+|μ| =
/// 24`: `s̃_{(8,5)}·s̃_{(7,4)}` completes and `s̃_{(8,5)}·s̃_{(8,5)}` does not.
/// The wall is `z_γ` in the intermediate rationals, not the answers, which stay
/// under 20 bits — a fact about `i128`, and with `bignum` the same call
/// escalates and returns exactly (`docs/record/kronecker.md`).
pub fn reduced_kronecker_product<C: Ring>(lambda: &Partition, mu: &Partition) -> St<C> {
    let mut out = St::zero();
    for (nu, k) in reduced_kronecker_row(lambda, mu).iter() {
        out.add_term(nu.clone(), C::from_i128(*k));
    }
    out
}

/// A single reduced Kronecker coefficient `ḡ^ν_{λμ}`.
///
/// Returns zero for a ν the column does not mention.
///
/// Convenience over [`reduced_kronecker_product`], and honest about it: asking
/// for one coefficient costs what the whole column costs, exactly as
/// [`ops::kronecker`](crate::ops::kronecker) does for the unreduced case.
///
/// # Panics
///
/// Panics where [`reduced_kronecker_product`] does, whose column this reads.
pub fn reduced_kronecker<C: Ring>(lambda: &Partition, mu: &Partition, nu: &Partition) -> C {
    reduced_kronecker_row(lambda, mu)
        .iter()
        .find(|(p, _)| p == nu)
        .map(|(_, k)| C::from_i128(*k))
        .unwrap_or_else(C::zero)
}

// --- the induced trivial basis, and the second route ------------------------

/// Partitions γ ⊢ |λ| + k with γ/λ a horizontal strip.
///
/// The interlacing condition γ₁ ≥ λ₁ ≥ γ₂ ≥ λ₂ ≥ … is what "at most one cell
/// per column" comes to, and it bounds ℓ(γ) by ℓ(λ)+1.
fn horizontal_strips(lambda: &Partition, k: u32) -> Vec<Partition> {
    let l = lambda.parts();
    let mut out = Vec::new();
    let mut current: Vec<u32> = Vec::with_capacity(l.len() + 1);

    fn rec(i: usize, left: u32, l: &[u32], current: &mut Vec<u32>, out: &mut Vec<Partition>) {
        if i == l.len() + 1 {
            if left == 0 {
                out.push(Partition::new(current.clone()));
            }
            return;
        }
        // γ_i ranges over [λ_i, λ_{i−1}] (no upper bound for i = 0).
        let lo = if i < l.len() { l[i] } else { 0 };
        let hi = if i == 0 {
            lo + left
        } else {
            l[i - 1].min(lo + left)
        };
        for v in lo..=hi {
            current.push(v);
            rec(i + 1, left - (v - lo), l, current, out);
            current.pop();
        }
    }

    rec(0, k, l, &mut current, &mut out);
    out
}

/// The coefficient of `s̃_λ` in `h̃_μ` (OZ Eq 7).
///
/// The paper states this with *stable* Kostka numbers
/// `K_{(n−|λ|,λ)(n−|μ|,μ)}` for n ≥ 2|μ|, and then gives the n-free form used
/// here: sum the ordinary `K_{γμ}` over γ ⊢ |μ| with γ/λ a horizontal strip.
/// Same number, and no partition of 2|μ| is ever enumerated to get it.
fn ht_to_st_coeff(lambda: &Partition, mu: &Partition) -> u128 {
    if lambda.size() > mu.size() {
        return 0;
    }
    horizontal_strips(lambda, mu.size() - lambda.size())
        .iter()
        .map(|g| kostka(g, mu))
        .sum()
}

/// `h̃_μ` expanded in the `s̃` basis.
fn ht_to_st_row(mu: &Partition) -> Arc<Vec<(Partition, i128)>> {
    ht_to_st_cached(mu, || {
        let mut out = Vec::new();
        for size in 0..=mu.size() {
            for lambda in crate::memo::partitions_cached(size).iter() {
                let c = ht_to_st_coeff(lambda, mu);
                if c != 0 {
                    // A structure constant crossing into the signed ring, so it
                    // checks rather than proving: `ht_to_st_coeff` sums ordinary
                    // Kostka numbers, which have no a-priori `i128` bound here.
                    let c = i128::try_from(c).unwrap_or_else(|_| {
                        panic!("the h̃ → s̃ coefficient at ({lambda}, {mu}) does not fit i128")
                    });
                    out.push((lambda.clone(), c));
                }
            }
        }
        out
    })
}

/// Order on partitions in which the `h̃ → s̃` matrix is triangular with unit
/// diagonal: by size, then by **reverse** lexicographic order.
///
/// Both halves are forced. `ht_to_st_coeff` vanishes unless |λ| ≤ |μ|, and at
/// equal size it is the Kostka number `K_{λμ}`, which vanishes unless λ ⊵ μ —
/// and dominance refines to lex. So every off-diagonal entry sits strictly
/// earlier in this order than its column, which is what back substitution
/// needs.
fn triangular_key(p: &Partition) -> (u32, std::cmp::Reverse<Vec<u32>>) {
    (p.size(), std::cmp::Reverse(p.parts().to_vec()))
}

/// `s̃_λ` expanded in the `h̃` basis, by back substitution against
/// [`ht_to_st_row`].
fn st_to_ht_row(lambda: &Partition) -> Arc<Vec<(Partition, i128)>> {
    st_to_ht_cached(lambda, || {
        let mut rem: BTreeMap<Partition, i128> = BTreeMap::new();
        rem.insert(lambda.clone(), 1);
        let mut out: Vec<(Partition, i128)> = Vec::new();

        // One lookup yields both the pivot and its coefficient, so neither the
        // emptiness test nor the re-fetch can disagree with it.
        while let Some((pivot, c)) = rem
            .iter()
            .max_by_key(|(p, _)| triangular_key(p))
            .map(|(p, &c)| (p.clone(), c))
        {
            rem.remove(&pivot);
            if c == 0 {
                continue;
            }
            out.push((pivot.clone(), c));
            for (nu, k) in ht_to_st_row(&pivot).iter() {
                if *nu == pivot {
                    continue; // the unit diagonal, already consumed
                }
                *rem.entry(nu.clone()).or_insert(0) -= c * k;
            }
            rem.retain(|_, v| *v != 0);
        }
        out
    })
}

impl<C: Ring> ToSchur<C> for Ht<C> {
    fn to_schur(&self) -> Schur<C> {
        let mut st: St<C> = St::zero();
        for (mu, c) in self.terms() {
            for (lambda, k) in ht_to_st_row(mu).iter() {
                st.add_term(lambda.clone(), C::from_i128(*k).mul(c));
            }
        }
        st.to_schur()
    }
}

impl<C: Ring> FromSchur<C> for Ht<C> {
    fn from_schur(s: &Schur<C>) -> Self {
        let st: St<C> = St::from_schur(s);
        let mut out = Ht::zero();
        for (lambda, c) in st.terms() {
            for (mu, k) in st_to_ht_row(lambda).iter() {
                out.add_term(mu.clone(), C::from_i128(*k).mul(c));
            }
        }
        out
    }
}

/// How many matrices [`ht_product_terms`] will look at before giving up.
///
/// The enumeration is cheap exactly where the partitions are short — λ = μ =
/// (6,4) is a 2×2 free block, at most 1225 matrices — and hopeless where they
/// are long: λ = μ = (1¹⁰) is a 10×10 block with row sums 1, which is 11¹⁰.
/// This route is a cross-check, so refusing is a perfectly good answer.
const HT_PRODUCT_BUDGET: u64 = 4_000_000;

/// `h̃_λ · h̃_μ` by the matrix rule, or `None` if the enumeration is too large.
///
/// The terms come back in ascending [`Partition`] order. Every multiplicity is
/// positive.
///
/// **Derived rather than read**, and the derivation is one paragraph. `h̃_λ` is
/// the character of the permutation module `M^{(n−|λ|,λ)}`. A tensor product of
/// permutation modules is the permutation module on the product of the two
/// coset spaces; its orbits are the double cosets, indexed by non-negative
/// integer
/// matrices with row sums `(n−|λ|, λ₁, λ₂, …)` and column sums
/// `(n−|μ|, μ₁, μ₂, …)`; and the stabilizer of an orbit is the Young subgroup on
/// the entries. So
///
/// ```text
///     h̃_λ · h̃_μ = Σ_A h̃_{entries of A, minus the (0,0) corner}
/// ```
///
/// Only the corner grows with n, so dropping it leaves a finite sum that never
/// mentions n. Checked against Sage on 9 pairs before it was implemented,
/// including `ht[3,1]·ht[2,2]`.
pub fn ht_product_terms(lambda: &Partition, mu: &Partition) -> Option<Vec<(Partition, u128)>> {
    let rows = lambda.parts();
    let cols = mu.parts();
    let mut acc: BTreeMap<Partition, u128> = BTreeMap::new();
    let mut cap: Vec<u32> = cols.to_vec();
    let mut entries: Vec<u32> = Vec::new();
    let mut scratch: Vec<u32> = Vec::new();
    let mut budget = HT_PRODUCT_BUDGET;

    // Choose one row of the free block at a time; `cap` carries the column
    // capacity left, and `left` the row capacity left.
    #[allow(clippy::too_many_arguments)]
    fn row(
        i: usize,
        j: usize,
        left: u32,
        rows: &[u32],
        cap: &mut Vec<u32>,
        entries: &mut Vec<u32>,
        scratch: &mut Vec<u32>,
        acc: &mut BTreeMap<Partition, u128>,
        budget: &mut u64,
    ) -> bool {
        if *budget == 0 {
            return false;
        }
        if j == cap.len() {
            entries.push(left); // the row slack, A[i][0]
            let ok = block(i + 1, rows, cap, entries, scratch, acc, budget);
            entries.pop();
            return ok;
        }
        for v in 0..=left.min(cap[j]) {
            cap[j] -= v;
            entries.push(v);
            let ok = row(i, j + 1, left - v, rows, cap, entries, scratch, acc, budget);
            entries.pop();
            cap[j] += v;
            if !ok {
                return false;
            }
        }
        true
    }

    fn block(
        i: usize,
        rows: &[u32],
        cap: &mut Vec<u32>,
        entries: &mut Vec<u32>,
        scratch: &mut Vec<u32>,
        acc: &mut BTreeMap<Partition, u128>,
        budget: &mut u64,
    ) -> bool {
        if i == rows.len() {
            if *budget == 0 {
                return false;
            }
            *budget -= 1;
            // The column slacks A[0][j] complete the matrix.
            //
            // Built in a reused buffer, and sorted and stripped of zeros in
            // place, so the leaf allocates exactly once — for the key the map
            // has to own. It used to allocate twice, cloning `entries` and then
            // letting `Partition::new` collect a second vector out of the
            // filter, on every one of up to `HT_PRODUCT_BUDGET` leaves.
            scratch.clear();
            scratch.extend_from_slice(entries);
            scratch.extend_from_slice(cap);
            scratch.retain(|&x| x != 0);
            scratch.sort_unstable_by(|a, b| b.cmp(a));
            *acc.entry(Partition::from_sorted(scratch.clone()))
                .or_insert(0) += 1;
            return true;
        }
        row(i, 0, rows[i], rows, cap, entries, scratch, acc, budget)
    }

    if !block(
        0,
        rows,
        &mut cap,
        &mut entries,
        &mut scratch,
        &mut acc,
        &mut budget,
    ) {
        return None;
    }
    Some(acc.into_iter().collect())
}

impl<C: Ring> Ht<C> {
    /// The product in the `h̃` basis, by the matrix rule.
    ///
    /// # Panics
    ///
    /// Panics if the enumeration exceeds its budget. This is a capacity wall,
    /// not a violated precondition: [`ht_product_terms`] returns `None` on the
    /// same input, and a caller who needs to handle the case rather than die on
    /// it should go through that.
    pub fn mul(&self, other: &Self) -> Self {
        let mut out = Self::zero();
        for (lambda, cl) in self.terms() {
            for (mu, cm) in other.terms() {
                let scale = cl.mul(cm);
                let terms = ht_product_terms(lambda, mu)
                    .expect("ht product enumeration exceeded its budget");
                for (nu, k) in terms {
                    out.add_term(nu, C::from_u128(k).mul(&scale));
                }
            }
        }
        out
    }
}

impl_product_ops!(Ht);

impl<C: Ring> SymAlgebra<C> for Ht<C> {
    fn times(&self, o: &Self) -> Self {
        self.mul(o)
    }
}

/// `s̃_λ · s̃_μ` computed the other way: through the `h̃` basis and its matrix
/// rule, sharing no code with [`reduced_kronecker_product`].
///
/// `None` when the matrix enumeration would be too large (long partitions).
/// This exists to be disagreed with — it is the crate's standing pattern of
/// holding a fast engine to an independent one. Here it matters more than
/// usual: past `st[4,3]·st[4,3]` there is no third-party package left to ask
/// (`docs/record/kronecker.md` surveys them).
///
/// # Panics
///
/// Panics if an `h̃` product multiplicity exceeds `i128`. It counts double
/// cosets and is unbounded in principle. The narrowing therefore checks as it
/// crosses into the signed ring rather than being absorbed into the sum (R5).
/// The enumeration budget is the *other* limit and is not a panic — that is
/// the `None`.
pub fn reduced_kronecker_via_ht<C: Ring>(lambda: &Partition, mu: &Partition) -> Option<St<C>> {
    let mut acc: BTreeMap<Partition, i128> = BTreeMap::new();
    for (a, ca) in st_to_ht_row(lambda).iter() {
        for (b, cb) in st_to_ht_row(mu).iter() {
            for (nu, k) in ht_product_terms(a, b)? {
                // As above: `k` counts double cosets and is unbounded in
                // principle, so the narrowing is checked at the seam rather
                // than absorbed into the sum.
                let k = i128::try_from(k).unwrap_or_else(|_| {
                    panic!("the h̃ product multiplicity at {nu} does not fit i128")
                });
                *acc.entry(nu).or_insert(0) += ca * cb * k;
            }
        }
    }
    let mut out = St::zero();
    for (nu, c) in acc {
        if c == 0 {
            continue;
        }
        for (lam, k) in ht_to_st_row(&nu).iter() {
            out.add_term(lam.clone(), C::from_i128(c * k));
        }
    }
    Some(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sym::{Elementary, Homogeneous};

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

    fn st(v: &[u32]) -> St<i128> {
        St::monomial(part(v), 1)
    }

    /// The two rungs of each conversion ladder are one generic function over
    /// different widths; this holds them to the same rows on degrees both can
    /// reach, so the wide rungs are not untested paths met first at the wall
    /// (`docs/policies/failure.md`, "the wide pass is the same code").
    #[cfg(feature = "bignum")]
    #[test]
    fn the_wide_degree_passes_agree_with_the_fixed_ones() {
        for n in 0..=6u32 {
            let fixed = guarded(|| schur_to_st_degree::<GuardedRat>(n))
                .flatten()
                .expect("degree 6 is far inside the fixed width");
            let wide = schur_to_st_degree::<num_rational::BigRational>(n)
                .expect("BigRational cannot leave its width");
            assert_eq!(fixed, wide, "s → s̃ at degree {n}");

            let fixed = guarded(|| st_to_schur_degree::<GuardedRat>(n, bold_guarded))
                .flatten()
                .expect("degree 6 is far inside the fixed width");
            let wide = st_to_schur_degree::<num_rational::BigRational>(n, bold_p_in)
                .expect("BigRational cannot leave its width");
            assert_eq!(fixed, wide, "s̃ → s at degree {n}");
        }
    }

    /// OZ Thm 1(3): `s̃_{1^r} = Σ_{i=0}^{r} (−1)^i e_{r−i}`.
    ///
    /// Hand-checkable, and it pins the *embedding* rather than any structure
    /// constant — the paper uses exactly this as the initial condition that
    /// makes the basis unique, so getting it right is not implied by getting
    /// the product right.
    #[test]
    fn column_shapes_are_alternating_sums_of_elementaries() {
        for r in 1..=6u32 {
            let col = st(&vec![1; r as usize]);
            let e: Elementary<i128> = Elementary::from_schur(&col.to_schur());
            for i in 0..=r {
                let want = if i % 2 == 0 { 1 } else { -1 };
                assert_eq!(e.coeff(&part(&[r - i])), want, "e_{} in s̃_(1^{r})", r - i);
            }
            assert_eq!(e.terms().len(), r as usize + 1);
        }
    }

    /// `s̃_1 = s_1 − 1`, the smallest non-trivial case, and the one where the
    /// inhomogeneity first shows up.
    #[test]
    fn first_character_is_the_defect_of_the_trivial_one() {
        let s = st(&[1]).to_schur();
        assert_eq!(s.coeff(&part(&[1])), 1);
        assert_eq!(s.coeff(&Partition::default()), -1);
        assert_eq!(s.terms().len(), 2);
    }

    /// OZ Eq (20): `h_{21} = s̃_3 + s̃_{21} + 4s̃_2 + 3s̃_{11} + 7s̃_1 +
    /// 4s̃_∅`.
    ///
    /// Printed in the paper, so this is a check against a *published* value
    /// rather than against another routine in this crate.
    #[test]
    fn published_expansion_of_h_21() {
        let h: Homogeneous<i128> = Homogeneous::monomial(part(&[2, 1]), 1);
        let got: St<i128> = St::from_schur(&h.to_schur());
        for (p, want) in [
            (vec![3], 1),
            (vec![2, 1], 1),
            (vec![2], 4),
            (vec![1, 1], 3),
            (vec![1], 7),
            (vec![], 4),
        ] {
            assert_eq!(got.coeff(&part(&p)), want, "coefficient of s̃_{p:?}");
        }
        assert_eq!(got.terms().len(), 6);
    }

    /// OZ Eq (21): the decomposition of `V^{⊗4}` as an Sₙ-module, also printed
    /// in the paper.
    #[test]
    fn published_expansion_of_h_1111() {
        let h: Homogeneous<i128> = Homogeneous::monomial(part(&[1, 1, 1, 1]), 1);
        let got: St<i128> = St::from_schur(&h.to_schur());
        for (p, want) in [
            (vec![], 15),
            (vec![1], 37),
            (vec![1, 1], 31),
            (vec![1, 1, 1], 10),
            (vec![1, 1, 1, 1], 1),
            (vec![2], 31),
            (vec![2, 1], 20),
            (vec![2, 1, 1], 3),
            (vec![2, 2], 2),
            (vec![3], 10),
            (vec![3, 1], 3),
            (vec![4], 1),
        ] {
            assert_eq!(got.coeff(&part(&p)), want, "coefficient of s̃_{p:?}");
        }
        assert_eq!(got.terms().len(), 12);
    }

    /// The two transitions invert each other, on every partition up to size 8.
    #[test]
    fn st_and_schur_round_trip() {
        for n in 0..=8u32 {
            for lambda in crate::partition::partitions_of(n) {
                let x = St::<i128>::monomial(lambda.clone(), 1);
                let back: St<i128> = St::from_schur(&x.to_schur());
                assert_eq!(back, x, "round trip at {lambda}");
            }
        }
    }

    /// Same for the `h̃` basis, which goes through `s̃` in both directions.
    #[test]
    fn ht_and_schur_round_trip() {
        for n in 0..=6u32 {
            for lambda in crate::partition::partitions_of(n) {
                let x = Ht::<i128>::monomial(lambda.clone(), 1);
                let back: Ht<i128> = Ht::from_schur(&x.to_schur());
                assert_eq!(back, x, "round trip at {lambda}");
            }
        }
    }

    /// `ḡ^ν_{λμ} = c^ν_{λμ}` when |ν| = |λ| + |μ| — the top-degree part of the
    /// reduced Kronecker product is the Littlewood–Richardson rule.
    ///
    /// This ties the new engine to the oldest one in the crate, and it is the
    /// check that would catch a systematic misreading of the paper: the two
    /// computations have no step in common.
    #[test]
    fn top_degree_is_littlewood_richardson() {
        for lambda in crate::partition::partitions_of(4) {
            for mu in crate::partition::partitions_of(3) {
                let red: St<i128> = reduced_kronecker_product(&lambda, &mu);
                let sl: Schur<i128> = Schur::monomial(lambda.clone(), 1);
                let sm: Schur<i128> = Schur::monomial(mu.clone(), 1);
                let lr = sl.mul(&sm);
                for (nu, c) in lr.terms() {
                    assert_eq!(
                        red.coeff(nu),
                        *c,
                        "top degree of s̃_{lambda} · s̃_{mu} at {nu}"
                    );
                }
            }
        }
    }

    /// The product agrees with the independent `h̃`-matrix route.
    #[test]
    fn two_product_routes_agree() {
        for lambda in crate::partition::partitions_of(3) {
            for mu in crate::partition::partitions_of(3) {
                let a: St<i128> = reduced_kronecker_product(&lambda, &mu);
                let b: St<i128> =
                    reduced_kronecker_via_ht(&lambda, &mu).expect("small enough to enumerate");
                assert_eq!(a, b, "routes disagree on s̃_{lambda} · s̃_{mu}");
            }
        }
    }

    /// `s̃_∅ = 1` is the unit, and the product is commutative.
    #[test]
    fn product_has_a_unit_and_commutes() {
        let a = st(&[2, 1]);
        let b = st(&[2]).add(&st(&[1, 1]));
        assert_eq!(a.mul(&St::unit()), a);
        assert_eq!(a.mul(&b), b.mul(&a));
    }

    /// Associativity, which is where a wrong Γ⁻¹ would show up even if every
    /// individual product looked plausible.
    #[test]
    fn product_is_associative() {
        let a = st(&[2]);
        let b = st(&[1, 1]);
        let c = st(&[2, 1]);
        assert_eq!(a.mul(&b).mul(&c), a.mul(&b.mul(&c)));
    }

    /// The product matches multiplying the two elements as ordinary symmetric
    /// functions — i.e. OZ Thm 7 really is a statement about the outer product,
    /// and the power-sum engine computes that and not something else.
    #[test]
    fn product_agrees_with_the_schur_route() {
        for lambda in crate::partition::partitions_of(3) {
            for mu in crate::partition::partitions_of(2) {
                let fast: St<i128> = reduced_kronecker_product(&lambda, &mu);
                let a: St<i128> = St::monomial(lambda.clone(), 1);
                let b: St<i128> = St::monomial(mu.clone(), 1);
                let slow: St<i128> = St::from_schur(&a.to_schur().mul(&b.to_schur()));
                assert_eq!(fast, slow, "s̃_{lambda} · s̃_{mu}");
            }
        }
    }

    /// Reduced Kronecker coefficients are the *stable* value of the ordinary
    /// ones: `ḡ^ν_{λμ} = g((n−|λ|,λ), (n−|μ|,μ), (n−|ν|,ν))` for n large.
    ///
    /// The only test that reaches the existing Kronecker implementation, and so
    /// the only one that could catch both of them being wrong together — which
    /// it cannot, because they share nothing but `Partition`.
    #[test]
    fn agrees_with_the_ordinary_kronecker_once_stable() {
        use crate::coeff::Rational;
        let lambda = part(&[2]);
        let mu = part(&[1, 1]);
        let red: St<i128> = reduced_kronecker_product(&lambda, &mu);
        let n = 9u32; // ≥ 2(|λ| + |μ|), comfortably inside stability
        let big = |p: &Partition| {
            let mut v = vec![n - p.size()];
            v.extend_from_slice(p.parts());
            Partition::new(v)
        };
        for nu in crate::partition::partitions_of(3) {
            let g: Rational = crate::ops::kronecker(&big(&lambda), &big(&mu), &big(&nu));
            assert_eq!(Rational::from_int(red.coeff(&nu)), g, "ḡ vs g at ν = {nu}");
        }
    }
}