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
//! Symmetric functions as **real types**, one per basis, unified by a trait.
//!
//! This is the deliberate departure from Symmetrica's single untyped `OP`
//! object (and from a single tagged `enum`): `Schur<C>`, `PowerSum<C>`, and
//! `Monomial<C>` are *distinct types*. You cannot add a Schur element to a
//! power-sum element, or feed one into the other's multiplication, because the
//! partitions mean different things in different bases and the compiler now
//! enforces that. Multiplication is basis-specific and dispatched statically:
//! `Schur::mul` goes through the Littlewood–Richardson backend, while
//! `PowerSum::mul` is a trivial multiset union — different rules, chosen at
//! compile time, no runtime tag.
//!
//! The shared *linear* structure (add, scale, coefficients, degree) lives on the
//! [`SymFn`] trait so it is written once and reused by every basis.
//!
//! ## Operators
//!
//! Every basis type implements the `core::ops` traits over its own methods:
//! `+`, `-` and unary `-` for every basis, `*` between two elements where the
//! basis has a product, `*` by a coefficient on the right, and the `+=`, `-=`
//! and `*=` forms. Each binary operator accepts either operand by value or by
//! reference, so `&a * &b` keeps both operands and `a * b` consumes both. The
//! coefficient stands on the right only, `f * c`; `c * f` would need an impl
//! on the coefficient type, which the orphan rules forbid for a type
//! parameter. The same operators exist on [`Schubert`](crate::schubert::Schubert)
//! and, without a product, on [`SymTensor`](crate::hopf::SymTensor).
//!
//! The named methods stay, and generic code bounded on [`SymFn`] uses them,
//! because the trait itself carries no operator bounds. Bringing
//! `core::ops::{Add, Sub, Mul, Neg}` into scope changes what `a.mul(&b)`
//! resolves to: the operator trait's method takes `self` by value, is found
//! before the inherent `&self` method, and moves `a`. Write the operator, or
//! leave the trait unimported.
//!
//! ```
//! use symfn::{Partition, Schur, SymFn};
//! let s2: Schur<i64> = Schur::monomial(Partition::new([2]), 1);
//! let s1: Schur<i64> = Schur::monomial(Partition::new([1]), 1);
//! // s_2 · s_1 = s_3 + s_{21}
//! let prod = &s2 * &s1;
//! assert_eq!(prod.coeff(&Partition::new([3])), 1);
//! assert_eq!(prod.coeff(&Partition::new([2, 1])), 1);
//! // 2·s_3 − (s_3 + s_{21}) = s_3 − s_{21}
//! let s3: Schur<i64> = Schur::monomial(Partition::new([3]), 1);
//! let diff = &s3 * 2 - &prod;
//! assert_eq!(diff.coeff(&Partition::new([3])), 1);
//! assert_eq!(diff.coeff(&Partition::new([2, 1])), -1);
//! assert_eq!(-&diff + &diff, Schur::zero());
//! ```

use crate::coeff::Ring;
use crate::lr::LrBackend;
use crate::partition::Partition;
use crate::strip_lr::AutoLr;
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;

/// The linear structure common to every basis of the ring of symmetric
/// functions: a finite formal `C`-combination of partitions. `BTreeMap` keeps a
/// deterministic term order, so display and tests see the same sequence every
/// run.
///
/// The operators `+`, `-` and `*` are implemented on each concrete basis type,
/// not on this trait; the module documentation lists them. Code generic over
/// `SymFn` uses the methods below.
pub trait SymFn<C: Ring>: Sized {
    /// Basis symbol used when printing (`s`, `p`, `m`, `st`, `ht`, …).
    const SYMBOL: &'static str;

    /// The terms, keyed by partition. Explicit zeros are never stored, so the
    /// map is empty exactly when the element is.
    fn terms(&self) -> &BTreeMap<Partition, C>;
    /// The terms, mutably. Inserting a zero coefficient through this breaks the
    /// invariant every other method reads — [`add_term`](Self::add_term) is the
    /// accumulating form that maintains it.
    fn terms_mut(&mut self) -> &mut BTreeMap<Partition, C>;
    /// Wrap a term map that is already free of explicit zeros.
    fn from_terms(terms: BTreeMap<Partition, C>) -> Self;

    /// The additive identity 0.
    fn zero() -> Self {
        Self::from_terms(BTreeMap::new())
    }

    /// A single basis element with coefficient `c` (dropped if `c` is zero).
    fn monomial(p: Partition, c: C) -> Self {
        let mut t = BTreeMap::new();
        if !c.is_zero() {
            t.insert(p, c);
        }
        Self::from_terms(t)
    }

    /// Coefficient of a given partition (zero if absent).
    fn coeff(&self, p: &Partition) -> C {
        self.terms().get(p).cloned().unwrap_or_else(C::zero)
    }

    /// Whether this is 0.
    fn is_zero(&self) -> bool {
        self.terms().is_empty()
    }

