Skip to main content

feynkit_tensor/
weingarten.rs

1//! Orthogonal-Weingarten coefficients for Lorentz-invariant projectors.
2//!
3//! This implements the Collins--Matsumoto orthogonality recurrence.  At rank
4//! `2k`, invariance under the hyperoctahedral group reduces the coefficient
5//! system from `(2k - 1)!!` pairings to `p(k)` integer partitions.
6//! This is the coefficient-generation counterpart of the orbit projectors in
7//! Goode *et al.*, [arXiv:2408.05137](https://arxiv.org/abs/2408.05137); the
8//! recurrence is Lemma 4.3 of Collins and Matsumoto,
9//! [arXiv:1701.04493](https://arxiv.org/abs/1701.04493).
10
11use std::{
12    collections::BTreeMap,
13    sync::{Mutex, OnceLock},
14};
15
16use symbolica::{
17    atom::{Atom, AtomCore},
18    symbol,
19};
20use thiserror::Error;
21
22/// The coset type of two perfect matchings.
23///
24/// Superimposing two matchings gives disjoint alternating cycles.  Dividing
25/// every cycle length by two produces an integer partition of the number of
26/// pairs; that partition is the coset type.  Orthogonal-Weingarten
27/// coefficients are constant on each such class.
28///
29/// # Examples
30///
31/// The crossed and uncrossed contractions of a rank-four vacuum tensor have
32/// coset types `[2]` and `[1, 1]`, respectively.
33///
34/// ```
35/// use feynkit_tensor::CosetType;
36///
37/// let crossed = CosetType::new([2])?;
38/// assert_eq!(crossed.parts(), [2]);
39/// # Ok::<(), feynkit_tensor::WeingartenError>(())
40/// ```
41#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
42pub struct CosetType {
43    parts: Box<[usize]>,
44}
45
46impl CosetType {
47    /// Construct a coset type from positive partition parts.
48    ///
49    /// The parts are canonicalized into non-increasing order.  The empty
50    /// partition is the unique rank-zero coset type.  Coset types above the
51    /// validated rank-20 target are rejected.
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use feynkit_tensor::CosetType;
57    ///
58    /// let orbit = CosetType::new([1, 3, 1])?;
59    /// assert_eq!(orbit.parts(), [3, 1, 1]);
60    /// # Ok::<(), feynkit_tensor::WeingartenError>(())
61    /// ```
62    pub fn new(parts: impl IntoIterator<Item = usize>) -> Result<Self, WeingartenError> {
63        let mut parts = parts.into_iter().collect::<Vec<_>>();
64        if parts.contains(&0) {
65            return Err(WeingartenError::ZeroPartitionPart);
66        }
67        let pair_count = parts.iter().try_fold(0_usize, |total, part| {
68            total
69                .checked_add(*part)
70                .ok_or(WeingartenError::RankOverflow)
71        })?;
72        if pair_count > OrthogonalWeingarten::MAX_RANK / 2 {
73            return Err(WeingartenError::UnsupportedRank {
74                rank: pair_count.saturating_mul(2),
75                maximum: OrthogonalWeingarten::MAX_RANK,
76            });
77        }
78        parts.sort_unstable_by(|left, right| right.cmp(left));
79        Ok(Self {
80            parts: parts.into_boxed_slice(),
81        })
82    }
83
84    /// Infer the coset type of two matchings represented by partner arrays.
85    ///
86    /// A matching `[1, 0, 3, 2]`, for example, contains the pairs `(0, 1)`
87    /// and `(2, 3)`.  Both arrays must be fixed-point-free involutions of the
88    /// same even length.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use feynkit_tensor::CosetType;
94    ///
95    /// let direct = [1, 0, 3, 2];
96    /// let crossed = [2, 3, 0, 1];
97    /// assert_eq!(CosetType::between_matchings(&direct, &crossed)?.parts(), [2]);
98    /// # Ok::<(), feynkit_tensor::WeingartenError>(())
99    /// ```
100    pub fn between_matchings(left: &[usize], right: &[usize]) -> Result<Self, WeingartenError> {
101        validate_matching(left)?;
102        validate_matching(right)?;
103        if left.len() != right.len() {
104            return Err(WeingartenError::MatchingLengthMismatch {
105                left: left.len(),
106                right: right.len(),
107            });
108        }
109
110        let mut seen = vec![false; left.len()];
111        let mut parts = Vec::new();
112        for start in 0..left.len() {
113            if seen[start] {
114                continue;
115            }
116            let mut stack = vec![start];
117            let mut vertices = 0;
118            while let Some(vertex) = stack.pop() {
119                if seen[vertex] {
120                    continue;
121                }
122                seen[vertex] = true;
123                vertices += 1;
124                stack.push(left[vertex]);
125                stack.push(right[vertex]);
126            }
127            debug_assert_eq!(vertices % 2, 0);
128            parts.push(vertices / 2);
129        }
130        Self::new(parts)
131    }
132
133    /// Integer-partition parts in canonical non-increasing order.
134    pub fn parts(&self) -> &[usize] {
135        &self.parts
136    }
137
138    /// Number of pairs, so the associated tensor rank is twice this value.
139    pub fn pair_count(&self) -> usize {
140        self.parts.iter().sum()
141    }
142
143    /// Number of matchings in this coset class relative to one fixed matching.
144    /// This is the orbit-size formula
145    /// `2^(k - length(lambda)) k! / z_lambda` of Eq. (2.39) in Goode *et al.*
146    /// for a partition `lambda` of `k`.
147    ///
148    /// # Examples
149    ///
150    /// There are six rank-six pairings in the `[2, 1]` orbit.
151    ///
152    /// ```
153    /// use feynkit_tensor::CosetType;
154    ///
155    /// assert_eq!(CosetType::new([2, 1])?.class_size(), 6);
156    /// # Ok::<(), feynkit_tensor::WeingartenError>(())
157    /// ```
158    pub fn class_size(&self) -> u128 {
159        let pair_count = self.pair_count();
160        let mut numerator = 1_u128 << (pair_count - self.parts.len());
161        numerator *= factorial(pair_count);
162
163        let mut denominator = 1_u128;
164        let mut offset = 0;
165        while offset < self.parts.len() {
166            let part = self.parts[offset];
167            let multiplicity = self.parts[offset..]
168                .iter()
169                .take_while(|candidate| **candidate == part)
170                .count();
171            denominator *= (part as u128).pow(multiplicity as u32);
172            denominator *= factorial(multiplicity);
173            offset += multiplicity;
174        }
175        numerator / denominator
176    }
177
178    fn without_one(&self) -> Option<Self> {
179        let one = self.parts.iter().rposition(|part| *part == 1)?;
180        let mut parts = self.parts.to_vec();
181        parts.remove(one);
182        Some(Self {
183            parts: parts.into_boxed_slice(),
184        })
185    }
186}
187
188/// Orthogonal-Weingarten coefficients at one even tensor rank.
189///
190/// Coefficients are exact Symbolica expressions in the caller-supplied
191/// dimension.  Generation proceeds through systems of size `p(k)` at rank
192/// `2k`; in particular, rank 20 has only 42 symmetry classes.
193///
194/// # Examples
195///
196/// Generate the Lorentz projector coefficients for a rank-four vacuum
197/// numerator in dimensional regularization.
198///
199/// ```no_run
200/// use feynkit_tensor::{CosetType, OrthogonalWeingarten};
201/// use symbolica::parse;
202///
203/// let table = OrthogonalWeingarten::for_rank(4, parse!("4 - 2*eps"))?;
204/// let crossed = table.coefficient(&CosetType::new([2])?)?;
205/// println!("crossed projector coefficient = {crossed}");
206/// # Ok::<(), feynkit_tensor::WeingartenError>(())
207/// ```
208#[derive(Clone, Debug)]
209pub struct OrthogonalWeingarten {
210    pair_count: usize,
211    dimension: Atom,
212    coefficients: BTreeMap<CosetType, Atom>,
213}
214
215impl OrthogonalWeingarten {
216    /// Largest tensor rank supported by the native coefficient engine.
217    pub const MAX_RANK: usize = 20;
218
219    /// Generate all coefficients for `pair_count` metric pairs.
220    ///
221    /// `dimension` may itself be symbolic, such as `4 - 2*eps`.  A rank-zero
222    /// table contains the empty coset type with coefficient one.  At most ten
223    /// pairs (rank 20) are accepted. Keep mixed high-rank projectors symbolic:
224    /// at fixed positive integer dimension `d < pair_count`, the labeled
225    /// metric basis is redundant and this constructor returns
226    /// [`WeingartenError::SingularDimension`]. The all-equal isotropic formula
227    /// does not require this inverse.
228    ///
229    /// # Examples
230    ///
231    /// ```no_run
232    /// use feynkit_tensor::OrthogonalWeingarten;
233    /// use symbolica::parse;
234    ///
235    /// let rank_six = OrthogonalWeingarten::new(3, parse!("D"))?;
236    /// assert_eq!(rank_six.rank(), 6);
237    /// # Ok::<(), feynkit_tensor::WeingartenError>(())
238    /// ```
239    pub fn new(pair_count: usize, dimension: Atom) -> Result<Self, WeingartenError> {
240        if pair_count > Self::MAX_RANK / 2 {
241            return Err(WeingartenError::UnsupportedRank {
242                rank: pair_count.saturating_mul(2),
243                maximum: Self::MAX_RANK,
244            });
245        }
246        Self::validate_inverse_dimension(pair_count, &dimension)?;
247        let canonical_dimension = canonical_dimension();
248        let canonical_coefficients = canonical_coefficients(pair_count, &canonical_dimension)?;
249
250        let coefficients = if dimension == canonical_dimension {
251            canonical_coefficients
252        } else {
253            canonical_coefficients
254                .into_iter()
255                .map(|(coset_type, coefficient)| {
256                    let coefficient = coefficient
257                        .replace(canonical_dimension.to_pattern())
258                        .with(dimension.clone());
259                    (coset_type, coefficient)
260                })
261                .collect()
262        };
263
264        Ok(Self {
265            pair_count,
266            dimension,
267            coefficients,
268        })
269    }
270
271    /// Generate coefficients for an even tensor rank.
272    ///
273    /// # Examples
274    ///
275    /// ```no_run
276    /// use feynkit_tensor::OrthogonalWeingarten;
277    /// use symbolica::parse;
278    ///
279    /// let projector = OrthogonalWeingarten::for_rank(12, parse!("4 - 2*eps"))?;
280    /// assert_eq!(projector.coefficients().len(), 11);
281    /// # Ok::<(), feynkit_tensor::WeingartenError>(())
282    /// ```
283    pub fn for_rank(rank: usize, dimension: Atom) -> Result<Self, WeingartenError> {
284        if !rank.is_multiple_of(2) {
285            return Err(WeingartenError::OddRank(rank));
286        }
287        Self::new(rank / 2, dimension)
288    }
289
290    /// Tensor rank covered by this table.
291    pub fn rank(&self) -> usize {
292        2 * self.pair_count
293    }
294
295    /// Number of metric pairs covered by this table.
296    pub fn pair_count(&self) -> usize {
297        self.pair_count
298    }
299
300    /// Dimension expression used in the generated coefficients.
301    pub fn dimension(&self) -> &Atom {
302        &self.dimension
303    }
304
305    /// Look up the coefficient of a coset type.
306    ///
307    /// # Examples
308    ///
309    /// ```no_run
310    /// use feynkit_tensor::{CosetType, OrthogonalWeingarten};
311    /// use symbolica::parse;
312    ///
313    /// let projector = OrthogonalWeingarten::for_rank(6, parse!("D"))?;
314    /// let coefficient = projector.coefficient(&CosetType::new([3])?)?;
315    /// println!("fully crossed rank-six coefficient = {coefficient}");
316    /// # Ok::<(), feynkit_tensor::WeingartenError>(())
317    /// ```
318    pub fn coefficient(&self, coset_type: &CosetType) -> Result<&Atom, WeingartenError> {
319        if coset_type.pair_count() != self.pair_count {
320            return Err(WeingartenError::CosetRankMismatch {
321                table_rank: self.rank(),
322                coset_rank: 2 * coset_type.pair_count(),
323            });
324        }
325        Ok(&self.coefficients[coset_type])
326    }
327
328    /// Iterate over all coset types and exact coefficients.
329    pub fn coefficients(&self) -> impl ExactSizeIterator<Item = (&CosetType, &Atom)> {
330        self.coefficients.iter()
331    }
332
333    /// Coefficient of every metric pairing for a totally symmetric tensor.
334    ///
335    /// For an integrand containing one repeated loop momentum, this is the
336    /// closed isotropic-tensor result
337    /// `1 / (D (D + 2) ... (D + 2k - 2))`.  It avoids constructing the full
338    /// Weingarten table and is therefore the preferred rank-20 fast path.
339    ///
340    /// # Examples
341    ///
342    /// A numerator with twenty powers of the same loop momentum uses this
343    /// coefficient for every product of ten metrics.
344    ///
345    /// ```
346    /// use feynkit_tensor::OrthogonalWeingarten;
347    /// use symbolica::parse;
348    ///
349    /// let coefficient =
350    ///     OrthogonalWeingarten::isotropic_pairing_coefficient(10, parse!("D"));
351    /// assert!(coefficient.to_string().contains("D"));
352    /// ```
353    pub fn isotropic_pairing_coefficient(pair_count: usize, dimension: Atom) -> Atom {
354        let denominator = (0..pair_count).fold(Atom::num(1), |denominator, offset| {
355            denominator * (dimension.clone() + Atom::num(2 * offset as i64))
356        });
357        Atom::num(1) / denominator
358    }
359
360    pub(crate) fn validate_inverse_dimension(
361        pair_count: usize,
362        dimension: &Atom,
363    ) -> Result<(), WeingartenError> {
364        if pair_count == 0 {
365            return Ok(());
366        }
367        if let Ok(fixed_dimension) = i64::try_from(dimension.as_view())
368            && (fixed_dimension <= 0 || fixed_dimension < pair_count as i64)
369        {
370            return Err(WeingartenError::SingularDimension {
371                rank: 2 * pair_count,
372                dimension: dimension.clone(),
373            });
374        }
375        Ok(())
376    }
377}
378
379fn canonical_coefficients(
380    pair_count: usize,
381    dimension: &Atom,
382) -> Result<BTreeMap<CosetType, Atom>, WeingartenError> {
383    static TABLES: OnceLock<Mutex<Vec<BTreeMap<CosetType, Atom>>>> = OnceLock::new();
384    let tables = TABLES.get_or_init(|| {
385        Mutex::new(vec![BTreeMap::from([(
386            CosetType {
387                parts: Box::new([]),
388            },
389            Atom::num(1),
390        )])])
391    });
392    let mut tables = tables
393        .lock()
394        .unwrap_or_else(|poisoned| poisoned.into_inner());
395    while tables.len() <= pair_count {
396        let current_pairs = tables.len();
397        let next = solve_level(current_pairs, dimension, tables.last().unwrap())?;
398        tables.push(next);
399    }
400    Ok(tables[pair_count].clone())
401}
402
403/// Failures in coset-type validation or coefficient generation.
404///
405/// # Examples
406///
407/// An odd-rank vacuum numerator has no Lorentz-invariant metric projector.
408///
409/// ```
410/// use feynkit_tensor::{OrthogonalWeingarten, WeingartenError};
411/// use symbolica::parse;
412///
413/// let error = OrthogonalWeingarten::for_rank(3, parse!("D")).unwrap_err();
414/// assert!(matches!(error, WeingartenError::OddRank(3)));
415/// ```
416#[derive(Debug, Error)]
417pub enum WeingartenError {
418    /// Tensor projectors only exist at even rank.
419    #[error("tensor rank {0} is odd; vacuum tensor reduction requires an even rank")]
420    OddRank(usize),
421    /// The exact engine is bounded to the validated high-rank target.
422    #[error("tensor rank {rank} exceeds the supported maximum {maximum}")]
423    UnsupportedRank { rank: usize, maximum: usize },
424    /// Summing user-provided partition parts overflowed the platform integer.
425    #[error("coset-type tensor rank is too large to represent")]
426    RankOverflow,
427    /// Integer partitions cannot contain zero.
428    #[error("coset-type partition parts must be positive")]
429    ZeroPartitionPart,
430    /// Matching arrays must describe the same vertex set.
431    #[error("matching lengths differ: left has {left} vertices, right has {right}")]
432    MatchingLengthMismatch { left: usize, right: usize },
433    /// A partner array did not describe a perfect matching.
434    #[error("invalid matching at vertex {vertex}: partner is {partner}")]
435    InvalidMatching { vertex: usize, partner: usize },
436    /// A coefficient was requested from a table at another rank.
437    #[error("coset type has rank {coset_rank}, but this table has rank {table_rank}")]
438    CosetRankMismatch {
439        table_rank: usize,
440        coset_rank: usize,
441    },
442    /// At low fixed integer dimension, metric pairings obey dimension-specific
443    /// identities and the universal Gram matrix has no inverse.
444    #[error(
445        "rank-{rank} metric-pairing Gram matrix is singular in fixed dimension {dimension}; keep the dimension symbolic or use the all-equal isotropic projector"
446    )]
447    SingularDimension { rank: usize, dimension: Atom },
448    /// Symbolica could not solve the reduced recurrence system.
449    #[error("could not solve rank-{rank} orthogonal-Weingarten system: {source}")]
450    Solve {
451        rank: usize,
452        #[source]
453        source: symbolica::solve::SolveError,
454    },
455}
456
457fn solve_level(
458    pair_count: usize,
459    dimension: &Atom,
460    lower: &BTreeMap<CosetType, Atom>,
461) -> Result<BTreeMap<CosetType, Atom>, WeingartenError> {
462    let coset_types = partitions(pair_count);
463    let variables = (0..coset_types.len())
464        .map(|index| {
465            Atom::var(symbol!(&format!(
466                "FeynKit::OrthogonalWeingarten{pair_count}_{index}"
467            )))
468        })
469        .collect::<Vec<_>>();
470    let positions = coset_types
471        .iter()
472        .enumerate()
473        .map(|(index, coset_type)| (coset_type.clone(), index))
474        .collect::<BTreeMap<_, _>>();
475
476    let equations = coset_types
477        .iter()
478        .enumerate()
479        .map(|(row, coset_type)| {
480            let matching = representative(coset_type);
481            let mut equation = dimension * &variables[row];
482            let pivot = 2 * pair_count - 2;
483            for vertex in 0..pivot {
484                let moved = relabel_transposition(&matching, vertex, pivot);
485                let target = CosetType::between_matchings(&reference_matching(pair_count), &moved)
486                    .expect("a relabelled perfect matching remains valid");
487                equation += &variables[positions[&target]];
488            }
489            if let Some(lower_type) = coset_type.without_one() {
490                equation -= &lower[&lower_type];
491            }
492            equation
493        })
494        .collect::<Vec<_>>();
495
496    let solutions = Atom::system_to_matrix::<u16, _, _>(&equations, &variables)
497        .and_then(|(matrix, rhs)| {
498            matrix
499                .solve(&rhs)
500                .map_err(|error| symbolica::solve::SolveError::Other(error.to_string()))
501        })
502        .map(|solution| {
503            solution
504                .into_vec()
505                .into_iter()
506                .map(|value| value.to_expression())
507                .collect::<Vec<_>>()
508        })
509        .map_err(|source| WeingartenError::Solve {
510            rank: 2 * pair_count,
511            source,
512        })?;
513
514    Ok(coset_types
515        .into_iter()
516        .zip(solutions.into_iter().map(|solution| solution.cancel()))
517        .collect())
518}
519
520fn canonical_dimension() -> Atom {
521    Atom::var(symbol!("FeynKit::Dimension"))
522}
523
524fn partitions(total: usize) -> Vec<CosetType> {
525    fn append(total: usize, maximum: usize, current: &mut Vec<usize>, output: &mut Vec<CosetType>) {
526        if total == 0 {
527            output.push(CosetType {
528                parts: current.clone().into_boxed_slice(),
529            });
530            return;
531        }
532        for next in (1..=total.min(maximum)).rev() {
533            current.push(next);
534            append(total - next, next, current, output);
535            current.pop();
536        }
537    }
538
539    let mut output = Vec::new();
540    append(total, total, &mut Vec::new(), &mut output);
541    output
542}
543
544fn reference_matching(pair_count: usize) -> Vec<usize> {
545    (0..2 * pair_count).map(|vertex| vertex ^ 1).collect()
546}
547
548fn representative(coset_type: &CosetType) -> Vec<usize> {
549    let mut matching = vec![usize::MAX; 2 * coset_type.pair_count()];
550    let mut start = 0;
551    for &part in coset_type.parts() {
552        for pair in 0..part {
553            let right = start + 2 * pair + 1;
554            let next_left = start + 2 * ((pair + 1) % part);
555            matching[right] = next_left;
556            matching[next_left] = right;
557        }
558        start += 2 * part;
559    }
560    matching
561}
562
563fn relabel_transposition(matching: &[usize], left: usize, right: usize) -> Vec<usize> {
564    let transpose = |vertex| {
565        if vertex == left {
566            right
567        } else if vertex == right {
568            left
569        } else {
570            vertex
571        }
572    };
573    let mut moved = vec![usize::MAX; matching.len()];
574    for (vertex, partner) in matching.iter().copied().enumerate() {
575        moved[transpose(vertex)] = transpose(partner);
576    }
577    moved
578}
579
580fn validate_matching(matching: &[usize]) -> Result<(), WeingartenError> {
581    for (vertex, partner) in matching.iter().copied().enumerate() {
582        if partner >= matching.len() || partner == vertex || matching[partner] != vertex {
583            return Err(WeingartenError::InvalidMatching { vertex, partner });
584        }
585    }
586    Ok(())
587}
588
589fn factorial(value: usize) -> u128 {
590    (2..=value).map(|factor| factor as u128).product()
591}
592
593#[cfg(test)]
594mod tests {
595    use std::time::Instant;
596
597    use symbolica::{
598        atom::{Atom, AtomCore},
599        parse,
600    };
601
602    use super::{CosetType, OrthogonalWeingarten, partitions, reference_matching, representative};
603
604    #[test]
605    fn partition_system_sizes_reach_only_42_at_rank_twenty() {
606        let counts = (0..=10)
607            .map(|pair_count| partitions(pair_count).len())
608            .collect::<Vec<_>>();
609        assert_eq!(counts, [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42]);
610        assert_eq!(
611            partitions(10)
612                .iter()
613                .map(CosetType::class_size)
614                .sum::<u128>(),
615            654_729_075
616        );
617    }
618
619    #[test]
620    fn representatives_have_the_requested_coset_type() {
621        for pair_count in 0..=10 {
622            let reference = reference_matching(pair_count);
623            for coset_type in partitions(pair_count) {
624                assert_eq!(
625                    CosetType::between_matchings(&reference, &representative(&coset_type)).unwrap(),
626                    coset_type
627                );
628            }
629        }
630    }
631
632    #[test]
633    fn empty_coset_class_contains_the_empty_matching() {
634        let empty = CosetType::new([]).unwrap();
635        assert_eq!(empty.class_size(), 1);
636        assert_eq!(CosetType::between_matchings(&[], &[]).unwrap(), empty);
637    }
638
639    #[test]
640    fn malformed_odd_matching_is_rejected() {
641        assert!(CosetType::between_matchings(&[1, 0, 2], &[1, 0, 2]).is_err());
642    }
643
644    #[test]
645    fn ranks_above_twenty_are_rejected_before_combinatorics() {
646        assert!(matches!(
647            OrthogonalWeingarten::new(11, parse!("D")),
648            Err(super::WeingartenError::UnsupportedRank {
649                rank: 22,
650                maximum: 20
651            })
652        ));
653        assert!(matches!(
654            CosetType::new([usize::MAX, 1]),
655            Err(super::WeingartenError::RankOverflow)
656        ));
657        assert!(CosetType::new([11]).is_err());
658    }
659
660    #[test]
661    fn rank_four_matches_the_closed_form() {
662        let dimension = parse!("D");
663        let table = OrthogonalWeingarten::new(2, dimension.clone()).unwrap();
664        let denominator = dimension.clone()
665            * (dimension.clone() - Atom::num(1))
666            * (dimension.clone() + Atom::num(2));
667        let diagonal = (dimension.clone() + Atom::num(1)) / denominator.clone();
668        let crossed = -Atom::num(1) / denominator;
669
670        assert!(
671            (table.coefficient(&CosetType::new([1, 1]).unwrap()).unwrap() - diagonal)
672                .together()
673                .is_zero()
674        );
675        assert!(
676            (table.coefficient(&CosetType::new([2]).unwrap()).unwrap() - crossed)
677                .together()
678                .is_zero()
679        );
680    }
681
682    #[test]
683    fn exceptional_fixed_dimensions_are_rejected_before_substitution() {
684        assert!(matches!(
685            OrthogonalWeingarten::for_rank(10, Atom::num(4)),
686            Err(super::WeingartenError::SingularDimension {
687                rank: 10,
688                dimension
689            }) if dimension == Atom::num(4)
690        ));
691        assert!(OrthogonalWeingarten::for_rank(8, Atom::num(4)).is_ok());
692
693        // The totally symmetric projector has a closed isotropic form and
694        // does not invert the redundant labeled-pairing basis.
695        let isotropic = OrthogonalWeingarten::isotropic_pairing_coefficient(10, Atom::num(4));
696        assert!(!isotropic.is_zero());
697    }
698
699    #[test]
700    fn isotropic_fast_path_is_the_sum_over_coset_classes() {
701        let dimension = parse!("D");
702        for pair_count in 1..=5 {
703            let table = OrthogonalWeingarten::new(pair_count, dimension.clone()).unwrap();
704            let summed = table
705                .coefficients()
706                .fold(Atom::num(0), |sum, (kind, value)| {
707                    sum + Atom::num(kind.class_size()) * value
708                });
709            let expected =
710                OrthogonalWeingarten::isotropic_pairing_coefficient(pair_count, dimension.clone());
711            assert!((summed - expected).together().is_zero());
712        }
713    }
714
715    #[test]
716    fn vakint_projector_tables_are_reproduced_through_rank_ten() {
717        let epsilon = parse!("ep");
718        let dimension = Atom::num(4) - Atom::num(2) * epsilon;
719        for rank in [2, 4, 6, 8, 10] {
720            let table = OrthogonalWeingarten::for_rank(rank, dimension.clone()).unwrap();
721            let expected = vakint_coefficients(rank);
722            let types = vakint_coset_order(rank / 2);
723            assert_eq!(expected.len(), types.len());
724            for (index, (expected, coset_type)) in expected.into_iter().zip(types).enumerate() {
725                let actual = table.coefficient(&coset_type).unwrap();
726                assert!(
727                    (actual - &expected).together().is_zero(),
728                    "VAKINT rank-{rank} coefficient {} ({:?}) differs: FeynKit={}, VAKINT={}",
729                    index + 1,
730                    coset_type.parts(),
731                    actual,
732                    expected
733                );
734            }
735        }
736    }
737
738    #[test]
739    fn rank_twenty_table_is_practical() {
740        // Goode et al.'s `coefficients.prc` ancillary is expressed in their
741        // transformed symmetric-`dd` orbit basis, rather than as raw
742        // orthogonal-Weingarten coefficients.  The exact VAKINT projector
743        // entries above are therefore the direct coefficient oracle here.
744        let started = Instant::now();
745        let table = OrthogonalWeingarten::new(10, parse!("D")).unwrap();
746        let elapsed = started.elapsed();
747        assert_eq!(table.coefficients().len(), 42);
748        assert!(
749            table
750                .coefficients()
751                .all(|(_, coefficient)| coefficient.cancel() == coefficient.clone())
752        );
753        let isotropic_sum = table
754            .coefficients()
755            .fold(Atom::num(0), |sum, (kind, coefficient)| {
756                sum + Atom::num(kind.class_size()) * coefficient
757            });
758        let isotropic_closed = OrthogonalWeingarten::isotropic_pairing_coefficient(10, parse!("D"));
759        assert!((isotropic_sum - isotropic_closed).together().is_zero());
760        eprintln!("rank-20 orthogonal-Weingarten table: {elapsed:?}");
761    }
762
763    fn vakint_coset_order(pair_count: usize) -> Vec<CosetType> {
764        let ascending_largest_part = match pair_count {
765            1 => vec![vec![1]],
766            2 => vec![vec![1, 1], vec![2]],
767            3 => vec![vec![1, 1, 1], vec![2, 1], vec![3]],
768            4 => vec![
769                vec![1, 1, 1, 1],
770                vec![2, 1, 1],
771                vec![2, 2],
772                vec![3, 1],
773                vec![4],
774            ],
775            5 => vec![
776                vec![1, 1, 1, 1, 1],
777                vec![2, 1, 1, 1],
778                vec![2, 2, 1],
779                vec![3, 1, 1],
780                vec![3, 2],
781                vec![4, 1],
782                vec![5],
783            ],
784            _ => unreachable!("VAKINT only preloads projector tables through rank ten"),
785        };
786        ascending_largest_part
787            .into_iter()
788            .map(|parts| CosetType::new(parts).unwrap())
789            .collect()
790    }
791
792    fn vakint_coefficients(rank: usize) -> Vec<Atom> {
793        // Exact MIT-licensed oracle transcribed from VAKINT's FORM tables
794        // `tensorreduce.frm` and `pvtab10.h` at D = 4 - 2 ep.  Keeping the
795        // compact coefficient data here lets this crate package independently
796        // instead of reaching into a sibling workspace member at compile time.
797        let expressions: &[&str] = match rank {
798            2 => &["1/(4-2*ep)"],
799            4 => &[
800                "(5-2*ep)/(72-108*ep+52*ep^2-8*ep^3)",
801                "-1/(72-108*ep+52*ep^2-8*ep^3)",
802            ],
803            6 => &[
804                "(26-22*ep+4*ep^2)/(1152-3168*ep+3280*ep^2-1600*ep^3+368*ep^4-32*ep^5)",
805                "-1/(192-464*ep+392*ep^2-136*ep^3+16*ep^4)",
806                "2/(1152-3168*ep+3280*ep^2-1600*ep^3+368*ep^4-32*ep^5)",
807            ],
808            8 => &[
809                "(287-278*ep+84*ep^2-8*ep^3)/(28800-125280*ep+199504*ep^2-159680*ep^3+71152*ep^4-17888*ep^5+2368*ep^6-128*ep^7)",
810                "(-166+198*ep-72*ep^2+8*ep^3)/(57600-308160*ep+649568*ep^2-718368*ep^3+461664*ep^4-178080*ep^5+40512*ep^6-4992*ep^7+256*ep^8)",
811                "(54-26*ep+4*ep^2)/(57600-308160*ep+649568*ep^2-718368*ep^3+461664*ep^4-178080*ep^5+40512*ep^6-4992*ep^7+256*ep^8)",
812                "2/(1800-8280*ep+13864*ep^2-11016*ep^3+4432*ep^4-864*ep^5+64*ep^6)",
813                "(-26+10*ep)/(57600-308160*ep+649568*ep^2-718368*ep^3+461664*ep^4-178080*ep^5+40512*ep^6-4992*ep^7+256*ep^8)",
814            ],
815            10 => &[
816                "(1280-5628*ep+6324*ep^2-2728*ep^3+496*ep^4-32*ep^5)/(-1382400*ep+7626240*ep^2-16822272*ep^3+19839104*ep^4-13953408*ep^5+6120576*ep^6-1684608*ep^7+281856*ep^8-26112*ep^9+1024*ep^10)",
817                "(-640+1412*ep-892*ep^2+208*ep^3-16*ep^4)/(-1382400*ep+7626240*ep^2-16822272*ep^3+19839104*ep^4-13953408*ep^5+6120576*ep^6-1684608*ep^7+281856*ep^8-26112*ep^9+1024*ep^10)",
818                "(32-22*ep+4*ep^2)/(-138240*ep+734976*ep^2-1535232*ep^3+1676864*ep^4-1059968*ep^5+400064*ep^6-88448*ep^7+10496*ep^8-512*ep^9)",
819                "(320-452*ep+160*ep^2-16*ep^3)/(-1382400*ep+7626240*ep^2-16822272*ep^3+19839104*ep^4-13953408*ep^5+6120576*ep^6-1684608*ep^7+281856*ep^8-26112*ep^9+1024*ep^10)",
820                "(-160+60*ep-8*ep^2)/(-1382400*ep+7626240*ep^2-16822272*ep^3+19839104*ep^4-13953408*ep^5+6120576*ep^6-1684608*ep^7+281856*ep^8-26112*ep^9+1024*ep^10)",
821                "(-16+10*ep)/(-138240*ep+734976*ep^2-1535232*ep^3+1676864*ep^4-1059968*ep^5+400064*ep^6-88448*ep^7+10496*ep^8-512*ep^9)",
822                "(80-28*ep)/(-1382400*ep+7626240*ep^2-16822272*ep^3+19839104*ep^4-13953408*ep^5+6120576*ep^6-1684608*ep^7+281856*ep^8-26112*ep^9+1024*ep^10)",
823            ],
824            _ => unreachable!("VAKINT only preloads projector tables through rank ten"),
825        };
826        expressions
827            .iter()
828            .map(|expression| parse!(expression))
829            .collect()
830    }
831}