Skip to main content

feynkit_kinematics/
momentum.rs

1use std::{
2    fmt::{Display, LowerExp},
3    ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign},
4};
5
6use numerica::domains::float::FloatLike;
7use serde::{Deserialize, Serialize};
8
9use crate::KinematicScalar;
10
11const LARGE_RAPIDITY_SENTINEL: usize = 100_000;
12
13/// The temporal component of a four-momentum.
14#[repr(transparent)]
15#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Hash, Serialize, Deserialize)]
16pub struct Energy<T> {
17    /// The energy value.
18    pub value: T,
19}
20
21impl<T> Energy<T> {
22    /// Wrap an energy value.
23    pub const fn new(value: T) -> Self {
24        Self { value }
25    }
26
27    /// Unwrap the energy value.
28    pub fn into_inner(self) -> T {
29        self.value
30    }
31
32    /// Transform the energy's scalar type.
33    pub fn map<U>(self, map: impl FnOnce(T) -> U) -> Energy<U> {
34        Energy::new(map(self.value))
35    }
36
37    /// Transform a borrowed energy value.
38    pub fn map_ref<U>(&self, map: impl FnOnce(&T) -> U) -> Energy<U> {
39        Energy::new(map(&self.value))
40    }
41}
42
43impl<T> From<T> for Energy<T> {
44    fn from(value: T) -> Self {
45        Self::new(value)
46    }
47}
48
49impl<T: Display> Display for Energy<T> {
50    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(formatter, "E: {}", self.value)
52    }
53}
54
55impl<T: LowerExp> LowerExp for Energy<T> {
56    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        write!(formatter, "E: {:e}", self.value)
58    }
59}
60
61impl<T> Add for Energy<T>
62where
63    T: Add<Output = T>,
64{
65    type Output = Self;
66
67    fn add(self, rhs: Self) -> Self::Output {
68        Self::new(self.value + rhs.value)
69    }
70}
71
72impl<T> AddAssign for Energy<T>
73where
74    T: AddAssign,
75{
76    fn add_assign(&mut self, rhs: Self) {
77        self.value += rhs.value;
78    }
79}
80
81impl<T> Sub for Energy<T>
82where
83    T: Sub<Output = T>,
84{
85    type Output = Self;
86
87    fn sub(self, rhs: Self) -> Self::Output {
88        Self::new(self.value - rhs.value)
89    }
90}
91
92impl<T> SubAssign for Energy<T>
93where
94    T: SubAssign,
95{
96    fn sub_assign(&mut self, rhs: Self) {
97        self.value -= rhs.value;
98    }
99}
100
101impl<T> Neg for Energy<T>
102where
103    T: Neg<Output = T>,
104{
105    type Output = Self;
106
107    fn neg(self) -> Self::Output {
108        Self::new(-self.value)
109    }
110}
111
112/// A Cartesian spatial momentum `(px, py, pz)`.
113#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Hash, Serialize, Deserialize)]
114pub struct ThreeMomentum<T> {
115    /// Momentum along the x-axis.
116    pub px: T,
117    /// Momentum along the y-axis.
118    pub py: T,
119    /// Momentum along the z-axis.
120    pub pz: T,
121}
122
123impl<T> ThreeMomentum<T> {
124    /// Construct a Cartesian spatial momentum.
125    pub const fn new(px: T, py: T, pz: T) -> Self {
126        Self { px, py, pz }
127    }
128
129    /// Transform the momentum's scalar type.
130    pub fn map<U>(self, mut map: impl FnMut(T) -> U) -> ThreeMomentum<U> {
131        ThreeMomentum::new(map(self.px), map(self.py), map(self.pz))
132    }
133
134    /// Transform borrowed components into another scalar type.
135    pub fn map_ref<U>(&self, mut map: impl FnMut(&T) -> U) -> ThreeMomentum<U> {
136        ThreeMomentum::new(map(&self.px), map(&self.py), map(&self.pz))
137    }
138
139    /// Borrow the components in Cartesian order.
140    pub fn components(&self) -> [&T; 3] {
141        [&self.px, &self.py, &self.pz]
142    }
143
144    /// Compute the Euclidean norm squared without restricting the scalar type to floats.
145    pub fn norm_squared(&self) -> T
146    where
147        T: Clone + Mul<Output = T> + Add<Output = T>,
148    {
149        self.px.clone() * self.px.clone()
150            + self.py.clone() * self.py.clone()
151            + self.pz.clone() * self.pz.clone()
152    }
153
154    /// Compute the Euclidean dot product.
155    pub fn dot(&self, rhs: &Self) -> T
156    where
157        T: Clone + Mul<Output = T> + Add<Output = T>,
158    {
159        self.px.clone() * rhs.px.clone()
160            + self.py.clone() * rhs.py.clone()
161            + self.pz.clone() * rhs.pz.clone()
162    }
163
164    /// Compute the Cartesian cross product.
165    pub fn cross(&self, rhs: &Self) -> Self
166    where
167        T: Clone + Mul<Output = T> + Sub<Output = T>,
168    {
169        Self {
170            px: self.py.clone() * rhs.pz.clone() - self.pz.clone() * rhs.py.clone(),
171            py: self.pz.clone() * rhs.px.clone() - self.px.clone() * rhs.pz.clone(),
172            pz: self.px.clone() * rhs.py.clone() - self.py.clone() * rhs.px.clone(),
173        }
174    }
175}
176
177impl<T: FloatLike> ThreeMomentum<T> {
178    /// Construct the zero vector retaining precision and derivative shape.
179    pub fn zero(representative: &T) -> Self {
180        let zero = representative.zero();
181        Self::new(zero.clone(), zero.clone(), zero)
182    }
183}
184
185impl<T: KinematicScalar> ThreeMomentum<T> {
186    /// Compute the Euclidean norm.
187    pub fn norm(&self) -> T {
188        self.norm_squared().sqrt()
189    }
190
191    /// Compute transverse momentum squared.
192    pub fn pt_squared(&self) -> T {
193        self.px.clone() * self.px.clone() + self.py.clone() * self.py.clone()
194    }
195
196    /// Compute transverse momentum.
197    pub fn pt(&self) -> T {
198        self.pt_squared().sqrt()
199    }
200
201    /// Return the azimuthal angle in `[0, 2*pi)`.
202    pub fn phi(&self) -> T {
203        let zero = self.px.zero();
204        let two_pi = self.px.pi() * self.px.from_usize(2);
205        let mut phi = self.py.atan2(&self.px);
206        if phi < zero {
207            phi += two_pi.clone();
208        }
209        if phi >= two_pi {
210            phi -= self.px.pi() * self.px.from_usize(2);
211        }
212        phi
213    }
214
215    /// Compute pseudorapidity, using a finite sentinel on the beam axis.
216    pub fn pseudorapidity(&self) -> T {
217        let pt = self.pt();
218        let zero = pt.zero();
219        if pt == zero {
220            let abs_pz = self.pz.norm();
221            if abs_pz == zero {
222                return zero;
223            }
224            let sentinel = abs_pz.from_usize(LARGE_RAPIDITY_SENTINEL) + abs_pz;
225            return if self.pz > self.pz.zero() {
226                sentinel
227            } else {
228                -sentinel
229            };
230        }
231
232        let theta = pt.atan2(&self.pz);
233        let two = theta.from_usize(2);
234        -(theta / two).tan().log()
235    }
236
237    /// Compute the wrapped absolute azimuthal separation in `[0, pi]`.
238    pub fn delta_phi(&self, rhs: &Self) -> T {
239        wrapped_delta_phi(self.phi(), rhs.phi())
240    }
241
242    /// Compute separation in pseudorapidity and azimuth.
243    pub fn delta_r(&self, rhs: &Self) -> T {
244        let delta_eta = self.pseudorapidity() - rhs.pseudorapidity();
245        let delta_phi = self.delta_phi(rhs);
246        (delta_eta.clone() * delta_eta + delta_phi.clone() * delta_phi).sqrt()
247    }
248
249    /// Compute the positive on-shell energy for this momentum and an optional mass.
250    pub fn on_shell_energy(&self, mass: Option<&T>) -> Energy<T> {
251        let mut energy_squared = self.norm_squared();
252        if let Some(mass) = mass {
253            energy_squared += mass.clone() * mass.clone();
254        }
255        Energy::new(energy_squared.sqrt())
256    }
257
258    /// Promote this spatial momentum to a positive-energy on-shell four-momentum.
259    pub fn on_shell(self, mass: Option<&T>) -> FourMomentum<T> {
260        let temporal = self.on_shell_energy(mass);
261        FourMomentum::new(temporal, self)
262    }
263}
264
265impl<T> From<[T; 3]> for ThreeMomentum<T> {
266    fn from([px, py, pz]: [T; 3]) -> Self {
267        Self::new(px, py, pz)
268    }
269}
270
271impl<T> From<ThreeMomentum<T>> for [T; 3] {
272    fn from(momentum: ThreeMomentum<T>) -> Self {
273        [momentum.px, momentum.py, momentum.pz]
274    }
275}
276
277impl<T> From<(T, T, T)> for ThreeMomentum<T> {
278    fn from((px, py, pz): (T, T, T)) -> Self {
279        Self::new(px, py, pz)
280    }
281}
282
283impl<T> From<ThreeMomentum<T>> for (T, T, T) {
284    fn from(momentum: ThreeMomentum<T>) -> Self {
285        (momentum.px, momentum.py, momentum.pz)
286    }
287}
288
289impl<T> IntoIterator for ThreeMomentum<T> {
290    type Item = T;
291    type IntoIter = std::array::IntoIter<T, 3>;
292
293    fn into_iter(self) -> Self::IntoIter {
294        [self.px, self.py, self.pz].into_iter()
295    }
296}
297
298impl<'a, T> IntoIterator for &'a ThreeMomentum<T> {
299    type Item = &'a T;
300    type IntoIter = std::array::IntoIter<&'a T, 3>;
301
302    fn into_iter(self) -> Self::IntoIter {
303        [&self.px, &self.py, &self.pz].into_iter()
304    }
305}
306
307impl<T> Add for ThreeMomentum<T>
308where
309    T: Add<Output = T>,
310{
311    type Output = Self;
312
313    fn add(self, rhs: Self) -> Self::Output {
314        Self::new(self.px + rhs.px, self.py + rhs.py, self.pz + rhs.pz)
315    }
316}
317
318impl<T> Add<&Self> for ThreeMomentum<T>
319where
320    T: for<'a> Add<&'a T, Output = T>,
321{
322    type Output = Self;
323
324    fn add(self, rhs: &Self) -> Self::Output {
325        Self::new(self.px + &rhs.px, self.py + &rhs.py, self.pz + &rhs.pz)
326    }
327}
328
329impl<T> AddAssign for ThreeMomentum<T>
330where
331    T: AddAssign,
332{
333    fn add_assign(&mut self, rhs: Self) {
334        self.px += rhs.px;
335        self.py += rhs.py;
336        self.pz += rhs.pz;
337    }
338}
339
340impl<T> Sub for ThreeMomentum<T>
341where
342    T: Sub<Output = T>,
343{
344    type Output = Self;
345
346    fn sub(self, rhs: Self) -> Self::Output {
347        Self::new(self.px - rhs.px, self.py - rhs.py, self.pz - rhs.pz)
348    }
349}
350
351impl<T> SubAssign for ThreeMomentum<T>
352where
353    T: SubAssign,
354{
355    fn sub_assign(&mut self, rhs: Self) {
356        self.px -= rhs.px;
357        self.py -= rhs.py;
358        self.pz -= rhs.pz;
359    }
360}
361
362impl<T> Neg for ThreeMomentum<T>
363where
364    T: Neg<Output = T>,
365{
366    type Output = Self;
367
368    fn neg(self) -> Self::Output {
369        Self::new(-self.px, -self.py, -self.pz)
370    }
371}
372
373impl<T> Neg for &ThreeMomentum<T>
374where
375    T: Clone + Neg<Output = T>,
376{
377    type Output = ThreeMomentum<T>;
378
379    fn neg(self) -> Self::Output {
380        ThreeMomentum::new(-self.px.clone(), -self.py.clone(), -self.pz.clone())
381    }
382}
383
384impl<T> Mul<T> for ThreeMomentum<T>
385where
386    T: Clone + Mul<Output = T>,
387{
388    type Output = Self;
389
390    fn mul(self, rhs: T) -> Self::Output {
391        Self::new(self.px * rhs.clone(), self.py * rhs.clone(), self.pz * rhs)
392    }
393}
394
395impl<T: Display> Display for ThreeMomentum<T> {
396    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
397        write!(
398            formatter,
399            "px: {}, py: {}, pz: {}",
400            self.px, self.py, self.pz
401        )
402    }
403}
404
405impl<T: LowerExp> LowerExp for ThreeMomentum<T> {
406    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407        write!(
408            formatter,
409            "px: {:e}, py: {:e}, pz: {:e}",
410            self.px, self.py, self.pz
411        )
412    }
413}
414
415/// A contravariant four-momentum `(E, px, py, pz)` with mostly-minus metric.
416#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Hash, Serialize, Deserialize)]
417pub struct FourMomentum<T> {
418    /// Temporal component.
419    pub temporal: Energy<T>,
420    /// Cartesian spatial component.
421    pub spatial: ThreeMomentum<T>,
422}
423
424impl<T> FourMomentum<T> {
425    /// Construct a four-momentum from temporal and spatial components.
426    pub const fn new(temporal: Energy<T>, spatial: ThreeMomentum<T>) -> Self {
427        Self { temporal, spatial }
428    }
429
430    /// Construct a four-momentum from `(E, px, py, pz)`.
431    pub const fn from_args(energy: T, px: T, py: T, pz: T) -> Self {
432        Self::new(Energy::new(energy), ThreeMomentum::new(px, py, pz))
433    }
434
435    /// Transform the momentum's scalar type.
436    pub fn map<U>(self, mut map: impl FnMut(T) -> U) -> FourMomentum<U> {
437        FourMomentum::from_args(
438            map(self.temporal.value),
439            map(self.spatial.px),
440            map(self.spatial.py),
441            map(self.spatial.pz),
442        )
443    }
444
445    /// Transform borrowed components into another scalar type.
446    pub fn map_ref<U>(&self, mut map: impl FnMut(&T) -> U) -> FourMomentum<U> {
447        FourMomentum::from_args(
448            map(&self.temporal.value),
449            map(&self.spatial.px),
450            map(&self.spatial.py),
451            map(&self.spatial.pz),
452        )
453    }
454
455    /// Borrow the components in `(E, px, py, pz)` order.
456    pub fn components(&self) -> [&T; 4] {
457        [
458            &self.temporal.value,
459            &self.spatial.px,
460            &self.spatial.py,
461            &self.spatial.pz,
462        ]
463    }
464
465    /// Compute the Minkowski scalar product with mostly-minus metric.
466    pub fn dot(&self, rhs: &Self) -> T
467    where
468        T: Clone + Mul<Output = T> + Add<Output = T> + Sub<Output = T>,
469    {
470        self.temporal.value.clone() * rhs.temporal.value.clone() - self.spatial.dot(&rhs.spatial)
471    }
472
473    /// Compute invariant mass squared with mostly-minus metric.
474    pub fn mass_squared(&self) -> T
475    where
476        T: Clone + Mul<Output = T> + Add<Output = T> + Sub<Output = T>,
477    {
478        self.dot(self)
479    }
480}
481
482impl<T: FloatLike> FourMomentum<T> {
483    /// Construct the zero four-vector retaining precision and derivative shape.
484    pub fn zero(representative: &T) -> Self {
485        let zero = representative.zero();
486        Self::from_args(zero.clone(), zero.clone(), zero.clone(), zero)
487    }
488}
489
490impl<T: KinematicScalar> FourMomentum<T> {
491    /// Initial-state denominator: `2 E` for decay or invariant scattering flux.
492    ///
493    /// The one-particle value is frame dependent. Two future-directed on-shell
494    /// momenta give `4 sqrt((p1.p2)^2 - p1^2 p2^2)`. Unit conversion, averages
495    /// and phase-space symmetry factors are not included.
496    pub fn flux(&self, other: Option<&Self>) -> T {
497        let flux = match other {
498            Some(other) => crate::InitialStateFlux::Scattering {
499                momentum_dot: self.dot(other),
500                mass_squared_product: self.mass_squared() * other.mass_squared(),
501            },
502            None => crate::InitialStateFlux::Decay {
503                energy: self.temporal.value.clone(),
504            },
505        };
506        flux.denominator(|value| value.sqrt())
507    }
508
509    /// Return the positive square root of invariant mass squared.
510    pub fn mass(&self) -> T {
511        self.mass_squared().sqrt()
512    }
513
514    /// Compute transverse momentum squared.
515    pub fn pt_squared(&self) -> T {
516        self.spatial.pt_squared()
517    }
518
519    /// Compute transverse momentum.
520    pub fn pt(&self) -> T {
521        self.spatial.pt()
522    }
523
524    /// Return the azimuthal angle in `[0, 2*pi)`.
525    pub fn phi(&self) -> T {
526        self.spatial.phi()
527    }
528
529    /// Compute pseudorapidity from the spatial momentum.
530    pub fn pseudorapidity(&self) -> T {
531        self.spatial.pseudorapidity()
532    }
533
534    /// Compute rapidity, using a finite sentinel for a massless beam-axis momentum.
535    pub fn rapidity(&self) -> T {
536        self.rapidity_with_pt_squared(&self.pt_squared())
537    }
538
539    pub(crate) fn rapidity_with_pt_squared(&self, pt_squared: &T) -> T {
540        let zero = self.temporal.value.zero();
541        let pz = self.spatial.pz.clone();
542        let abs_pz = pz.norm();
543        let energy = self.temporal.value.clone();
544
545        if *pt_squared == zero.clone() && energy == abs_pz {
546            let sentinel = abs_pz.from_usize(LARGE_RAPIDITY_SENTINEL) + abs_pz;
547            return if pz >= zero { sentinel } else { -sentinel };
548        }
549
550        let spatial_norm_squared = self.spatial.norm_squared();
551        let mass_squared = energy.clone() * energy.clone() - spatial_norm_squared;
552        let effective_mass_squared = if mass_squared < zero {
553            self.temporal.value.zero()
554        } else {
555            mass_squared
556        };
557        let energy_plus_abs_pz = energy + abs_pz;
558        let two = energy_plus_abs_pz.from_usize(2);
559        let half = energy_plus_abs_pz.one() / two;
560        let denominator = energy_plus_abs_pz.clone() * energy_plus_abs_pz;
561        let mut rapidity =
562            ((pt_squared.clone() + effective_mass_squared) / denominator).log() * half;
563        if pz > self.spatial.pz.zero() {
564            rapidity = -rapidity;
565        }
566        rapidity
567    }
568
569    /// Compute the wrapped absolute azimuthal separation in `[0, pi]`.
570    pub fn delta_phi(&self, rhs: &Self) -> T {
571        self.spatial.delta_phi(&rhs.spatial)
572    }
573
574    /// Compute separation in rapidity and azimuth, as used by hadron-collider jets.
575    pub fn delta_r(&self, rhs: &Self) -> T {
576        let delta_rapidity = self.rapidity() - rhs.rapidity();
577        let delta_phi = self.delta_phi(rhs);
578        (delta_rapidity.clone() * delta_rapidity + delta_phi.clone() * delta_phi).sqrt()
579    }
580}
581
582impl<T> From<[T; 4]> for FourMomentum<T> {
583    fn from([energy, px, py, pz]: [T; 4]) -> Self {
584        Self::from_args(energy, px, py, pz)
585    }
586}
587
588impl<T> From<FourMomentum<T>> for [T; 4] {
589    fn from(momentum: FourMomentum<T>) -> Self {
590        [
591            momentum.temporal.value,
592            momentum.spatial.px,
593            momentum.spatial.py,
594            momentum.spatial.pz,
595        ]
596    }
597}
598
599impl<T> From<(T, T, T, T)> for FourMomentum<T> {
600    fn from((energy, px, py, pz): (T, T, T, T)) -> Self {
601        Self::from_args(energy, px, py, pz)
602    }
603}
604
605impl<T> From<FourMomentum<T>> for (T, T, T, T) {
606    fn from(momentum: FourMomentum<T>) -> Self {
607        (
608            momentum.temporal.value,
609            momentum.spatial.px,
610            momentum.spatial.py,
611            momentum.spatial.pz,
612        )
613    }
614}
615
616impl<T> IntoIterator for FourMomentum<T> {
617    type Item = T;
618    type IntoIter = std::array::IntoIter<T, 4>;
619
620    fn into_iter(self) -> Self::IntoIter {
621        <[T; 4]>::from(self).into_iter()
622    }
623}
624
625impl<'a, T> IntoIterator for &'a FourMomentum<T> {
626    type Item = &'a T;
627    type IntoIter = std::array::IntoIter<&'a T, 4>;
628
629    fn into_iter(self) -> Self::IntoIter {
630        self.components().into_iter()
631    }
632}
633
634impl<T> Add for FourMomentum<T>
635where
636    T: Add<Output = T>,
637{
638    type Output = Self;
639
640    fn add(self, rhs: Self) -> Self::Output {
641        Self::new(self.temporal + rhs.temporal, self.spatial + rhs.spatial)
642    }
643}
644
645impl<T> Add<&Self> for FourMomentum<T>
646where
647    T: for<'a> Add<&'a T, Output = T>,
648{
649    type Output = Self;
650
651    fn add(self, rhs: &Self) -> Self::Output {
652        Self::from_args(
653            self.temporal.value + &rhs.temporal.value,
654            self.spatial.px + &rhs.spatial.px,
655            self.spatial.py + &rhs.spatial.py,
656            self.spatial.pz + &rhs.spatial.pz,
657        )
658    }
659}
660
661impl<T> AddAssign for FourMomentum<T>
662where
663    T: AddAssign,
664{
665    fn add_assign(&mut self, rhs: Self) {
666        self.temporal += rhs.temporal;
667        self.spatial += rhs.spatial;
668    }
669}
670
671impl<T> Sub for FourMomentum<T>
672where
673    T: Sub<Output = T>,
674{
675    type Output = Self;
676
677    fn sub(self, rhs: Self) -> Self::Output {
678        Self::new(self.temporal - rhs.temporal, self.spatial - rhs.spatial)
679    }
680}
681
682impl<T> SubAssign for FourMomentum<T>
683where
684    T: SubAssign,
685{
686    fn sub_assign(&mut self, rhs: Self) {
687        self.temporal -= rhs.temporal;
688        self.spatial -= rhs.spatial;
689    }
690}
691
692impl<T> Neg for FourMomentum<T>
693where
694    T: Neg<Output = T>,
695{
696    type Output = Self;
697
698    fn neg(self) -> Self::Output {
699        Self::new(-self.temporal, -self.spatial)
700    }
701}
702
703impl<T> Neg for &FourMomentum<T>
704where
705    T: Clone + Neg<Output = T>,
706{
707    type Output = FourMomentum<T>;
708
709    fn neg(self) -> Self::Output {
710        FourMomentum::from_args(
711            -self.temporal.value.clone(),
712            -self.spatial.px.clone(),
713            -self.spatial.py.clone(),
714            -self.spatial.pz.clone(),
715        )
716    }
717}
718
719impl<T> Mul<T> for FourMomentum<T>
720where
721    T: Clone + Mul<Output = T>,
722{
723    type Output = Self;
724
725    fn mul(self, rhs: T) -> Self::Output {
726        Self::from_args(
727            self.temporal.value * rhs.clone(),
728            self.spatial.px * rhs.clone(),
729            self.spatial.py * rhs.clone(),
730            self.spatial.pz * rhs,
731        )
732    }
733}
734
735impl<T: Display> Display for FourMomentum<T> {
736    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
737        write!(formatter, "{}, {}", self.temporal, self.spatial)
738    }
739}
740
741impl<T: LowerExp> LowerExp for FourMomentum<T> {
742    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
743        write!(formatter, "{:e}, {:e}", self.temporal, self.spatial)
744    }
745}
746
747pub(crate) fn wrapped_delta_phi<T: KinematicScalar>(lhs: T, rhs: T) -> T {
748    let pi = lhs.pi();
749    let two_pi = pi.clone() * pi.from_usize(2);
750    let delta = (lhs - rhs).norm();
751    if delta > pi { two_pi - delta } else { delta }
752}
753
754#[cfg(test)]
755mod tests {
756    use numerica::domains::{
757        dual::{DualNumberStructure, HyperDual},
758        float::{Complex, DoubleFloat, Float, FloatLike, Real, RealLike},
759    };
760
761    use super::*;
762    use static_dual::Dual;
763
764    // Numerica implements static Dual division through inversion and multiplication.
765    #[allow(clippy::suspicious_arithmetic_impl, clippy::suspicious_op_assign_impl)]
766    mod static_dual {
767        numerica::create_hyperdual_single_derivative!(Dual, 2);
768    }
769
770    fn assert_close(lhs: f64, rhs: f64) {
771        assert!((lhs - rhs).abs() < 1.0e-12, "{lhs} != {rhs}");
772    }
773
774    #[test]
775    fn on_shell_construction_preserves_mass() {
776        let spatial = ThreeMomentum::new(3.0, 4.0, 0.0);
777        let momentum = spatial.on_shell(Some(&12.0));
778
779        assert_close(momentum.temporal.value, 13.0);
780        assert_close(momentum.mass_squared(), 144.0);
781    }
782
783    #[test]
784    fn azimuthal_separation_wraps_at_two_pi() {
785        let epsilon = 0.01_f64;
786        let left = ThreeMomentum::new(epsilon.cos(), epsilon.sin(), 0.0);
787        let angle = 0.0_f64.pi() * 2.0 - epsilon;
788        let right = ThreeMomentum::new(angle.cos(), angle.sin(), 0.0);
789
790        assert_close(left.delta_phi(&right), 2.0 * epsilon);
791    }
792
793    #[test]
794    fn vector_arithmetic_supports_symbolica_high_precision_scalars() {
795        let zero = DoubleFloat::default();
796        let one = zero.one();
797        let momentum = FourMomentum::from_args(
798            one.from_usize(5),
799            one.from_usize(3),
800            one.from_usize(4),
801            zero,
802        );
803
804        assert_close(momentum.mass_squared().to_f64(), 0.0);
805    }
806
807    #[test]
808    fn zero_momenta_preserve_complex_precision_and_dual_shape() {
809        let value = Complex::new(Float::with_val(256, 2), Float::with_val(256, 3));
810        let complex_zero = FourMomentum::zero(&value);
811        for component in complex_zero.components() {
812            assert!(component.is_fully_zero());
813            assert_eq!(component.get_precision(), 256);
814        }
815
816        let dynamic = HyperDual::from_values(
817            vec![vec![0, 0], vec![1, 0], vec![0, 1], vec![1, 1]],
818            vec![value.clone(); 4],
819        );
820        let dynamic_zero = FourMomentum::zero(&dynamic);
821        for component in dynamic_zero.components() {
822            assert_eq!(component.get_shape(), dynamic.get_shape());
823            assert!(component.values.iter().all(FloatLike::is_fully_zero));
824            assert!(
825                component
826                    .values
827                    .iter()
828                    .all(|value| value.get_precision() == 256)
829            );
830        }
831
832        let fixed = Dual {
833            values: [value.clone(), value.one(), value.zero()],
834        };
835        let fixed_zero = ThreeMomentum::zero(&fixed);
836        for component in [&fixed_zero.px, &fixed_zero.py, &fixed_zero.pz] {
837            assert!(component.values.iter().all(FloatLike::is_fully_zero));
838            assert!(
839                component
840                    .values
841                    .iter()
842                    .all(|value| value.get_precision() == 256)
843            );
844        }
845        let momentum = FourMomentum::new(Energy::new(fixed), fixed_zero);
846        let square = momentum.mass_squared();
847        assert_eq!(
848            square.values[0],
849            Complex::new(Float::with_val(256, -5), Float::with_val(256, 12))
850        );
851        assert_eq!(
852            square.values[1],
853            Complex::new(Float::with_val(256, 4), Float::with_val(256, 6))
854        );
855        assert!(square.values[2].is_fully_zero());
856    }
857}