    /// The degree |λ| of the top term, or `None` for 0.
    fn degree(&self) -> Option<u32> {
        self.terms().keys().map(Partition::size).max()
    }

    /// `self += c · [p]`, keeping the map free of explicit zeros.
    fn add_term(&mut self, p: Partition, c: C) {
        if c.is_zero() {
            return;
        }
        // One descent, and the key is moved, never copied: the entry removes
        // itself when the sum cancels.
        match self.terms_mut().entry(p) {
            Entry::Vacant(e) => {
                e.insert(c);
            }
            Entry::Occupied(mut e) => {
                e.get_mut().add_assign(&c);
                if e.get().is_zero() {
                    e.remove();
                }
            }
        }
    }

    /// Formal sum `self + other`.
    fn add(&self, other: &Self) -> Self {
        let mut out = Self::from_terms(self.terms().clone());
        for (p, c) in other.terms() {
            out.add_term(p.clone(), c.clone());
        }
        out
    }

    /// Scalar multiple `c · self`.
    fn scale(&self, c: &C) -> Self {
        let mut t = BTreeMap::new();
        if !c.is_zero() {
            for (p, cc) in self.terms() {
                let v = cc.mul(c);
                if !v.is_zero() {
                    t.insert(p.clone(), v);
                }
            }
        }
        Self::from_terms(t)
    }

    /// Additive inverse −self.
    fn neg(&self) -> Self {
        self.scale(&C::from_i64(-1))
    }

    /// Difference self − other.
    fn sub(&self, other: &Self) -> Self {
        self.add(&other.neg())
    }

    /// Human-readable form, e.g. `s[2] + s[1,1]` or `2*s[3,2,1]`.
    fn format(&self) -> String {
        if self.is_zero() {
            return "0".to_string();
        }
        let one = C::one();
        let mut out = Vec::new();
        for (p, c) in self.terms() {
            let prefix = if *c == one {
                String::new()
            } else {
                format!("{c:?}*")
            };
            out.push(format!("{prefix}{}{p}", Self::SYMBOL));
        }
        out.join(" + ")
    }
}

/// The in-place arithmetic the operator impls are written over.
///
/// One implementation per element type: `basis!` writes one over the [`SymFn`]
/// methods for every basis, and `Schubert` and `SymTensor` write their own. A
/// blanket impl over `SymFn` is ruled out by coherence, since a downstream
/// crate may implement `SymFn<R>` for a type here over its own ring `R`. Every
/// method keeps the term map free of explicit zeros.
pub(crate) trait InPlaceArith<C: Ring>: Sized {
    /// `self += other`, copying the terms of `other`.
    fn add_from(&mut self, other: &Self);
    /// `self += other`, moving the terms of `other` rather than copying them.
    fn add_owned(&mut self, other: Self);
    /// `self -= other`, copying the terms of `other`.
    fn sub_from(&mut self, other: &Self);
    /// `self = -self`.
    fn negate(&mut self);
    /// `self = c · self`.
    fn scale_by(&mut self, c: &C);
}

