Skip to main content

feynkit_kinematics/
symbolic.rs

1//! Scoped scalar-product assumptions; no global Symbolica state is mutated.
2
3use spenso::{
4    network::library::symbolic::ETS,
5    structure::{
6        dimension::{Dimension, DimensionError},
7        representation::{Minkowski, RepName},
8    },
9};
10use std::{
11    collections::{BTreeMap, BTreeSet},
12    sync::Arc,
13};
14use symbolica::{
15    atom::{Atom, AtomCore, AtomView},
16    domains::atom::AtomField,
17    function,
18    poly::PolyVariable,
19};
20use thiserror::Error;
21
22#[derive(Clone, Debug, Error)]
23pub enum SymbolicKinematicsError {
24    #[error("expected an unindexed momentum symbol or labeled call, got {0}")]
25    InvalidMomentum(Atom),
26    #[error("{0} is not linear in the declared momenta; declare momenta before combining them")]
27    NonlinearMomentum(Atom),
28    #[error("phase-space densities require four-dimensional kinematics")]
29    PhaseSpaceDimension,
30    #[error("Weyl-matrix pivot {0:?} is outside the two-by-two matrix")]
31    InvalidWeylPivot([usize; 2]),
32    #[error("Weyl-matrix pivot {0:?} is identically zero")]
33    ZeroWeylPivot([usize; 2]),
34}
35
36/// Symbolic Lorentz kinematics in Spenso's scalar-product notation.
37///
38/// Momentum names are unindexed symbols or labeled calls such as `Q(1)`.
39/// Assumptions belong to this value and can be reused across expressions.
40/// Tensor and Dirac contractions remain the responsibility of Idenso; apply
41/// these substitutions after converting contractions to compact scalar products.
42#[derive(Clone, Debug)]
43pub struct Kinematics {
44    dimension: Dimension,
45    products: BTreeMap<Atom, Atom>,
46    momenta: BTreeSet<Atom>,
47}
48
49impl Default for Kinematics {
50    fn default() -> Self {
51        Self {
52            dimension: 4.into(),
53            products: BTreeMap::new(),
54            momenta: BTreeSet::new(),
55        }
56    }
57}
58
59impl Kinematics {
60    /// Construct an empty set of four-dimensional scalar-product assumptions.
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    /// Lorentz dimension carried by this context's scalar products.
66    pub fn dimension(&self) -> Dimension {
67        self.dimension
68    }
69
70    /// Declared formal momentum names, including those without assumptions.
71    ///
72    /// Iteration follows native Atom ordering, not a portable serialization order.
73    pub fn momenta(&self) -> impl ExactSizeIterator<Item = &Atom> {
74        self.momenta.iter()
75    }
76
77    /// Every stored scalar-product key and its value, including metric aliases.
78    ///
79    /// Values are borrowed verbatim: no substitution or arithmetic is performed.
80    /// Iteration follows native Atom ordering, not a portable serialization order.
81    pub fn scalar_assumptions(&self) -> impl ExactSizeIterator<Item = (&Atom, &Atom)> {
82        self.products.iter()
83    }
84
85    /// Transform scalar assumption values while retaining all keys and momenta.
86    ///
87    /// The callback runs once per structurally distinct original value, in native
88    /// Atom order. Its result is reused for every occurrence, so equal values
89    /// and dot/metric aliases remain equal even with a stateful callback. Results
90    /// are stored verbatim, without recursive substitution or simplification.
91    /// Dimension and formal momentum names are unchanged. Failure returns no
92    /// partial owner and leaves `self` unchanged; callback side effects are not
93    /// rolled back. An arbitrary mapping does not certify physical equivalence.
94    pub fn try_map_scalar_values<E>(
95        &self,
96        mut map: impl FnMut(&Atom) -> Result<Atom, E>,
97    ) -> Result<Self, E> {
98        let values = self.products.values().collect::<BTreeSet<_>>();
99        let mapped = values
100            .into_iter()
101            .map(|value| map(value).map(|mapped| (value, mapped)))
102            .collect::<Result<BTreeMap<_, _>, E>>()?;
103        Ok(Self {
104            dimension: self.dimension,
105            momenta: self.momenta.clone(),
106            products: self
107                .products
108                .iter()
109                .map(|(key, value)| (key.clone(), mapped[value].clone()))
110                .collect(),
111        })
112    }
113
114    /// Start with no assumptions in a symbolic or nonnegative integer dimension.
115    ///
116    /// Use a symbol such as `D` during dimensional regularization, then
117    /// substitute `D = 4 - 2 eps` in the contracted result with Symbolica.
118    pub fn in_dimension(dimension: &Atom) -> Result<Self, DimensionError> {
119        Ok(Self {
120            dimension: Dimension::try_from(dimension.as_view())?,
121            products: BTreeMap::new(),
122            momenta: BTreeSet::new(),
123        })
124    }
125
126    /// Declare momentum names for linear combinations with symbolic coefficients.
127    ///
128    /// Setting a scalar product also declares both momentum names. Symbols not
129    /// declared as momenta are scalar coefficients inside a linear combination.
130    pub fn with_momenta(
131        mut self,
132        momenta: impl IntoIterator<Item = Atom>,
133    ) -> Result<Self, SymbolicKinematicsError> {
134        for momentum in momenta {
135            if !matches!(momentum.as_view(), AtomView::Var(_) | AtomView::Fun(_)) {
136                return Err(SymbolicKinematicsError::InvalidMomentum(momentum));
137            }
138            self.momenta.insert(momentum);
139        }
140        Ok(self)
141    }
142
143    /// Set one scalar product. Reversed arguments use the same symmetric key.
144    pub fn with_scalar_product(
145        self,
146        left: &Atom,
147        right: &Atom,
148        value: Atom,
149    ) -> Result<Self, SymbolicKinematicsError> {
150        let mut result = self.with_momenta([left.clone(), right.clone()])?;
151        let rep = Minkowski {}.new_rep(result.dimension);
152        result
153            .products
154            .insert(rep.inner_product(left, right), value.clone());
155        // Dirac simplification may retain metric shorthand instead of dots.
156        result.products.insert(
157            function!(
158                ETS.metric,
159                rep.vector(left.as_view(), []),
160                rep.vector(right.as_view(), [])
161            ),
162            value,
163        );
164        Ok(result)
165    }
166
167    /// Set the on-shell relation `p.p = mass_squared`.
168    pub fn with_mass_squared(
169        self,
170        momentum: &Atom,
171        mass_squared: Atom,
172    ) -> Result<Self, SymbolicKinematicsError> {
173        self.with_scalar_product(momentum, momentum, mass_squared)
174    }
175
176    /// Initial-state denominator for scattering, or a decay in its rest frame.
177    ///
178    /// Two momenta give `4 sqrt((p1.p2)^2 - p1^2 p2^2)`. One momentum gives
179    /// `2 sqrt(p^2)` for a rest-frame decay. Divide the squared matrix element
180    /// times the phase-space measure by this value. Physical momenta are future
181    /// directed and on shell; square roots retain Symbolica's branch semantics.
182    pub fn flux(
183        &self,
184        first: &Atom,
185        second: Option<&Atom>,
186    ) -> Result<Atom, SymbolicKinematicsError> {
187        let flux = match second {
188            Some(second) => crate::InitialStateFlux::Scattering {
189                momentum_dot: self.scalar_product(first, second)?,
190                mass_squared_product: self.scalar_product(first, first)?
191                    * self.scalar_product(second, second)?,
192            },
193            None => crate::InitialStateFlux::Decay {
194                energy: self.scalar_product(first, first)?.sqrt(),
195            },
196        };
197        Ok(flux.denominator(|value| value.sqrt()))
198    }
199
200    /// Four-dimensional `dPhi_2 / dOmega` for two outgoing on-shell momenta.
201    ///
202    /// The measure includes `(2 pi)^4 delta^4(P-p1-p2)` and each
203    /// `d^3p / ((2 pi)^3 2E)`. The solid angle is measured in the pair rest
204    /// frame. This is the physical above-threshold branch, without an
205    /// identical-particle factor or initial-state flux. Symbolica retains
206    /// roots unless positivity assumptions justify their simplification.
207    pub fn two_body_phase_space(
208        &self,
209        first: &Atom,
210        second: &Atom,
211    ) -> Result<Atom, SymbolicKinematicsError> {
212        if self.dimension != Dimension::from(4) {
213            return Err(SymbolicKinematicsError::PhaseSpaceDimension);
214        }
215        let invariant = self.scalar_product(first, first)?
216            + Atom::num(2) * self.scalar_product(first, second)?
217            + self.scalar_product(second, second)?;
218        Ok(self.flux(first, Some(second))?
219            / (Atom::num(64) * Atom::var(symbolica::atom::Symbol::PI).pow(2) * invariant))
220    }
221
222    /// Four-dimensional `dPhi_3 / (ds12 ds23)`, with overall orientation integrated.
223    ///
224    /// Here `sij=(pi+pj)^2`. The normalization includes `(2 pi)^4 delta^4`
225    /// and `d^3p / ((2 pi)^3 2E)` for each final particle. The density is
226    /// `1/(128 pi^3 P^2)`, where `P=p1+p2+p3`, inside the physical Dalitz
227    /// region. Masses determine that region, not the density. This method does
228    /// not impose its boundaries or include flux or identical-particle factors.
229    /// Use an orientation-independent or orientation-averaged squared amplitude.
230    pub fn three_body_phase_space(
231        &self,
232        first: &Atom,
233        second: &Atom,
234        third: &Atom,
235    ) -> Result<Atom, SymbolicKinematicsError> {
236        if self.dimension != Dimension::from(4) {
237            return Err(SymbolicKinematicsError::PhaseSpaceDimension);
238        }
239        let momenta = [first, second, third];
240        let mut invariant = Atom::Zero;
241        for (i, p) in momenta.iter().enumerate() {
242            invariant += self.scalar_product(p, p)?;
243            for q in &momenta[i + 1..] {
244                invariant += Atom::num(2) * self.scalar_product(p, q)?;
245            }
246        }
247        Ok(Atom::one()
248            / (Atom::num(128) * Atom::var(symbolica::atom::Symbol::PI).pow(3) * invariant))
249    }
250
251    /// Scalar products for `p1 + p2 -> p3 + p4`.
252    ///
253    /// Mass arguments are squared masses. The invariants obey
254    /// `s=(p1+p2)^2`, `t=(p1-p3)^2`, `u=(p1-p4)^2` and
255    /// `s+t+u=sum(mass_squared)`. This constructor does not eliminate an
256    /// invariant; use ordinary Symbolica substitution to choose which to remove.
257    pub fn mandelstam(
258        momenta: [&Atom; 4],
259        mass_squared: [Atom; 4],
260        invariants: [Atom; 3],
261    ) -> Result<Self, SymbolicKinematicsError> {
262        let [s, t, u] = invariants;
263        let mut result = Self::new();
264        for i in 0..4 {
265            result = result.with_mass_squared(momenta[i], mass_squared[i].clone())?;
266        }
267        for (i, j, invariant, sign) in [
268            (0, 1, &s, 1),
269            (2, 3, &s, 1),
270            (0, 2, &t, -1),
271            (1, 3, &t, -1),
272            (0, 3, &u, -1),
273            (1, 2, &u, -1),
274        ] {
275            let value = Atom::num(sign) * (invariant - &mass_squared[i] - &mass_squared[j]) / 2;
276            result = result.with_scalar_product(momenta[i], momenta[j], value.expand())?;
277        }
278        Ok(result)
279    }
280
281    /// Expand a bilinear scalar product and apply the known assumptions.
282    ///
283    /// Single momentum names need no declaration. For sums and products, declare
284    /// the momentum names first; all remaining symbols are scalar coefficients.
285    pub fn scalar_product(
286        &self,
287        left: &Atom,
288        right: &Atom,
289    ) -> Result<Atom, SymbolicKinematicsError> {
290        let left = self.linear_terms(left)?;
291        let right = self.linear_terms(right)?;
292        let rep = Minkowski {}.new_rep(self.dimension);
293        let mut result = Atom::Zero;
294        for (p, a) in &left {
295            for (q, b) in &right {
296                let dot = rep.inner_product(p, q);
297                result += a * b * self.products.get(&dot).cloned().unwrap_or(dot);
298            }
299        }
300        Ok(result.expand())
301    }
302
303    /// Decompose a linear momentum into `(momentum name, scalar coefficient)` pairs.
304    ///
305    /// Single names need no declaration. For combinations, momentum names must
306    /// be declared and may not occur inside scalar coefficient functions or powers.
307    /// Native exact expression-field grouping retains Gaussian and symbolic
308    /// coefficients without statistical zero testing.
309    pub fn linear_terms(
310        &self,
311        momentum: &Atom,
312    ) -> Result<Vec<(Atom, Atom)>, SymbolicKinematicsError> {
313        if momentum.is_zero() {
314            return Ok(Vec::new());
315        }
316        if matches!(momentum.as_view(), AtomView::Var(_) | AtomView::Fun(_)) {
317            return Ok(vec![(momentum.clone(), Atom::one())]);
318        }
319        let invalid = || SymbolicKinematicsError::NonlinearMomentum(momentum.clone());
320        let variables = self.momenta.iter().collect::<Vec<_>>();
321        let requested = variables
322            .iter()
323            .map(|v| PolyVariable::try_from((*v).clone()))
324            .collect::<Result<Vec<_>, _>>()
325            .map_err(|_| invalid())?;
326        let field = AtomField {
327            statistical_zero_test: false,
328            cancel_check_on_division: false,
329            custom_normalization: None,
330        };
331        let polynomial = momentum
332            .try_to_polynomial::<_, i32>(&field, Some(Arc::new(requested.clone())))
333            .map_err(|_| invalid())?;
334        // Conversion may normalize rational powers or extend the variable map.
335        // Keep the literal declared momentum coordinates, or reject the input.
336        let indices = requested
337            .iter()
338            .map(|v| {
339                polynomial
340                    .variables()
341                    .iter()
342                    .position(|p| p == v)
343                    .ok_or_else(invalid)
344            })
345            .collect::<Result<Vec<_>, _>>()?;
346        let mut terms = Vec::new();
347        for (exponents, coefficient) in polynomial.to_multivariate_polynomial_list(&indices, true) {
348            let mut powers = indices
349                .iter()
350                .enumerate()
351                .filter(|(_, index)| exponents[**index] != 0);
352            let key = match (powers.next(), powers.next()) {
353                (Some((position, index)), None) if exponents[*index] == 1 => variables[position],
354                _ => return Err(invalid()),
355            };
356            let coefficient = coefficient.flatten(false);
357            if variables.iter().any(|p| coefficient.contains(p.as_view())) {
358                return Err(invalid());
359            }
360            terms.push((key.clone(), coefficient));
361        }
362        terms.sort_by(|(left, _), (right, _)| left.cmp(right));
363        Ok(terms)
364    }
365
366    /// Substitute known dot products and compact metric contractions.
367    ///
368    /// Substitutions are simultaneous: a value containing another assumed
369    /// scalar product is retained verbatim. This avoids recursive rewrite cycles.
370    pub fn apply(&self, expression: &Atom) -> Atom {
371        // Exact atoms, rather than wildcard patterns, keep assumptions local to
372        // their momenta and preserve unknown scalar products.
373        expression.replace_map(|view, _, output| {
374            if let Some(value) = self.products.get(&view.to_owned()) {
375                **output = value.clone();
376            }
377        })
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384    use symbolica::parse;
385
386    #[test]
387    fn scalar_value_mapping_preserves_all_roles_and_equal_assumptions() {
388        let [p, q, auxiliary, unassigned] = [
389            parse!("scalar_map::p"),
390            parse!("scalar_map::q"),
391            parse!("scalar_map::auxiliary"),
392            parse!("scalar_map::unassigned"),
393        ];
394        let dimension = parse!("scalar_map::D");
395        let original = Kinematics::in_dimension(&dimension)
396            .unwrap()
397            .with_momenta([unassigned.clone()])
398            .unwrap()
399            .with_scalar_product(&p, &q, parse!("scalar_map::s"))
400            .unwrap()
401            .with_mass_squared(&auxiliary, parse!("scalar_map::s"))
402            .unwrap()
403            .with_scalar_product(&p, &auxiliary, parse!("scalar_map::t"))
404            .unwrap();
405        let mut calls = Vec::new();
406        let mapped = original
407            .try_map_scalar_values(|value| {
408                calls.push(value.clone());
409                Ok::<_, ()>(Atom::num(calls.len() as i64))
410            })
411            .unwrap();
412        let unique = original.products.values().cloned().collect::<BTreeSet<_>>();
413        assert_eq!(calls, unique.into_iter().collect::<Vec<_>>());
414        assert_eq!(calls.len(), 2);
415        assert_eq!(mapped.dimension(), original.dimension());
416        assert_eq!(
417            mapped.momenta().collect::<Vec<_>>(),
418            original.momenta().collect::<Vec<_>>()
419        );
420        assert!(mapped.momenta().any(|momentum| momentum == &unassigned));
421        assert_eq!(
422            mapped.products.keys().collect::<Vec<_>>(),
423            original.products.keys().collect::<Vec<_>>()
424        );
425        assert_eq!(mapped.scalar_assumptions().len(), 6);
426        let pq = mapped.scalar_product(&p, &q).unwrap();
427        assert_eq!(pq, mapped.scalar_product(&q, &p).unwrap());
428        assert_eq!(pq, mapped.scalar_product(&auxiliary, &auxiliary).unwrap());
429        let rep = Minkowski {}.new_rep(original.dimension());
430        let metric = function!(
431            ETS.metric,
432            rep.vector(p.as_view(), []),
433            rep.vector(q.as_view(), [])
434        );
435        assert_eq!(mapped.apply(&metric), pq);
436        assert_eq!(
437            original.scalar_product(&p, &q).unwrap(),
438            parse!("scalar_map::s")
439        );
440        // Declarations without assumptions still govern symbolic linear terms.
441        assert!(mapped.linear_terms(&(&p + &unassigned)).is_ok());
442        let foreign = parse!("scalar_map::undeclared");
443        assert!(mapped.linear_terms(&(&p + &foreign)).is_err());
444    }
445
446    #[test]
447    fn scalar_value_mapping_failure_leaves_original_owner_intact() {
448        let [p, q] = [
449            parse!("scalar_map_failure::p"),
450            parse!("scalar_map_failure::q"),
451        ];
452        let original = Kinematics::new()
453            .with_mass_squared(&p, Atom::num(3))
454            .unwrap()
455            .with_mass_squared(&q, Atom::num(5))
456            .unwrap();
457        let before = original.clone();
458        let mut calls = 0;
459        let result = original.try_map_scalar_values(|_| {
460            calls += 1;
461            if calls == 2 {
462                Err("conversion refused")
463            } else {
464                Ok(Atom::Zero)
465            }
466        });
467        assert!(matches!(result, Err("conversion refused")));
468        assert_eq!(calls, 2);
469        assert_eq!(original.dimension, before.dimension);
470        assert_eq!(original.momenta, before.momenta);
471        assert_eq!(original.products, before.products);
472        let retry = original
473            .try_map_scalar_values(|value| Ok::<_, ()>(value.clone()))
474            .unwrap();
475        assert_eq!(retry.products, before.products);
476    }
477
478    #[test]
479    fn scalar_value_mapping_preserves_original_float_precision_verbatim() {
480        use numerica::domains::{float::Float, rational::Rational};
481        let high = Float::parse("0.1000000000000000000000000000000000000001", Some(192)).unwrap();
482        let low = Float::with_val(53, 0.1f64);
483        assert_ne!(
484            high.try_to_rational().unwrap(),
485            low.try_to_rational().unwrap()
486        );
487        let half_low = Atom::num(Float::with_val(53, 0.5));
488        let half_high = Atom::num(Float::with_val(192, 0.5));
489        assert_ne!(half_low, half_high);
490        let values = [
491            Atom::num(high),
492            Atom::num(low),
493            Atom::num(f64::from_bits(1)),
494            half_low,
495            half_high,
496        ];
497        let mut original = Kinematics::new();
498        for (index, value) in values.iter().enumerate() {
499            let momentum = function!(
500                symbolica::symbol!("scalar_map_float::p"),
501                Atom::num(index as i64)
502            );
503            original = original
504                .with_mass_squared(&momentum, value.clone())
505                .unwrap();
506        }
507        let mut seen = BTreeSet::new();
508        let identity = original
509            .try_map_scalar_values(|value| {
510                seen.insert(value.clone());
511                Ok::<_, ()>(value.clone())
512            })
513            .unwrap();
514        assert_eq!(seen, values.into_iter().collect::<BTreeSet<_>>());
515        assert_eq!(identity.products, original.products);
516        assert!(
517            original
518                .scalar_assumptions()
519                .all(|(_, value)| Rational::try_from(value.as_view()).is_err())
520        );
521    }
522
523    #[test]
524    fn scalar_value_mapping_is_simultaneous_and_allows_collapsed_values() {
525        let [p, q] = [
526            parse!("scalar_map_simultaneous::p"),
527            parse!("scalar_map_simultaneous::q"),
528        ];
529        let rep = Minkowski {}.new_rep(4);
530        let pp = rep.inner_product(&p, &p);
531        let qq = rep.inner_product(&q, &q);
532        let original = Kinematics::new()
533            .with_mass_squared(&p, Atom::num(3))
534            .unwrap()
535            .with_mass_squared(&q, Atom::num(5))
536            .unwrap();
537        let mapped = original
538            .try_map_scalar_values(|_| Ok::<_, ()>(qq.clone()))
539            .unwrap();
540        assert_eq!(mapped.apply(&pp), qq);
541        assert_eq!(mapped.scalar_product(&p, &p).unwrap(), qq);
542        assert_eq!(mapped.scalar_product(&q, &q).unwrap(), qq);
543        let empty = Kinematics::new()
544            .try_map_scalar_values(|_| -> Result<Atom, ()> { panic!("empty context") })
545            .unwrap();
546        assert_eq!(empty.scalar_assumptions().len(), 0);
547        assert_eq!(empty.momenta().len(), 0);
548    }
549
550    #[test]
551    fn two_body_measure_has_physical_normalization_and_mass_symmetry() {
552        let p = parse!("p");
553        let q = parse!("q");
554        let pi = Atom::var(symbolica::atom::Symbol::PI);
555        let kin = Kinematics::new()
556            .with_mass_squared(&p, Atom::num(9))
557            .unwrap()
558            .with_mass_squared(&q, Atom::num(25))
559            .unwrap()
560            .with_scalar_product(&p, &q, Atom::num(113))
561            .unwrap();
562        assert_eq!(kin.flux(&p, Some(&q)).unwrap(), Atom::num(448));
563        assert_eq!(kin.flux(&p, None).unwrap(), Atom::num(6));
564        let measure = kin.two_body_phase_space(&p, &q).unwrap();
565        assert!(
566            (measure.clone() * Atom::num(260) * pi.clone().pow(2) - Atom::num(7))
567                .expand()
568                .is_zero()
569        );
570        assert_eq!(measure, kin.two_body_phase_space(&q, &p).unwrap());
571        let threshold = kin.with_scalar_product(&p, &q, Atom::num(15)).unwrap();
572        assert!(threshold.two_body_phase_space(&p, &q).unwrap().is_zero());
573        assert!(
574            Kinematics::in_dimension(&parse!("D"))
575                .unwrap()
576                .two_body_phase_space(&p, &q)
577                .is_err()
578        );
579        // Momentum names also work without assumptions or prior declarations.
580        assert!(Kinematics::new().two_body_phase_space(&p, &q).is_ok());
581    }
582
583    #[test]
584    fn dalitz_density_has_massless_volume_and_permutation_symmetry() {
585        let [p, q, r, s, s12, s23] = [
586            parse!("p"),
587            parse!("q"),
588            parse!("r"),
589            parse!("s"),
590            parse!("s12"),
591            parse!("s23"),
592        ];
593        let mut kin = Kinematics::new();
594        for momentum in [&p, &q, &r] {
595            kin = kin.with_mass_squared(momentum, Atom::Zero).unwrap();
596        }
597        kin = kin
598            .with_scalar_product(&p, &q, &s12 / 2)
599            .unwrap()
600            .with_scalar_product(&q, &r, &s23 / 2)
601            .unwrap()
602            .with_scalar_product(&p, &r, (&s - &s12 - &s23) / 2)
603            .unwrap();
604        let density = kin.three_body_phase_space(&p, &q, &r).unwrap();
605        let pi = Atom::var(symbolica::atom::Symbol::PI);
606        // The massless Dalitz triangle has area s^2/2. Its integrated volume
607        // also follows from two sequential two-body phase spaces.
608        assert!(
609            (density.clone() * s.clone().pow(2) / 2 - &s / (Atom::num(256) * pi.clone().pow(3)))
610                .together()
611                .is_zero()
612        );
613        assert_eq!(density, kin.three_body_phase_space(&r, &p, &q).unwrap());
614        let massive = kin.clone().with_mass_squared(&p, Atom::num(9)).unwrap();
615        assert!(
616            (massive.three_body_phase_space(&p, &q, &r).unwrap()
617                * (s + Atom::num(9))
618                * Atom::num(128)
619                * pi.pow(3)
620                - Atom::one())
621            .together()
622            .is_zero()
623        );
624        assert!(matches!(
625            Kinematics::in_dimension(&parse!("D"))
626                .unwrap()
627                .three_body_phase_space(&p, &q, &r),
628            Err(SymbolicKinematicsError::PhaseSpaceDimension)
629        ));
630        assert!(kin.three_body_phase_space(&(&p * &q), &q, &r).is_err());
631    }
632
633    #[test]
634    fn bilinear_momenta_use_symbolica_coefficients() {
635        let p = parse!("Q(1)");
636        let q = parse!("Q(2)");
637        let a = parse!("a");
638        let b = parse!("b");
639        let kin = Kinematics::new()
640            .with_scalar_product(&p, &p, parse!("m2"))
641            .unwrap()
642            .with_scalar_product(&q, &q, Atom::Zero)
643            .unwrap()
644            .with_scalar_product(&p, &q, parse!("s/2"))
645            .unwrap();
646        let result = kin
647            .scalar_product(&(&a * &p + &b * &q), &(&p - &q))
648            .unwrap();
649        let expected = parse!("a*m2 + (b-a)*s/2");
650        assert!((result - expected).expand().is_zero());
651        assert!(kin.scalar_product(&Atom::Zero, &p).unwrap().is_zero());
652        assert!(kin.scalar_product(&(&p * &q), &p).is_err());
653        assert!(kin.scalar_product(&parse!("Q(1)/(1+Q(2))"), &p).is_err());
654        assert!(kin.scalar_product(&(&p + Atom::one()), &p).is_err());
655        assert!(Kinematics::new().with_momenta([&p + &q]).is_err());
656    }
657
658    #[test]
659    fn tiny_expanded_symbolic_momentum_coefficients_are_exact() {
660        let p = parse!("p");
661        let k = parse!("k");
662        let kin = Kinematics::new()
663            .with_momenta([p.clone(), k.clone()])
664            .unwrap();
665        for coefficient in [
666            parse!("(a+b)/10^1000"),
667            parse!("(a+b)*10^1000"),
668            parse!("𝑖*(a+b)/10^1000"),
669            parse!("(1+𝑖)*(sin(a)+cos(b))/(c+d)"),
670        ] {
671            let expected = &coefficient * kin.scalar_product(&k, &p).unwrap()
672                + kin.scalar_product(&p, &p).unwrap();
673            for momentum in [&coefficient * &k + &p, (&coefficient * &k + &p).expand()] {
674                let actual = kin.scalar_product(&momentum, &p).unwrap();
675                assert!((actual - &expected).together().is_zero());
676                let terms = kin
677                    .linear_terms(&momentum)
678                    .unwrap()
679                    .into_iter()
680                    .collect::<BTreeMap<_, _>>();
681                assert_eq!(terms.len(), 2);
682                assert!((&terms[&k] - &coefficient).together().is_zero());
683                assert_eq!(terms[&p], Atom::one());
684            }
685        }
686        for invalid in [
687            parse!("p+sin(k)*p/10^1000"),
688            parse!("p+k^2/10^1000"),
689            parse!("p+k^(1/2)/10^1000"),
690            parse!("p+k^(-1)/10^1000"),
691            parse!("p+k/(1+p)"),
692        ] {
693            assert!(matches!(
694                kin.linear_terms(&invalid),
695                Err(SymbolicKinematicsError::NonlinearMomentum(_))
696            ));
697        }
698    }
699
700    #[test]
701    fn declarations_expand_unknown_products_without_global_assumptions() {
702        let p = parse!("p");
703        let q = parse!("q");
704        let kin = Kinematics::new()
705            .with_momenta([p.clone(), q.clone()])
706            .unwrap();
707        let difference = kin.scalar_product(&(&p + &q), &(&p - &q)).unwrap();
708        let expected = kin.scalar_product(&p, &p).unwrap() - kin.scalar_product(&q, &q).unwrap();
709        assert_eq!(difference, expected);
710        assert!(Kinematics::new().scalar_product(&(&p + &q), &p).is_err());
711    }
712
713    #[test]
714    fn unequal_mass_mandelstam_respects_momentum_conservation() {
715        let p = [parse!("p1"), parse!("p2"), parse!("p3"), parse!("p4")];
716        let masses = [
717            parse!("m1sq"),
718            parse!("m2sq"),
719            parse!("m3sq"),
720            parse!("m4sq"),
721        ];
722        let s = parse!("s");
723        let t = parse!("t");
724        let u = masses.iter().cloned().sum::<Atom>() - &s - &t;
725        let kin = Kinematics::mandelstam(
726            p.each_ref(),
727            masses.clone(),
728            [s.clone(), t.clone(), u.clone()],
729        )
730        .unwrap();
731        for i in 0..4 {
732            assert_eq!(kin.scalar_product(&p[i], &p[i]).unwrap(), masses[i]);
733            let conserved = kin.scalar_product(&p[i], &p[0]).unwrap()
734                + kin.scalar_product(&p[i], &p[1]).unwrap()
735                - kin.scalar_product(&p[i], &p[2]).unwrap()
736                - kin.scalar_product(&p[i], &p[3]).unwrap();
737            assert!(conserved.expand().is_zero(), "{conserved}");
738        }
739        assert!(
740            (kin.scalar_product(&p[0], &p[1]).unwrap() * 2 + &masses[0] + &masses[1] - s)
741                .expand()
742                .is_zero()
743        );
744        assert!(
745            (&masses[0] + &masses[2] - kin.scalar_product(&p[0], &p[2]).unwrap() * 2 - t)
746                .expand()
747                .is_zero()
748        );
749        assert!(
750            (&masses[0] + &masses[3] - kin.scalar_product(&p[0], &p[3]).unwrap() * 2 - u)
751                .expand()
752                .is_zero()
753        );
754    }
755
756    #[test]
757    fn substitutions_are_scoped_symmetric_and_simultaneous() {
758        let rep = Minkowski {}.new_rep(4);
759        let p = parse!("p");
760        let q = parse!("q");
761        let r = parse!("r");
762        let pq = rep.inner_product(&p, &q);
763        let qr = rep.inner_product(&q, &r);
764        let kin = Kinematics::new()
765            .with_scalar_product(&p, &q, qr.clone())
766            .unwrap()
767            .with_scalar_product(&q, &r, Atom::num(7))
768            .unwrap();
769        assert_eq!(kin.scalar_product(&q, &p).unwrap(), qr);
770        assert_eq!(kin.apply(&pq), qr);
771        assert_eq!(Kinematics::new().apply(&pq), pq);
772        let shorthand = function!(
773            ETS.metric,
774            rep.vector(p.as_view(), []),
775            rep.vector(q.as_view(), [])
776        );
777        assert_eq!(kin.apply(&shorthand), qr);
778        let unknown = rep.inner_product(&p, &r);
779        assert_eq!(kin.apply(&unknown), unknown);
780    }
781
782    #[test]
783    fn symbolic_dimensions_do_not_mix_with_four_dimensions() {
784        let d = parse!("D");
785        let p = parse!("p");
786        let kin = Kinematics::in_dimension(&d)
787            .unwrap()
788            .with_mass_squared(&p, Atom::num(7))
789            .unwrap();
790        assert_eq!(kin.scalar_product(&p, &p).unwrap(), Atom::num(7));
791        let four_dimensional = Kinematics::new().scalar_product(&p, &p).unwrap();
792        assert_eq!(kin.apply(&four_dimensional), four_dimensional);
793        assert!(Kinematics::in_dimension(&parse!("4-2*eps")).is_err());
794    }
795}