/// The linear `core::ops` impls for an element type, written over its
/// [`InPlaceArith`]: `+`, `-`, unary `-`, `*` by a coefficient on the right,
/// and `+=`, `-=`, `*=` by a coefficient. Every binary form takes either
/// operand owned or borrowed; the owned forms reuse an operand's map.
macro_rules! impl_linear_ops {
    ($name:ident) => {
        impl<C: $crate::coeff::Ring> core::ops::Add<&$name<C>> for $name<C> {
            type Output = $name<C>;
            fn add(mut self, rhs: &$name<C>) -> $name<C> {
                $crate::sym::InPlaceArith::add_from(&mut self, rhs);
                self
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Add<$name<C>> for $name<C> {
            type Output = $name<C>;
            fn add(mut self, rhs: $name<C>) -> $name<C> {
                $crate::sym::InPlaceArith::add_owned(&mut self, rhs);
                self
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Add<&$name<C>> for &$name<C> {
            type Output = $name<C>;
            fn add(self, rhs: &$name<C>) -> $name<C> {
                self.clone() + rhs
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Add<$name<C>> for &$name<C> {
            type Output = $name<C>;
            fn add(self, rhs: $name<C>) -> $name<C> {
                rhs + self
            }
        }

        impl<C: $crate::coeff::Ring> core::ops::Sub<&$name<C>> for $name<C> {
            type Output = $name<C>;
            fn sub(mut self, rhs: &$name<C>) -> $name<C> {
                $crate::sym::InPlaceArith::sub_from(&mut self, rhs);
                self
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Sub<$name<C>> for $name<C> {
            type Output = $name<C>;
            fn sub(mut self, mut rhs: $name<C>) -> $name<C> {
                $crate::sym::InPlaceArith::negate(&mut rhs);
                $crate::sym::InPlaceArith::add_owned(&mut self, rhs);
                self
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Sub<&$name<C>> for &$name<C> {
            type Output = $name<C>;
            fn sub(self, rhs: &$name<C>) -> $name<C> {
                self.clone() - rhs
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Sub<$name<C>> for &$name<C> {
            type Output = $name<C>;
            fn sub(self, mut rhs: $name<C>) -> $name<C> {
                $crate::sym::InPlaceArith::negate(&mut rhs);
                $crate::sym::InPlaceArith::add_from(&mut rhs, self);
                rhs
            }
        }

        impl<C: $crate::coeff::Ring> core::ops::Neg for $name<C> {
            type Output = $name<C>;
            fn neg(mut self) -> $name<C> {
                $crate::sym::InPlaceArith::negate(&mut self);
                self
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Neg for &$name<C> {
            type Output = $name<C>;
            fn neg(self) -> $name<C> {
                -self.clone()
            }
        }

        impl<C: $crate::coeff::Ring> core::ops::Mul<&C> for $name<C> {
            type Output = $name<C>;
            fn mul(mut self, rhs: &C) -> $name<C> {
                $crate::sym::InPlaceArith::scale_by(&mut self, rhs);
                self
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Mul<C> for $name<C> {
            type Output = $name<C>;
            fn mul(mut self, rhs: C) -> $name<C> {
                $crate::sym::InPlaceArith::scale_by(&mut self, &rhs);
                self
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Mul<&C> for &$name<C> {
            type Output = $name<C>;
            fn mul(self, rhs: &C) -> $name<C> {
                self.clone() * rhs
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Mul<C> for &$name<C> {
            type Output = $name<C>;
            fn mul(self, rhs: C) -> $name<C> {
                self.clone() * &rhs
            }
        }

        impl<C: $crate::coeff::Ring> core::ops::AddAssign<&$name<C>> for $name<C> {
            fn add_assign(&mut self, rhs: &$name<C>) {
                $crate::sym::InPlaceArith::add_from(self, rhs);
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::AddAssign<$name<C>> for $name<C> {
            fn add_assign(&mut self, rhs: $name<C>) {
                $crate::sym::InPlaceArith::add_owned(self, rhs);
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::SubAssign<&$name<C>> for $name<C> {
            fn sub_assign(&mut self, rhs: &$name<C>) {
                $crate::sym::InPlaceArith::sub_from(self, rhs);
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::SubAssign<$name<C>> for $name<C> {
            fn sub_assign(&mut self, mut rhs: $name<C>) {
                $crate::sym::InPlaceArith::negate(&mut rhs);
                $crate::sym::InPlaceArith::add_owned(self, rhs);
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::MulAssign<&C> for $name<C> {
            fn mul_assign(&mut self, rhs: &C) {
                $crate::sym::InPlaceArith::scale_by(self, rhs);
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::MulAssign<C> for $name<C> {
            fn mul_assign(&mut self, rhs: C) {
                $crate::sym::InPlaceArith::scale_by(self, &rhs);
            }
        }
    };
}

/// The product `core::ops` impls for an element type with an inherent
/// `mul(&self, &Self) -> Self`: `*` between two elements, with either operand
/// owned or borrowed, and `*=`. The path `<$name<C>>::mul` resolves to the
/// inherent method, which takes precedence over the trait methods of the same
/// name.
macro_rules! impl_product_ops {
    ($name:ident) => {
        impl<C: $crate::coeff::Ring> core::ops::Mul<&$name<C>> for &$name<C> {
            type Output = $name<C>;
            fn mul(self, rhs: &$name<C>) -> $name<C> {
                <$name<C>>::mul(self, rhs)
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Mul<$name<C>> for &$name<C> {
            type Output = $name<C>;
            fn mul(self, rhs: $name<C>) -> $name<C> {
                <$name<C>>::mul(self, &rhs)
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Mul<&$name<C>> for $name<C> {
            type Output = $name<C>;
            fn mul(self, rhs: &$name<C>) -> $name<C> {
                <$name<C>>::mul(&self, rhs)
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::Mul<$name<C>> for $name<C> {
            type Output = $name<C>;
            fn mul(self, rhs: $name<C>) -> $name<C> {
                <$name<C>>::mul(&self, &rhs)
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::MulAssign<&$name<C>> for $name<C> {
            fn mul_assign(&mut self, rhs: &$name<C>) {
                *self = <$name<C>>::mul(self, rhs);
            }
        }
        impl<C: $crate::coeff::Ring> core::ops::MulAssign<$name<C>> for $name<C> {
            fn mul_assign(&mut self, rhs: $name<C>) {
                *self = <$name<C>>::mul(self, &rhs);
            }
        }
    };
}

pub(crate) use impl_linear_ops;
pub(crate) use impl_product_ops;

/// Define a basis newtype `$name` (symbol `$sym`) plus its `SymFn`, `Display`
/// and linear-operator impls. Keeps the per-basis boilerplate in one place.
macro_rules! basis {
    ($(#[$m:meta])* $name:ident, $sym:literal) => {
        $(#[$m])*
        #[derive(Clone, PartialEq, Eq, Debug)]
        pub struct $name<C: Ring>(BTreeMap<Partition, C>);

        impl<C: Ring> SymFn<C> for $name<C> {
            const SYMBOL: &'static str = $sym;
            fn terms(&self) -> &BTreeMap<Partition, C> { &self.0 }
            fn terms_mut(&mut self) -> &mut BTreeMap<Partition, C> { &mut self.0 }
            fn from_terms(terms: BTreeMap<Partition, C>) -> Self { $name(terms) }
        }

        impl<C: Ring> InPlaceArith<C> for $name<C> {
            fn add_from(&mut self, other: &Self) {
                for (p, c) in other.terms() {
                    self.add_term(p.clone(), c.clone());
                }
            }

            fn add_owned(&mut self, mut other: Self) {
                // Addition commutes, so the side with more terms keeps its map and
                // the other side's keys move into it, one descent each and no copy.
                if self.terms().len() < other.terms().len() {
                    std::mem::swap(self, &mut other);
                }
                for (p, c) in std::mem::take(other.terms_mut()) {
                    self.add_term(p, c);
                }
            }

            fn sub_from(&mut self, other: &Self) {
                for (p, c) in other.terms() {
                    self.add_term(p.clone(), c.neg());
                }
            }

            fn negate(&mut self) {
                // -c is zero only when c is, so no term can cancel here.
                for c in self.terms_mut().values_mut() {
                    *c = c.neg();
                }
            }

            fn scale_by(&mut self, c: &C) {
                let terms = self.terms_mut();
                if c.is_zero() {
                    terms.clear();
                    return;
                }
                for v in terms.values_mut() {
                    *v = v.mul(c);
                }
                // A ring with zero divisors can send a nonzero product to zero.
                terms.retain(|_, v| !v.is_zero());
            }
        }

        impl_linear_ops!($name);

        impl<C: Ring> core::fmt::Display for $name<C> {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_str(&self.format())
            }
        }
    };
}

basis!(
    /// Symmetric functions in the **Schur** basis {s_λ}.
    Schur, "s"
);
basis!(
    /// Symmetric functions in the **power-sum** basis {p_λ}.
    PowerSum, "p"
);
basis!(
    /// Symmetric functions in the **monomial** basis {m_λ}.
    Monomial, "m"
);
basis!(
    /// Symmetric functions in the **elementary** basis {e_λ}.
    Elementary, "e"
);
basis!(
    /// Symmetric functions in the **complete homogeneous** basis {h_λ}.
    Homogeneous, "h"
);
basis!(
    /// Symmetric functions in the **forgotten** basis {f_λ}, defined by
    /// f_λ = ω(m_λ).
    ///
    /// This is the sixth and last of Macdonald's classical bases (I.2), and the
    /// only one with no independent combinatorial description — it is *defined*
    /// as the image of the monomial basis under ω, which is where the name comes
    /// from. Because ω is an involutive algebra automorphism, {f_λ} is a basis
    /// the moment {m_λ} is, and every conversion involving it is a conversion
    /// involving m with an ω on one side; see `convert`.
    ///
    /// Note it is deliberately **not** a [`SymAlgebra`]: unlike p, e, and h it is
    /// not multiplicative, so f_μ · f_ν is not f_{μ ∪ ν} and there is no
    /// index-concatenation product to expose.
    Forgotten, "f"
);
basis!(
    /// Symmetric functions in the Orellana–Zabrocki **irreducible character**
    /// basis {s̃_λ} — the `st` basis.
    ///
    /// `s̃_λ` is the unique symmetric function whose evaluation at the
    /// eigenvalues of a permutation matrix of cycle type γ ⊢ n is the *symmetric
    /// group* character `χ^{(n−|λ|,λ)}(γ)`, for every n ≥ |λ| + λ₁ (OZ Thm 1).
    /// Schur functions are the characters of GLₙ; these are the characters of
    /// Sₙ, living in the same ring. The long first row is implicit, which is why
    /// λ indexes a shape of *any* large size.
    ///
    /// Two consequences shape the type. It is **inhomogeneous** — `s̃_λ` has
    /// components in every degree from 0 to |λ| — which is why nothing in
    /// [`SymFn`] may assume a single degree; [`SymFn::degree`] returning the max
    /// over terms is already the right answer. And its structure constants are
    /// the **reduced (stable) Kronecker coefficients** (OZ Thm 7), so an
    /// ordinary product in this basis computes them:
    /// [`St::mul`](crate::character_basis) is the reduced-Kronecker engine.
    /// See `character_basis` for both.
    St, "st"
);
basis!(
    /// Symmetric functions in the Orellana–Zabrocki **induced trivial
    /// character** basis {h̃_λ} — the `ht` basis.
    ///
    /// `h̃_λ` evaluates to the character of the trivial representation induced
    /// from a Young subgroup, i.e. of the permutation module `M^{(n−|λ|,λ)}`
    /// (OZ Def 4). It is to [`St`] what [`Homogeneous`] is to [`Schur`], and it
    /// is kept for the same reason: the transition between the two is a Kostka
    /// matrix, and its own product is a sum over integer matrices. That is an
    /// independent second route to the reduced Kronecker coefficients. It is
    /// how the first one gets checked at sizes no other package can reach;
    /// `docs/record/oracles-and-comparisons.md` surveys the incumbents.
    Ht, "ht"
);

/// `map[p] += c` for a key the caller only borrows, keeping the map free of
/// explicit zeros.
///
/// The key is copied only when the term is new. Landing on an existing term
/// costs one descent and no allocation; a new term costs a second descent for
/// the insert. That is the right trade where most terms land on partitions
/// already present, which is what a product with many pairs of terms does
/// (`examples/bench_schur_mul`; the measurement is in
/// `docs/record/littlewood-richardson.md`).
pub(crate) fn add_at<C: Ring>(map: &mut BTreeMap<Partition, C>, p: &Partition, c: C) {
    if c.is_zero() {
        return;
    }
    if let Some(e) = map.get_mut(p) {
        e.add_assign(&c);
        if e.is_zero() {
            map.remove(p);
        }
    } else {
        map.insert(p.clone(), c);
    }
}

/// The terms of `f` grouped by degree, ascending.
///
/// The transitions into a parametric basis run one degree at a time — each
/// needs that degree's whole table — while their arguments are ordinary
/// elements and may mix degrees freely.
pub(crate) fn by_degree<C: Ring, S: SymFn<C>>(f: &S) -> BTreeMap<u32, Vec<(&Partition, &C)>> {
    let mut groups: BTreeMap<u32, Vec<(&Partition, &C)>> = BTreeMap::new();
    for (mu, c) in f.terms() {
        groups.entry(mu.size()).or_default().push((mu, c));
    }
    groups
}

/// The product shared by every *multiplicative* basis: since p_λ, e_λ, h_λ are
/// each defined as a product of one-part generators, x_λ · x_μ = x_{λ ∪ μ} (the
/// multiset union of parts). One implementation, reused by p, e, and h.
fn multiplicative_product<C: Ring, S: SymFn<C>>(a: &S, b: &S) -> S {
    let mut out = S::zero();
    for (mu, cmu) in a.terms() {
        crate::interrupt::poll();
        for (nu, cnu) in b.terms() {
            let mut parts = mu.parts().to_vec();
            parts.extend_from_slice(nu.parts());
            out.add_term(Partition::new(parts), cmu.mul(cnu));
        }
    }
    out
}

impl<C: Ring> Schur<C> {
    /// Product in the Schur basis via an explicit LR backend.
    ///
    /// Structure constants arrive as `u128` and are injected through
    /// [`Ring::from_u128`], so a bignum coefficient type carries them exactly;
    /// only fixed-width types lose range, and that is inherent to them.
    ///
    /// Each pair of terms reads the backend's expansion in place
    /// ([`LrBackend::schur_product_shared`]) and copies a partition once, into
    /// the result — the memoized expansion is never duplicated whole. The
    /// first pair's terms, already sorted and distinct, build the result in
    /// one pass; later pairs accumulate term by term.
    pub fn mul_with<B: LrBackend>(&self, other: &Self, backend: &B) -> Self {
        let mut out = BTreeMap::new();
        for (mu, cmu) in self.terms() {
            for (nu, cnu) in other.terms() {
                crate::interrupt::poll();
                let cprod = cmu.mul(cnu);
                let product = backend.schur_product_shared(mu, nu);
                let terms = product.iter().filter_map(|(lambda, k)| {
                    let c = C::from_u128(*k).mul(&cprod);
                    (!c.is_zero()).then_some((lambda, c))
                });
                if out.is_empty() {
                    // Sorted by λ with no repeats, so the map is built in one
                    // pass instead of one descent per term. The vector is
                    // sized first: `BTreeMap::from_iter` takes a vector's
                    // buffer as it is, where collecting an iterator of
                    // unknown length would grow one by doubling.
                    let mut sorted = Vec::with_capacity(product.len());
                    sorted.extend(terms.map(|(lambda, c)| (lambda.clone(), c)));
                    out = sorted.into_iter().collect();
                } else {
                    for (lambda, c) in terms {
                        add_at(&mut out, lambda, c);
                    }
                }
            }
        }
        Schur(out)
    }

    /// Product in the Schur basis using the default backend,
    /// [`crate::strip_lr::AutoLr`] — currently a single traversal of the
    /// product's skew shape, binned by content.
    /// `NaiveLr` remains available as the reference oracle.
    pub fn mul(&self, other: &Self) -> Self {
        self.mul_with(other, &AutoLr)
    }
}

impl<C: Ring> PowerSum<C> {
    /// Product in the power-sum basis: p_μ · p_ν = p_{μ ∪ ν}.
    pub fn mul(&self, other: &Self) -> Self {
        multiplicative_product(self, other)
    }
}

impl<C: Ring> Elementary<C> {
    /// Product in the elementary basis: e_μ · e_ν = e_{μ ∪ ν}.
    pub fn mul(&self, other: &Self) -> Self {
        multiplicative_product(self, other)
    }
}

impl<C: Ring> Homogeneous<C> {
    /// Product in the complete-homogeneous basis: h_μ · h_ν = h_{μ ∪ ν}.
    pub fn mul(&self, other: &Self) -> Self {
        multiplicative_product(self, other)
    }
}

impl<C: Ring> Monomial<C> {
    /// Product in the monomial basis: `m_μ · m_ν = Σ_λ c_λ m_λ`, where `c_λ` is
    /// the number of ways to write the exponent vector of λ as `α + β` with α a
    /// distinct rearrangement of μ and β one of ν.
    ///
    /// Not a multiset union — that rule belongs to the *multiplicative* bases
    /// `p`, `e`, `h`, and `m` is not one of them: `m_1 · m_1 = 2·m_{11} + m_2`,
    /// where a union would give `m_{11}` alone. The coefficients are
    /// non-negative but not always 0 or 1, which is the fact the doctest pins.
    ///
    /// Cost is bounded by the pairs of rearrangements the recursion visits,
    /// which is far below `R(μ)·R(ν)`. The slots are chosen jointly and the
    /// weakly-decreasing constraint prunes on the way down, so a pair whose sum
    /// is not a partition is abandoned at the first slot that proves it rather
    /// than after both rearrangements are complete.
    ///
    /// This is the operation behind Sage's product in the `m` basis, whose
    /// backend is Symmetrica's `mult_monomial_monomial`.
    ///
    /// # Examples
    ///
    /// ```
    /// use symfn::{Monomial, Partition, SymFn};
    /// let m1: Monomial<i64> = Monomial::monomial(Partition::new([1]), 1);
    /// let sq = m1.mul(&m1);
    /// assert_eq!(sq.coeff(&Partition::new([1, 1])), 2);
    /// assert_eq!(sq.coeff(&Partition::new([2])), 1);
    /// ```
    pub fn mul(&self, other: &Self) -> Self {
        let mut out = Self::zero();
        for (mu, cmu) in self.terms() {
            for (nu, cnu) in other.terms() {
                let c = cmu.mul(cnu);
                if c.is_zero() {
                    continue;
                }
                overlays(mu, nu, &mut |lambda: &[u32]| {
                    out.add_term(Partition::new(lambda.iter().copied()), c.clone());
                });
            }
        }
        out
    }
}

impl_product_ops!(Schur);
impl_product_ops!(PowerSum);
impl_product_ops!(Elementary);
impl_product_ops!(Homogeneous);
impl_product_ops!(Monomial);

/// Every λ obtained as the slotwise sum of a distinct rearrangement of μ and one
/// of ν, emitted once per *pair* — so the multiplicity with which λ arrives is
/// the structure constant.
///
/// `ℓ(μ) + ℓ(ν)` slots are enough and never too few: a nonzero slot needs a part
/// from at least one side, so no λ in the product has more rows than that. The
/// bound matters because the answer is read off a *fixed* exponent vector — the
/// weakly decreasing one — and that is only legitimate while every λ that
/// occurs still fits in the alphabet.
fn overlays(mu: &Partition, nu: &Partition, emit: &mut impl FnMut(&[u32])) {
    let n = mu.len() + nu.len();
    let mut a = crate::eval::multiplicities(mu);
    let mut b = crate::eval::multiplicities(nu);
    let mut sum = vec![0u32; n];
    walk(
        &mut sum,
        0,
        u32::MAX,
        &mut a,
        &mut b,
        mu.len(),
        nu.len(),
        emit,
    );
}

/// Fill slot `slot` with `α_slot + β_slot`, keeping the running vector weakly
/// decreasing, and recurse.
#[allow(clippy::too_many_arguments)]
fn walk(
    sum: &mut [u32],
    slot: usize,
    prev: u32,
    a: &mut [(u32, u32)],
    b: &mut [(u32, u32)],
    left_a: usize,
    left_b: usize,
    emit: &mut impl FnMut(&[u32]),
) {
    if left_a == 0 && left_b == 0 {
        // Every later slot would be 0, so the vector ends here.
        emit(&sum[..slot]);
        return;
    }
    // Each side still needs a slot per unplaced part.
    if sum.len() - slot < left_a.max(left_b) {
        return;
    }
    // Index `len` means "this side contributes nothing to this slot". Both
    // sides declining would make the slot 0 with parts still to place, and a 0
    // forces every later slot to 0 — so that branch can never complete and is
    // skipped rather than explored and abandoned.
    let (na, nb) = (a.len(), b.len());
    for i in 0..=na {
        let va = if i == na {
            0
        } else if a[i].1 == 0 {
            continue;
        } else {
            a[i].0
        };
        for j in 0..=nb {
            let vb = if j == nb {
                0
            } else if b[j].1 == 0 {
                continue;
            } else {
                b[j].0
            };
            if i == na && j == nb {
                continue;
            }
            if va + vb > prev {
                continue;
            }
            if i < na {
                a[i].1 -= 1;
            }
            if j < nb {
                b[j].1 -= 1;
            }
            sum[slot] = va + vb;
            walk(
                sum,
                slot + 1,
                va + vb,
                a,
                b,
                left_a - usize::from(i < na),
                left_b - usize::from(j < nb),
                emit,
            );
            if i < na {
                a[i].1 += 1;
            }
            if j < nb {
                b[j].1 += 1;
            }
        }
    }
    sum[slot] = 0;
}

/// A basis that is also a *ring* under its own multiplication, with a unit (the
/// empty partition, = 1). This lets generic code — determinants in particular —
/// multiply basis elements without knowing which basis it holds.
pub trait SymAlgebra<C: Ring>: SymFn<C> {
    /// The multiplicative unit 1 = x_∅.
    fn unit() -> Self {
        Self::monomial(Partition::default(), C::one())
    }
    /// The basis product (delegates to each basis's inherent `mul`).
    fn times(&self, other: &Self) -> Self;
}

impl<C: Ring> SymAlgebra<C> for Homogeneous<C> {
    fn times(&self, o: &Self) -> Self {
        self.mul(o)
    }
}
impl<C: Ring> SymAlgebra<C> for Elementary<C> {
    fn times(&self, o: &Self) -> Self {
        self.mul(o)
    }
}
impl<C: Ring> SymAlgebra<C> for PowerSum<C> {
    fn times(&self, o: &Self) -> Self {
        self.mul(o)
    }
}
impl<C: Ring> SymAlgebra<C> for Schur<C> {
    fn times(&self, o: &Self) -> Self {
        self.mul(o)
    }
}
impl<C: Ring> SymAlgebra<C> for Monomial<C> {
    fn times(&self, o: &Self) -> Self {
        self.mul(o)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn s(parts: &[u32], c: i64) -> Schur<i64> {
        Schur::monomial(Partition::new(parts.iter().copied()), c)
    }

    /// The direct overlay rule and the `m → s → m` route must agree.
    ///
    /// They share no step: one counts pairs of rearrangements slot by slot, the
    /// other inverts the Kostka matrix, runs Littlewood–Richardson, and applies
    /// the Kostka matrix again. Agreement across a whole degree is the check
    /// that the joint recursion's pruning drops only branches that could not
    /// have completed.
    #[test]
    fn monomial_product_agrees_with_the_schur_route() {
        use crate::memo::partitions_cached;
        for a in 0..=4u32 {
            for b in 0..=4u32 {
                for mu in partitions_cached(a).iter() {
                    for nu in partitions_cached(b).iter() {
                        let x: Monomial<i64> = Monomial::monomial(mu.clone(), 1);
                        let y: Monomial<i64> = Monomial::monomial(nu.clone(), 1);
                        assert_eq!(x.mul(&y), x.mul_via_schur(&y), "m_{mu} · m_{nu}");
                    }
                }
            }
        }
    }

    /// The product is what evaluation says it is: `(fg)(x) = f(x)·g(x)` at a
    /// concrete alphabet, for any alphabet long enough to separate the terms.
    ///
    /// This pins the structure constants against something outside the basis
    /// entirely, so a rule that were self-consistently wrong — double-counting
    /// equal parts, say — would still fail here.
    #[test]
    fn monomial_product_evaluates_as_a_product() {
        use crate::memo::partitions_cached;
        let xs = [2i64, -1, 3, 1, -2, 4];
        for a in 0..=4u32 {
            for b in 0..=4u32 {
                for mu in partitions_cached(a).iter() {
                    for nu in partitions_cached(b).iter() {
                        let x: Monomial<i64> = Monomial::monomial(mu.clone(), 1);
                        let y: Monomial<i64> = Monomial::monomial(nu.clone(), 1);
                        assert_eq!(
                            x.mul(&y).eval(&xs),
                            x.eval(&xs) * y.eval(&xs),
                            "m_{mu} · m_{nu} at the alphabet"
                        );
                    }
                }
            }
        }
    }

    /// `m_1 · m_1 = 2·m_{11} + m_2`, the smallest value that distinguishes the
    /// monomial product from the multiset union p, e and h use.
    #[test]
    fn monomial_product_is_not_a_multiset_union() {
        let m1: Monomial<i64> = Monomial::monomial(Partition::new([1]), 1);
        let sq = m1.mul(&m1);
        assert_eq!(sq.coeff(&Partition::new([1, 1])), 2);
        assert_eq!(sq.coeff(&Partition::new([2])), 1);
        assert_eq!(sq.terms().len(), 2);
    }

    #[test]
    fn schur_product_matches_known_expansion() {
        // s_2 · s_1 = s_3 + s_{21}
        let prod = s(&[2], 1).mul(&s(&[1], 1));
        assert_eq!(prod.coeff(&Partition::new([3])), 1);
        assert_eq!(prod.coeff(&Partition::new([2, 1])), 1);
        assert_eq!(prod.terms().len(), 2);
    }

    #[test]
    fn schur_product_is_commutative() {
        let a = s(&[2, 1], 1);
        let b = s(&[2], 1).add(&s(&[1, 1], 1));
        assert_eq!(a.mul(&b), b.mul(&a));
    }

    #[test]
    fn schur_multiplicity_two_survives_scaling() {
        // 3·s_{21} · s_{21} has coefficient 6 on s_{321}
        let prod = s(&[2, 1], 3).mul(&s(&[2, 1], 1));
        assert_eq!(prod.coeff(&Partition::new([3, 2, 1])), 6);
    }

    /// `mul_with` builds the first pair's terms in one pass and accumulates
    /// the rest by reference; both must give what adding every term of every
    /// pair's expansion one at a time gives, over the reference backend.
    #[test]
    fn schur_product_matches_term_by_term_accumulation() {
        use crate::lr::NaiveLr;
        let a = s(&[2, 1], 1).add(&s(&[3], -1)).add(&s(&[1, 1, 1], 2));
        let b = s(&[2], 1).add(&s(&[1, 1], -1)).add(&s(&[3, 1], 1));
        let mut want: Schur<i64> = Schur::zero();
        for (mu, cmu) in a.terms() {
            for (nu, cnu) in b.terms() {
                for (lambda, k) in NaiveLr.schur_product(mu, nu) {
                    want.add_term(lambda, i64::try_from(k).unwrap() * cmu * cnu);
                }
            }
        }
        assert_eq!(a.mul(&b), want);
        assert_eq!(a.mul_with(&b, &NaiveLr), want);
        assert!(want.terms().values().all(|c| *c != 0));
    }

    /// `(s_2 − s_{11}) · s_1 = s_3 − s_{111}`: the `s_{21}` the two pairs
    /// contribute cancels, and the canceled term must leave the map rather
    /// than sit in it as an explicit zero.
    #[test]
    fn schur_product_drops_a_term_that_cancels_across_pairs() {
        let a = s(&[2], 1).add(&s(&[1, 1], -1));
        let prod = a.mul(&s(&[1], 1));
        assert_eq!(prod, s(&[3], 1).add(&s(&[1, 1, 1], -1)));
        assert_eq!(prod.terms().len(), 2);
        assert!(!prod.terms().contains_key(&Partition::new([2, 1])));
        // The same cancellation inside one `add_term`.
        let mut f = s(&[2, 1], 4);
        f.add_term(Partition::new([2, 1]), -4);
        assert!(f.is_zero());
    }

    /// The zero element absorbs, on either side, and no pair is ever formed.
    #[test]
    fn schur_product_with_zero_is_zero() {
        let a = s(&[2, 1], 1).add(&s(&[3], -1));
        let zero: Schur<i64> = Schur::zero();
        assert!(a.mul(&zero).is_zero());
        assert!(zero.mul(&a).is_zero());
        assert!(zero.mul(&zero).is_zero());
    }

    #[test]
    fn power_sum_product_is_multiset_union() {
        // p_2 · p_{31} = p_{321}
        let a: PowerSum<i64> = PowerSum::monomial(Partition::new([2]), 1);
        let b: PowerSum<i64> = PowerSum::monomial(Partition::new([3, 1]), 1);
        let prod = a.mul(&b);
        assert_eq!(prod.coeff(&Partition::new([3, 2, 1])), 1);
        assert_eq!(prod.terms().len(), 1);
    }

    #[test]
    fn elementary_and_homogeneous_products_are_multiplicative() {
        // e_2 · e_1 = e_{21}, h_{11} · h_2 = h_{211}
        let e: Elementary<i64> = Elementary::monomial(Partition::new([2]), 1);
        let e1: Elementary<i64> = Elementary::monomial(Partition::new([1]), 1);
        assert_eq!(e.mul(&e1).coeff(&Partition::new([2, 1])), 1);

        let h: Homogeneous<i64> = Homogeneous::monomial(Partition::new([1, 1]), 1);
        let h2: Homogeneous<i64> = Homogeneous::monomial(Partition::new([2]), 1);
        let prod = h.mul(&h2);
        assert_eq!(prod.coeff(&Partition::new([2, 1, 1])), 1);
        assert_eq!(prod.terms().len(), 1);
    }

    #[test]
    fn display_omits_unit_coefficient() {
        let f = s(&[2], 1).add(&s(&[1, 1], 3));
        // BTreeMap order: [1,1] < [2] lexicographically? parts vecs: [1,1] vs [2] -> [1,1] < [2]
        assert_eq!(f.to_string(), "3*s[1,1] + s[2]");
    }
}